This post explains how to install Rust on a Docker container and then use that container to compile Rust files/projects on your machine.
Create a folder for your Rust Docker Container. Inside that folder create a file named “Dockerfile”. Inside put the following:
This means creating a container with Rust version 1.58. You can change the version per your needs.
Run the following command to create the container:
docker build --tag rust-docker .
This command will create a Docker container and give it “rust-docker” as the name. You will then use this same name “rust-docker” when calling it to compile Rust files.
How to compile Rust project through Docker?
Let’s say for the sake of the test that your project is located at /Users/username/Documents/RustProject
You will need to mount that path so that the Docker container gets access to that path. Then you need to provide a command for example “Cargo Run” to run on that project.
docker run -v /Users/username/Documents/RustProject:/project rust-docker cargo run
Oops when you run this you will get “error: could not find
/ or any parent directory”. This is because by default cargo run will execute in the / directory but you can’t set the mapping in Docker to /. For example the command below is illegal:
docker run -v /Users/username/Documents/RustProject:/ rust-docker cargo run
docker: Error response from daemon: invalid volume specification: ‘/host_mnt/Users/username/Documents/RustProject:/’: invalid mount config for type “bind”: invalid specification: destination can’t be ‘/’.
See ‘docker run –help’
How to point Cargo Run to a project path?
Thankfully the docs are really helpful. If you check under the manifest options: https://doc.rust-lang.org/cargo/commands/cargo-build.html#manifest-options you will see that you can point Cargo towards the toml file, so let’s do just that:
docker run -v /Users/username/Documents/RustProject:/project rust-docker cargo run --manifest-path /project/Cargo.toml
Tada! that should do it. You can run all the necessary commands from that Docker container. Hope this has helped you 🙂
Note: I initially got this issue because I had to install Gigabytes of libraries on MacOS (because I had to install xcode-select or some bullshit)
Update: adding one caveat of running Rust through Docker like that is that a new Docker container is spun up every time you run the above command and if it is long running and you want to stop the process you will need to delete/kill the container.