I was working through Chen Tian’s Programming Rust course and building the sample code in Docker. Every run spent time refreshing the crates.io index—even when Cargo.toml had not changed.
There has to be a way to cache that. This is the path I took (including what did not work).
Host-mounted cache — failed
One approach: point CARGO_HOME at a directory on the host so the crate index persists.
1 | docker run --rm --user "$(id -u)":"$(id -g)" -v "$PWD":/usr/src/myapp -w /usr/src/myapp -e CARGO_HOME=".cargo" rust cargo run |
That run blew up:
1 | Compiling libc v0.2.107 |
Digging in, it looks like an environment mismatch: pkg-config and native libs do not line up when you mix host paths with the container userspace. References: Rust cross-compile to Darwin troubleshooting and Stack Overflow: Docker image with a Rust binary.
Image layer cache — worked
This Stack Overflow answer (cache-rust-dependencies-with-docker-build) is the trick that stuck.
Idea: dependency layers should stay valid while Cargo.toml is stable. A docker build that copies application source invalidates cache whenever any file changes.
So compile dependencies against a throwaway main, cache that layer, swap in real sources, then build again—fast iteration and warm deps.
Dockerfile:
1 | FROM rust |
Build arg SRC_DIR lets one Dockerfile serve multiple crates.
Matching Cargo.toml bin section:
1 | [[bin]] |
Build and run in one shot:
1 | # run.sh |
Example:
1 | eg: |
Dependency downloads stay cached; back to studying.
Sample repo: rust-koan.

Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
