How to properly share cargo registry with docker containers?

I'd like to share a project repo with a container via a local volume in order to build and run code in it. And I'd like to share cargo's dependency cache, otherwise deps will be redownloaded and rebuilt quite a lot.

Is it ok to share ~/.cargo/registry for this?

And should I share anything else?

services:
  app:
    volumes:
      - ~/repo:/home/appuser/repo
      - ~/.cargo/registry:/home/appuser/.cargo/registry

I'd recommend using a caching tool like cargo chef instead. More alternatives can be found in the Cache Rust dependencies with Docker build SO question.

1 Like

Cargo-chef is great, but it's for caching deps within images. I'd like to share dependencies between host and containers via local volumes.

Yes, caching/sharing ~/.cargo/registry of the container will work fine to avoid redundant downloads.

If you share it with your actual ~/.cargo outside the container, you may need to ensure that file ownership doesn't conflict (i.e. the same UID/GID is used by the user in the container as outside), otherwise you may get permission errors (Dockerized Cargo will create files that non-Docker Cargo can't modify and vice versa).

It may be easier to just map a dedicated dir for the Docker, e.g. /var/tmp/dockerized_cache:/home/appuser/.cargo.

2 Likes