Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 38 ยท Testing and Deployment

Configuration, Docker and Deployment

Ship an Axum service. Read configuration from the environment, build a small multi-stage Docker image, add health checks and run migrations safely, with runnable Rust stand-ins.

A service that works on your laptop is only half done. Production needs configuration that changes per environment, a build that produces one small artifact, a way for the platform to ask "are you healthy?" and a plan for database migrations. Rust helps here: a release build is a single static-ish binary with no runtime to install.

This lesson shows the real configuration code and Dockerfile read-only (Docker and the crates cannot run on this site) and gives you runnable stand-ins for the parsing and validation logic, which is where most deployment bugs live.

Twelve-factor configuration

Keep configuration out of the code and read it from environment variables. The same binary then runs in development, staging and production. Fail fast at startup if something is missing, instead of crashing on the first request.

Rust
use std::net::SocketAddr;

#[derive(Debug, Clone)]
pub struct Config {
    pub bind_addr: SocketAddr,
    pub database_url: String,
    pub jwt_secret: String,
}

impl Config {
    pub fn from_env() -> Result<Config, String> {
        let bind_addr = std::env::var("BIND_ADDR")
            .unwrap_or_else(|_| "0.0.0.0:3000".into())
            .parse()
            .map_err(|e| format!("BIND_ADDR: {e}"))?;
        let database_url = std::env::var("DATABASE_URL")
            .map_err(|_| "DATABASE_URL is required".to_string())?;
        let jwt_secret = std::env::var("JWT_SECRET")
            .map_err(|_| "JWT_SECRET is required".to_string())?;
        if jwt_secret.len() < 32 {
            return Err("JWT_SECRET must be at least 32 characters".into());
        }
        Ok(Config { bind_addr, database_url, jwt_secret })
    }
}

In main, call Config::from_env() once, print a clear error and exit with a non-zero code on failure. Put the result in your shared state. Locally, the dotenvy crate loads a .env file into the environment; never load it in production images.

Never log the whole config. It contains secrets. Log the bind address and the fact that the database is configured, not the URL with its password. Never commit .env files with real values.

Stand-in: a testable config loader

To make configuration testable, take the variables from a map instead of reading the process environment directly. Production passes real environment values; tests pass a HashMap.

Rust Parse and validate configuration (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Failing at startup with a readable message ("DATABASE_URL is required") is far kinder than a panic deep in a request.

Release builds and Docker

cargo build --release turns on optimizations. For production images use a multi-stage build: compile in a big image with the Rust toolchain, then copy only the binary into a tiny runtime image.

DOCKERFILE
# syntax=docker/dockerfile:1
FROM rust:1.90 AS build
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY src ./src
COPY migrations ./migrations
COPY .sqlx ./.sqlx
ENV SQLX_OFFLINE=true
RUN cargo build --release

FROM debian:bookworm-slim AS runtime
RUN useradd --system --create-home app
WORKDIR /home/app
COPY --from=build /app/target/release/my-service ./my-service
USER app
ENV BIND_ADDR=0.0.0.0:3000
EXPOSE 3000
CMD ["./my-service"]

Points worth knowing:

  • SQLX_OFFLINE=true and the .sqlx folder (created with cargo sqlx prepare) let the compile-time checked query! macros build without a live database.
  • Bind to 0.0.0.0, not 127.0.0.1. Inside a container, loopback is unreachable from outside.
  • Run as a non-root user. A compromise then has fewer rights.
  • Layer caching: copying Cargo.toml and Cargo.lock before src lets Docker reuse the dependency layer. Tools such as cargo-chef improve this further.
  • The final image holds just the binary and a minimal OS, often under 100 MB.

Health checks and migrations

Orchestrators need two cheap endpoints:

  • Liveness (/healthz): the process is up. Return 200 without touching dependencies.
  • Readiness (/readyz): it can serve traffic. Check the database with SELECT 1; return 503 if it fails so the load balancer stops sending requests.
Rust
async fn readyz(State(state): State<AppState>) -> StatusCode {
    match sqlx::query("SELECT 1").execute(&state.pool).await {
        Ok(_) => StatusCode::OK,
        Err(_) => StatusCode::SERVICE_UNAVAILABLE,
    }
}

For migrations, either run sqlx migrate run as a separate release step before starting new instances, or call sqlx::migrate!().run(&pool).await? at startup. The separate step is safer when several instances start at once. Write migrations to be backward compatible (add a column first, remove the old one in a later release) so old and new versions can run side by side during a rolling deploy.

Stand-in: liveness, readiness and rollout

Rust Readiness decides who gets traffic (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice app-2 is alive but not ready. Restarting it will not fix a database outage, so liveness stays green while readiness removes it from rotation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a container bind to 0.0.0.0 instead of 127.0.0.1?

    Binding to loopback means only processes in the same container can connect.
  2. 2. What is the main benefit of a multi-stage Dockerfile for Rust?

    The build stage is large; only the compiled binary is copied to the small final image.
  3. 3. What should a readiness endpoint check that a liveness endpoint should not?

    Readiness answers 'can I serve traffic now?'. Liveness only says the process is running.
  4. 4. Why load configuration from environment variables and fail at startup?

    One artifact, many environments, and early clear errors.

Summary

  • Read configuration from the environment once at startup and validate it; fail with a clear message.
  • Make the loader take a map so tests do not depend on the real environment.
  • Use a multi-stage Docker build, SQLX_OFFLINE, a non-root user and 0.0.0.0 binding.
  • Expose liveness and readiness endpoints; readiness checks the database.
  • Run migrations as a release step and keep them backward compatible.
  • Never log or commit secrets.

Next: Observability and Production Hardening