I run development using --config
file on my Rust API, it is something like this
cargo run --config dev-config.toml
where the dev-config.toml is like my Environments
like this
[env]
APP_ENV = "development"
APP_PORT = "8181"
APP_TIMEOUT = "3" # in seconds
APP_MAX_ATTEMPTS = "50" # in attempts ( 50 request in 60 seconds )
MONGO_URI="balblaaa"
...
I can build image in my docker like this to copy the file
# Use the official Rust image as the base image
FROM rust:latest as builder
# Set the current working directory inside the Docker image
WORKDIR /usr/src
# Copy the Cargo.toml file and your source code into the Docker image
COPY Cargo.toml .
COPY src ./src
COPY secrets ./secrets
# Copy the dev-config.toml file
COPY dev-config.toml .
# Build the application in release mode
RUN cargo build --release --config dev-config.toml
# Start a new build stage
FROM rust:latest
# Copy the binary from the builder stage to the current stage
COPY --from=builder /usr/src/target/release/my-api /usr/local/bin
# Set the command to run your application
CMD ["my-api"]
when I run docker run -p 8080:8080 my-api
I got error the env was empty and not set
[INFO] - "Trying to Connect MongoDB..."
thread 'main' panicked at src/db.rs:43:75:
MONGO_URI must be set.: NotPresent
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
is that something I miss here and other way to use --config
? instead set manual env
I have been read cases on internet, but there is none of my topic out there because rust is new,
2
Answers
There is more than one possible answer here. Let’s see a few options.
Option 1
You can have multiple docker files (eg.: dockerfile / dockerfile.local ) that copy specific config files to the image. Inside a dockerfile.local you should have:
Option 2
You can code, as seen in this reddit post, env config to be loaded dynamically based on specific rules.
Your problem
As I can’t see your entire project structure, I’d suggest you to run locally the RUN cargo build –release and see if it works. If it works, then open your docker image (this way) and check if the copied files are in the same structure as your local project.
The
[env]
from using a cargo--config
file only affects cargo invocations with it (i.e.cargo build
,cargo run
, etc.). So you could make this work as-is by using:Though I don’t actually recommend that even if
cargo build
was ran beforehand.Instead, I would suggest reading How do I pass environment variables to Docker containers? Options there like using a
--env-file
or launching with adocker-compose
configuration would likely be more palatable. If you go with a.env
file, you could change your Rust code to load from it using the dotenvy crate instead of provided by cargo’s config.