Search code examples
dockerrustrust-cargo

How to run a custom entry-point file on Rust Docker


I am using the Rust official docker image for a web application. Since Dockerfile on the official doc ends with CMD ["myapp"], I wonder how to specify an entry-point file whose file name is not main.rs using this docker image.

Specifically, the folder structure of my application is as follows, and I would like to run src/main1.rs using Dockerfile1 and src/main2.rs using Dockerfile2.

├─Cargo.toml
├─Cargo.lock
├─Dockerfile1
├─Dockerfile2
└─src/
  ├─main1.rs
  └─main2.rs

As far as I know, Cargo.toml should be like this:

[package]
name = ...
version = ...
authors = ...

[[bin]]
name = "main1"
path = "src/main1.rs"

[[bin]]
name = "main2"
path = "src/main2.rs"

Solution

  • Well you gave your binaries a name, namely main1 and main2 so you can make them the containers command with CMD ["main1"] or CMD ["main2"] respectively

    While you're at it you might avoid the other binaries in the containers where they're not used replacing RUN cargo install --path . with RUN cargo install --bin mainN --path . in the docker files.


    And a side note, cargo automatically creates binary crates for Rust files in src/bin so instead of adding [[bin]] tables for every binary you might to just want to change your layout to

    ├─Cargo.toml
    ├─Cargo.lock
    ├─Dockerfile1
    ├─Dockerfile2
    └─src/
      └─bin/
        ├─main1.rs
        └─main2.rs
    

    with a Cargo.toml of just

    [package]
    name = ...
    version = ...
    authors = ...
    

    to produce the same result.