Installing and Executing Rust Code via Docker

1 minute read

Published:

The best way to try new technologies without having clutter? Docker.

This article is about how to install and run Rust code via Docker.

  • Create a new directory in the host machine. Let's call it "my-rust-app"
  • Create a very simple Dockerfile with the following lines
    # pull the latest version of Rust
    FROM rust:latest
    
    # change our work dir to /usr/myrustapp
    WORKDIR /usr/myrustapp
    
    # copy all the files in current dir to the work dir
    COPY . .
    
    # compile and run Rust script
    CMD ["cargo", "run"]
    
  • Create a file called Cargo.toml and pass the following lines to the file.
    [package]
    name = "hello_world"
    version = "0.0.0"
    authors = ["Your Name"]
    edition = "2019"
    
  • Create a directory src and a file main.rs within it. Here's the content of the main.rs.
    fn main() {
        println!("Hello, World!");
    }
    
  • Open up a Terminal and execute the following commands.
    # build the image from the docker file
    docker build -t my-rust-img [path_to_the_dockerfile]
    
    # create and run a container from the image
    docker run -it --rm --name my-rust-container my-rust-img
    
  • The Rust script should be compiled and executed

Thanks for reading.