Environment variables at runtime

Learn how environment variables reach a running container, how docker run passes them with -e and --env-file, and how the Axum config loader reads them

An environment variable at runtime is a setting handed to a container when it starts, not baked into the image when it is built. The same image can run on a laptop, on a test server, and in production, with a different database address, a different listen address, and a different secret on each machine, because the variables are supplied at the moment the container starts. The program inside reads them once at startup, and the image itself never changes.

Docker itself is not installed on the machine used to write these docs, so no docker run command on this page was run live here. Every Docker flag and behaviour follows the official Docker docs. The env-var wiring itself was verified by running the Rust server directly with the same variables set in the shell, exactly as a container would receive them, and watching it bind, answer requests, and fail fast when a required variable was missing.

Where This Fits

The build made an image that holds a server, and the run command started it with flags. This page is about the most important of those flags, the ones that carry settings into the container. A server that reads its database address from the code cannot change databases without a rebuild. A server that reads it from the environment can change databases with a new run command, and the image stays the same. That is the whole reason the config loader exists, and this page connects it to the container that runs it.

Think of the image as a printed form and the environment variables as the handwriting filled in on it. The form is identical for everyone, and the handwriting is different on every copy. The name, the address, and the signature change, but the form does not need reprinting. The Dockerfile is the form. The docker run flags are the handwriting.

The Smallest Working Version

Start with the config-driven server from the earlier pages, with the four-field AppConfig that reads four variables and the same rules for each one.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
dotenvy = "=0.15.7"
src/config.rs
use std::net::SocketAddr;

#[derive(Clone)]
pub struct AppConfig {
    pub database_url: String,
    pub listen_address: SocketAddr,
    pub rust_log: String,
    pub jwt_secret: String,
}

impl AppConfig {
    pub fn from_env() -> Result<AppConfig, String> {
        let database_url = std::env::var("DATABASE_URL").map_err(|_| {
            "DATABASE_URL must be set, for example postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config"
                .to_string()
        })?;
        let listen_address = std::env::var("LISTEN_ADDRESS")
            .unwrap_or_else(|_| "127.0.0.1:3000".to_string())
            .parse::<SocketAddr>()
            .map_err(|_| {
                "LISTEN_ADDRESS must be an address like 127.0.0.1:3000".to_string()
            })?;
        let rust_log = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string());
        let jwt_secret =
            std::env::var("JWT_SECRET").map_err(|_| "JWT_SECRET must be set".to_string())?;
        Ok(AppConfig {
            database_url,
            listen_address,
            rust_log,
            jwt_secret,
        })
    }
}

The four variables and their rules are the same as in the configuration work. DATABASE_URL and JWT_SECRET are required, and the program stops at startup with a clear message when either is missing. LISTEN_ADDRESS defaults to 127.0.0.1:3000 and RUST_LOG defaults to info. The loader runs once, at the start of main, and after it returns, no code reads the environment again.

src/lib.rs
pub mod config;
src/main.rs
use axum::{extract::State, routing::get, Json, Router};
use axum_project::config::AppConfig;
use serde::Serialize;

#[derive(Serialize)]
struct Status {
    listen_address: String,
    rust_log: String,
}

async fn status(State(config): State<AppConfig>) -> Json<Status> {
    Json(Status {
        listen_address: config.listen_address.to_string(),
        rust_log: config.rust_log.clone(),
    })
}

#[tokio::main]
async fn main() {
    let _ = dotenvy::dotenv();
    let config = match AppConfig::from_env() {
        Ok(config) => config,
        Err(error) => {
            eprintln!("Configuration error: {error}");
            std::process::exit(1);
        }
    };
    let app = Router::new()
        .route("/", get(status))
        .route("/health", get(|| async { "OK" }))
        .with_state(config.clone());
    let listener = tokio::net::TcpListener::bind(config.listen_address)
        .await
        .unwrap();
    println!("Listening on http://{}", config.listen_address);
    axum::serve(listener, app).await.unwrap();
}

The dotenvy::dotenv() call at the top loads a .env file when one exists. Inside a container there is usually no .env file, so the call finds nothing and returns an error that the let _ = discards, and the loader then reads only the variables Docker passed in. That is the correct behaviour. The .env file is a development convenience, and the container does not need it.

The smallest run command passes the four variables one by one with -e:

docker run -d \
  --name axum-server \
  -p 3000:3000 \
  -e DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config \
  -e LISTEN_ADDRESS=0.0.0.0:3000 \
  -e RUST_LOG=info \
  -e JWT_SECRET=test-secret-only-for-local-development \
  axum-project:1.0

The database address here names a database on the local machine and carries a password that is only an example for local development, so it is safe to copy for a local test, and it must be replaced with the real address before any real deployment. The listen address is 0.0.0.0:3000, not the default, because the default 127.0.0.1:3000 only accepts connections from inside the container itself, and nothing outside could reach the server.

This wiring was verified in the scratch project used for these docs by running the release binary directly with the same four variables set in the shell, exactly as Docker would set them. The server printed Listening on http://0.0.0.0:3000, a request to / returned {"listen_address":"0.0.0.0:3000","rust_log":"info"}, and /health returned OK. Running it with DATABASE_URL unset printed Configuration error: DATABASE_URL must be set, for example postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config and stopped, and running it with JWT_SECRET unset printed Configuration error: JWT_SECRET must be set and stopped. Running it with neither LISTEN_ADDRESS nor RUST_LOG set started on the default 127.0.0.1:3000 with the default log level, and /health still returned OK.

Working Setup:

If the container starts and a request to / returns the listen address and log level as JSON, the variables reached the server and the loader read them. If the container stops at once, docker logs axum-server shows which variable is missing, named in the error message.

Docker Is Not Installed Here:

Every Docker command on this page is written from the official Docker docs, not from a live run on this machine. The variable wiring was verified by running the Rust server directly with the variables set in the shell, which is the same environment a container provides, but no container was started while writing this page.

How a Variable Travels Into a Container

A variable set with docker run -e is placed into the environment of the container process before the server starts. The server process is the container process, so the variable is visible to it from the first line of main, and std::env::var reads it like any other environment variable. There is no file involved, no network call, and no special Docker channel. The container environment is a plain process environment, the same kind every program on Linux receives from its parent.

The Dockerfile can also set a variable with ENV, and that value is baked into the image as a default. A runtime flag overrides it. The order, from lowest to highest precedence, is the Dockerfile ENV value, then the --env-file value, then the -e flag value. A variable set in two places takes the value from the highest place that sets it, and a variable set in none of them is simply absent, which is what makes the required variables fail fast.

One consequence is worth stating plainly. The variables are fixed at container creation. They cannot be changed on a running container, because the server process already read them at startup and never reads the environment again. Changing a value means stopping the container, removing it, and running a fresh one with the new value. A container is cheap to recreate, and that is the intended way to change its configuration.

The -e Flag, One Variable at a Time

The -e flag sets a single variable, and it can be repeated for each variable the server needs. Its two forms are worth knowing, because the second one surprises beginners.

docker run -d -e RUST_LOG=debug axum-project:1.0
docker run -d -e RUST_LOG axum-project:1.0

The first form sets the value in the command itself. The second form, -e RUST_LOG with no value, copies the current value of RUST_LOG from the shell that runs Docker. If the shell has no such variable, the container gets no value at all, and the loader falls back to its default or fails, depending on the variable. The copy form is useful when a value already exists on the host and should not be typed again, but it hides where the value came from, so the explicit form is better when the value matters and should be visible in the command.

The -e flag is the right tool for one or two variables, and for a quick override of a single value. A server with four variables and a secret among them is already at the point where the file form is cleaner, which is the next section.

Secrets on the Command Line Stay in Shell History:

A secret typed as -e JWT_SECRET=... is saved in the shell history file, where anyone with access to the machine can read it later. It is also visible in the process list while the command runs. Use the file form below for secrets, so the value never appears on a command line.

The --env-file Flag, Many Variables at Once

The --env-file flag loads variables from a file, one KEY=value pair per line, and sets them all inside the container. The file is read from the host machine at container start, and it never becomes part of the image.

.env
DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config
LISTEN_ADDRESS=0.0.0.0:3000
RUST_LOG=info
JWT_SECRET=test-secret-only-for-local-development
docker run -d --name axum-server -p 3000:3000 --env-file .env axum-project:1.0

The file format has three rules that catch beginners. Blank lines are ignored, and lines starting with # are comments. Quotes are not processed, so JWT_SECRET="abc" sets the value to "abc" with the quote characters included, which is not the secret the server expects. And there is no shell expansion, so DATABASE_URL=$DB_URL sets the literal text $DB_URL, not the value of a shell variable. The file is plain text, one pair per line, with no quotes and no expansion.

The file must be kept out of version control, because it holds the database password and the signing secret. Add .env to .gitignore before the first commit, and never push it to a shared repository. A secret that reaches version control has to be treated as known to everyone, and changing it afterwards does not undo the exposure.

Several files can be given at once, and they are read in order, with later files overriding earlier ones for the same variable. A -e flag overrides all of them. That order is useful for a shared base file and a per-machine override file, where the override file holds only the values that differ.

docker run -d --env-file .env.common --env-file .env.production -e RUST_LOG=debug axum-project:1.0

In this command, the production file wins over the common file for any variable they share, and the -e RUST_LOG=debug flag wins over both files for the log level. The rest of the variables come from whichever file sets them.

ENV in the Dockerfile and ARG in the Build

Two Dockerfile instructions look like they set variables, and only one of them reaches the running container. ENV sets a variable that exists during the build and stays set in the finished image, so it is visible to the container as a default. ARG sets a build-time variable that exists only while the image is being built and is gone at runtime.

Dockerfile
FROM debian:bookworm-slim
ENV RUST_LOG=info
EXPOSE 3000
CMD ["/usr/local/bin/axum-project"]

The ENV RUST_LOG=info line sets a default log level that the container inherits, unless a -e RUST_LOG=debug flag or an --env-file entry overrides it at runtime. That is a reasonable use of ENV, because a log level is a safe default, not a secret. The same line with a secret would be a mistake, because the value is baked into the image and visible to anyone who can inspect it with docker inspect.

An ARG value never reaches the container at all. A Dockerfile that declares ARG DATABASE_URL and a build that passes --build-arg DATABASE_URL=... gives the build the value, and the running container nothing. A server that reads DATABASE_URL at startup finds it missing and fails fast, which is confusing until the difference is understood. Build arguments are for values the build needs, such as a compiler version. Runtime settings are for the run flags.

ARG Values Never Reach the Container:

A variable passed with --build-arg exists only during the build and is gone before the container starts. A server that needs a value at runtime must receive it through -e or --env-file, never through a build argument. A container that fails at startup with a missing variable, after a build that seemed to set it, has almost always confused the two.

What Each Variable Does for This Server

The four variables are not interchangeable, and each one deserves its own explanation, because each one fails differently when it is wrong.

DATABASE_URL is the address of the database, and it is required. The value names the database engine, the user, the password, the host, the port, and the database name, all in one string. A wrong host means the server cannot connect, and a missing value means the server refuses to start. The value is a secret, because it holds a password, so it travels only through --env-file or -e, never through the Dockerfile.

LISTEN_ADDRESS is the address the server binds to, and it is optional, with a default of 127.0.0.1:3000. Inside a container the default is wrong, because it only accepts connections from inside the container, so the run command must override it to 0.0.0.0:3000. A malformed value, such as a port number with no address, fails at startup with a parse error, because the loader parses the string into a socket address before the server binds. A port below 1024 needs privilege the container user does not have, so the port should stay above 1024, and 3000 is the usual choice.

RUST_LOG is the log filter, and it is optional, with a default of info. It controls how much the server logs, and a value of debug produces more output than info, which is useful when a container misbehaves and the logs are the only clue. A misspelled value does not fail the server, because the loader accepts any string for this field, so a typo here produces silence or noise rather than an error, and the fix is to check the spelling against the value that was intended.

JWT_SECRET is the signing secret for login tokens, and it is required, with no default. A signing secret must never have a fallback value written in code, because a fallback secret is a secret everyone can read. A missing value stops the server at startup, which is the correct outcome, and a wrong value does not stop the server but makes every token it signs invalid on the next deploy, so the value must be the same across restarts of the same service.

The Concept Behind Runtime Configuration

Configuration that changes between machines belongs outside the code and outside the image, because the code and the image are the same everywhere, and the settings are not. The environment is the place for those settings, because it belongs to the machine that runs the program, not to the repository that holds it. The image carries the program. The run command carries the settings. The loader is the one place where the two meet, and it meets them once, at startup.

That split has three effects. First, the program fails fast. A missing or malformed setting stops startup, before any request is served, with a message that names the variable. Second, the program is consistent. Every part of the program reads the same struct, so no part can see a different database address from another part. Third, the program is portable. The same image runs on a laptop and on a production server, and only the run command changes.

A beginner sometimes asks why the settings are not simply written into the Dockerfile with ENV. The answer is that the Dockerfile is part of the image, and the image is shared. A value written into the image is the same on every machine that runs it, which is wrong for a database address and dangerous for a secret. The run flags exist precisely because some values must differ per machine, and the image must not decide them.

A Richer Complete Example

The richer example puts the whole chain together: the Dockerfile with a safe ENV default, the .env file with the real values, the run command that uses it, and the check that proves the variables arrived.

Dockerfile
FROM rust:1.100.0-bookworm AS builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
RUN cargo fetch
COPY src ./src
RUN cargo build --release
FROM debian:bookworm-slim
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/axum-project /usr/local/bin/axum-project
USER nobody
ENV RUST_LOG=info
EXPOSE 3000
CMD ["/usr/local/bin/axum-project"]

The only ENV line in the file is the safe default for the log level. No secret appears in the Dockerfile, and no database address does either. The .env file holds the real values:

.env
DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config
LISTEN_ADDRESS=0.0.0.0:3000
RUST_LOG=info
JWT_SECRET=test-secret-only-for-local-development

The run command uses the file and overrides nothing:

docker run -d --name axum-server -p 3000:3000 --env-file .env --restart unless-stopped axum-project:1.0

A second run command shows the override order. The same image, the same file, but the log level changed for one run, without editing the file:

docker run -d --name axum-debug -p 3001:3000 --env-file .env -e RUST_LOG=debug axum-project:1.0

The second container listens on host port 3001, because host port 3000 is taken by the first, and it logs at debug because the -e flag wins over the file. Both containers read the same database address and the same secret, and both serve the same routes. The image never changed. Only the run commands differed.

After either container starts, the checks are the same. docker logs axum-server shows the startup line with the listen address, and a request to / returns the listen address and log level as JSON. For the debug container, the log output is more detailed, which is the visible effect of the override. If a container stops at once, docker logs shows the configuration error, which names the missing variable, and the fix is to add that variable to the file or the run command and start a fresh container.

How the Variables Flow

The path from a run flag to a handler has five steps, and each one hands the value to the next without changing it.

docker run -e LISTEN_ADDRESS=0.0.0.0:3000 --env-file .env
        |
        v
container process starts with those variables in its environment
        |
        v
dotenvy::dotenv() loads .env when one exists, ignored when it does not
        |
        v
AppConfig::from_env() reads four variables once, fails fast on a bad one
        |
        v
main binds config.listen_address, handlers read State<AppConfig>

The loader is the narrow point in the flow, and it is the only place that reads the environment. Everything before it is about getting values in, and everything after it is about using values that are already checked. A variable that is wrong is caught at the loader step, before the server binds, which is why a missing variable produces a clear startup error instead of a broken request later.

Testing It Without a Docker Daemon

The wiring was verified on this machine by running the server directly with the variables set in the shell, which is the same environment a container provides, and the checks below are the ones that were run.

First, run the server with all four variables set, as the smallest example does, and request both routes. The scratch project ran the release binary with LISTEN_ADDRESS=0.0.0.0:3000 and the other three variables set, and a request to / returned {"listen_address":"0.0.0.0:3000","rust_log":"info"} while /health returned OK.

Second, run it with a required variable missing. The scratch project ran it with DATABASE_URL unset and saw Configuration error: DATABASE_URL must be set, for example postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config, and with JWT_SECRET unset and saw Configuration error: JWT_SECRET must be set. Both runs stopped before binding, with no server started.

Third, run it with the optional variables missing. The scratch project ran it with neither LISTEN_ADDRESS nor RUST_LOG set, and the server started on the default 127.0.0.1:3000 and answered /health with OK, which proves the defaults apply.

A test file can prove the same loader behaviour without starting a server at all, using the same pattern as the configuration work:

tests/config_test.rs
use axum_project::config::AppConfig;

fn set_full_env() {
    std::env::set_var(
        "DATABASE_URL",
        "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config",
    );
    std::env::set_var("LISTEN_ADDRESS", "0.0.0.0:3000");
    std::env::set_var("RUST_LOG", "info");
    std::env::set_var("JWT_SECRET", "test-secret-only-for-local-development");
}

#[test]
fn full_env_loads() {
    set_full_env();
    let config = AppConfig::from_env().unwrap();
    assert_eq!(config.listen_address.to_string(), "0.0.0.0:3000");
    assert_eq!(config.rust_log, "info");
}

#[test]
fn missing_database_url_fails() {
    set_full_env();
    std::env::remove_var("DATABASE_URL");
    let error = match AppConfig::from_env() {
        Ok(_) => panic!("expected loading to fail without DATABASE_URL"),
        Err(error) => error,
    };
    assert!(error.contains("DATABASE_URL"), "{error}");
}

#[test]
fn defaults_apply_when_optional_vars_missing() {
    set_full_env();
    std::env::remove_var("LISTEN_ADDRESS");
    std::env::remove_var("RUST_LOG");
    let config = AppConfig::from_env().unwrap();
    assert_eq!(config.listen_address.to_string(), "127.0.0.1:3000");
    assert_eq!(config.rust_log, "info");
}

The missing-variable test uses a match instead of unwrap_err, because unwrap_err needs the success type to implement Debug, and AppConfig deliberately has no Debug implementation, since a debug print would show the database password and the secret. The match form reads the error out without asking for a debug print of the struct.

The tests set variables with std::env::set_var, which changes the environment of the test process itself, and tests in one file share that process, so they run one at a time with --test-threads=1, or one test's variables leak into the next test's reads. Run them with:

cargo test --test config_test -- --test-threads=1

All three passed in the scratch project. The first proves a full environment loads, the second proves a missing required variable fails with a message naming it, and the third proves the two defaults appear when their variables are absent. The --test-threads=1 flag is not optional here: without it, the tests run in parallel threads of one process, and the remove_var in one test can run while another test is reading, which makes failures appear and disappear between runs.

The checks that need Docker are the docker run commands themselves, the log check, and the request to the published port. Those are the first commands to run once Docker is installed, and they prove the container, not just the code, reads the variables.

Common Beginner Mistakes

Baking a secret into the image with ENV

# Wrong - the secret is visible in the image forever
ENV JWT_SECRET=dev-secret-do-not-use-in-production

Anyone who can pull or inspect the image can read this value. The fix is to remove the line from the Dockerfile and pass the secret at runtime with --env-file, so it never enters the image.

Quoting values in the env file

# Wrong - the quotes become part of the value
JWT_SECRET="test-secret-only-for-local-development"

The --env-file format does no shell parsing, so the loader reads the value with the quote characters included, and the secret no longer matches the one the tokens were signed with. The fix is to write the value with no quotes, one plain KEY=value pair per line.

Forgetting the listen address override

# Wrong - the container starts, but nothing outside can reach it
docker run -d -p 3000:3000 --env-file .env axum-project:1.0

When the file holds no LISTEN_ADDRESS, the loader uses its default, 127.0.0.1:3000, which only accepts connections from inside the container. The container runs, the port is published, and every request fails to connect. The fix is a LISTEN_ADDRESS=0.0.0.0:3000 line in the file, or a -e LISTEN_ADDRESS=0.0.0.0:3000 flag on the run command.

Trying to change a variable on a running container

Environment variables are set when the container is created, and they cannot be changed afterwards. Editing the .env file does not affect a container that is already running, and docker exec -e sets a variable for one exec command only. The fix is to stop the container, remove it, and run a fresh one with the new values.

Copying the .env file into the image

# Wrong - the secrets file becomes part of the image
COPY .env /app/.env

A .env file copied into the image ships its secrets to every machine that pulls the image, and the dotenvy::dotenv() call inside the container would then load it, which hides the mistake by making the server work. The fix is to keep .env out of the image with .dockerignore, and to pass the variables at runtime instead, so the image holds no secrets at all.

Expecting dotenvy to load the file inside the container

The dotenvy::dotenv() call loads a .env file from the working directory of the process, and a container built from the Dockerfile in this cluster has no .env file, because .dockerignore excludes it. That is correct, not a bug. The variables arrive through Docker flags, and the dotenv call simply finds nothing and moves on. A server that works locally but fails in a container with a missing variable has almost always relied on the local .env file without passing the same variables to the container.

Final Complete Example

Everything on this page put together is the project, the Dockerfile, the env file, and the commands that run it and prove the variables arrived.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
dotenvy = "=0.15.7"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Dockerfile
FROM rust:1.100.0-bookworm AS builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
RUN cargo fetch
COPY src ./src
RUN cargo build --release
FROM debian:bookworm-slim
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/axum-project /usr/local/bin/axum-project
USER nobody
ENV RUST_LOG=info
EXPOSE 3000
CMD ["/usr/local/bin/axum-project"]
.env
DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config
LISTEN_ADDRESS=0.0.0.0:3000
RUST_LOG=info
JWT_SECRET=test-secret-only-for-local-development
.dockerignore
target/
.git/
.env
Dockerfile
.dockerignore

The Rust files are the config module, the library declaration, the server, and the two test files from this page and the earlier Docker pages. Check the code first, then run on a machine with Docker:

cargo check
cargo test --test config_test -- --test-threads=1
docker build -t axum-project:1.0 .
docker run -d --name axum-server -p 3000:3000 --env-file .env --restart unless-stopped axum-project:1.0
docker logs axum-server
curl http://127.0.0.1:3000/

The first two commands were run for this page in the scratch project and passed. The rest follow the official Docker command reference and need Docker installed. When the container is running, the request to / returns the listen address and log level as JSON, which proves the variables travelled from the run command into the server.

Summary

Runtime environment variables are the seam between an image that never changes and a machine that always does. The image holds the program, the run command holds the settings, and the loader is the one place where the two meet, once, at startup, with a clear error when a setting is missing. That seam is what makes one image run on a laptop and on a production server without a rebuild, and it is what makes a secret safe, because the secret only exists in the run command and the container environment, never in the image.

The decision framework is short. If a value is the same on every machine, it can be a default in the code or an ENV line in the Dockerfile. If a value differs per machine, it belongs in a run flag or a file, and the file form wins as soon as there are more than a couple of variables. If a value is a secret, it belongs in a file that is never committed and never copied into the image, and it never appears on a command line. And if a container misbehaves, the first thing to check is the variables it was started with, because the loader fails fast and says which one is missing, and the fix is a fresh container with the right values, not a change to the image.