Deployment and Production
8 min read
Welcome to the final boss fight! π₯ You have built a blazing fast API, but currently, it only lives on your laptop (localhost). If you close your terminal, it dies. To let the world see your creation, we need to deploy it.
But we don't just "copy-paste" code to a server. We need to:
- Manage secrets (passwords/keys) securely.
- Make the binary tiny and fast.
- Package it into a container (so it runs anywhere).
- Secure it with HTTPS (the green lock).
Let's turn your code into a production-grade artifact.
1. Environment Variables and Configuration Management
The Problem
Imagine you hardcode your database password in main.rs.
// β BAD: Hardcoded secrets
let db_url = "postgres://user:super_secret_password@localhost/db";If you push this to GitHub, hackers have your password. If you change the database URL, you have to recompile the whole app.
The Solution: The 12-Factor App
The industry standard (12-Factor App methodology) says: Store config in the environment.
We use Environment Variables (VAR=value). They exist outside your code, in the operating system.
Implementation
We will use two crates:
dotenvy: Loads variables from a.envfile (for local dev).config: Merges config from files and environment variables into a nice Rust struct.
Add dependencies:
[dependencies]
dotenvy = "0.15"
config = "0.14"
serde = { version = "1.0", features = ["derive"] }Step 1: Create a .env file (Add this to .gitignore!)
SERVER_HOST=127.0.0.1
SERVER_PORT=8080
DATABASE_URL=postgres://user:pass@localhost/mydbStep 2: Create a type-safe Config struct
Instead of reading strings everywhere, we define a struct that represents our settings.
use config::{Config, ConfigError, File, Environment};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Settings {
pub server: ServerSettings,
pub database_url: String,
}
#[derive(Debug, Deserialize)]
pub struct ServerSettings {
pub host: String,
pub port: u16,
}
impl Settings {
pub fn new() -> Result<Self, ConfigError> {
let builder = Config::builder()
// 1. Start with defaults (optional)
.set_default("server.host", "127.0.0.1")?
.set_default("server.port", 8080)?
// 2. Load from .env file (if it exists)
// We use File::with_name("config") if we had config.toml,
// but here we rely mostly on Env vars.
// 3. Load from Environment Variables
// Variables like APP_SERVER__PORT will override settings.
.add_source(Environment::default().separator("__").prefix("APP"));
builder.build()?.try_deserialize()
}
}Step 3: Use it in main.rs
use dotenvy::dotenv;
use actix_web::{web, App, HttpServer};
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Load .env file (returns error if not found, usually ignored in prod)
dotenv().ok();
// Load config
let config = crate::config::Settings::new().expect("Config loaded");
println!("π Server running at {}:{}", config.server.host, config.server.port);
HttpServer::new(|| {
App::new().service(web::resource("/").to(|| async { "Hello!" }))
})
.bind((config.server.host, config.server.port))?
.run()
.await
}Why this rocks: You can now change the port by simply running APP_SERVER__PORT=9090 ./my_app without touching a single line of Rust code!
2. Compiling for Release: Optimizing Binary Size and Speed
The Problem
By default, cargo build creates a Debug build.
- Huge size: Contains debug symbols (maps code to text for errors).
- Slow: No optimizations (checks for overflows, etc.).
- Fact: A "Hello World" debug build might be 150MB because it includes a kitchen sink of debugging info.
The Solution: Release Profile
We use cargo build --release. But we can squeeze it further. We want a "Release" build that strips out the fat.
Optimization Recipe
Modify your Cargo.toml. We will enable LTO (Link Time Optimization). This tells the compiler to look at the entire program (all crates together) to remove unused code, rather than optimizing one file at a time.
[profile.release]
opt-level = 3 # Maximize speed (default)
lto = true # Enable Link Time Optimization (slower build, faster binary)
codegen-units = 1 # Reduce parallel code generation to maximize optimization
panic = "abort" # Crash immediately on panic (removes stack unwinding code)
strip = true # Strip symbols from binary (reduces size drastically)What do these do?
lto = true: Like a trash compactor. It finds code used across different libraries and merges/deletes duplicates.codegen-units = 1: Usually, Rust splits code into chunks to compile in parallel. Setting this to 1 makes it compile slower (single core) but allows the optimizer to see the "big picture" better.panic = "abort": By default, Rust can "unwind" the stack to catch panics. In an API, if we panic, we usually just want to restart the pod. Removing unwinding saves space.strip = true: Removes the dictionary that translates machine code back to function names.
The Result:
- Debug Build: ~200MB
- Release Build: ~15MB
- Release + Stripped + LTO: ~5MB (Tiny! π)
3. Dockerizing Your Actix Web Application
The Problem
"It works on my machine!" is the most dangerous sentence in software. Docker fixes this by packaging your OS, libraries, and app into a single Image.
The Solution: Multi-Stage Builds
Rust compile times are long, and the build tools (compiler, cargo) take up gigabytes of space. We don't want the compiler in the final server.
We use a Multi-Stage Build:
- Stage 1 (Builder): Heavy image (Rust, GCC, Cargo). We build the app here.
- Stage 2 (Runtime): Tiny image (Debian Slim or Alpine). We copy only the binary from Stage 1.
The Secret Weapon: cargo-chef π¨βπ³
Docker caches layers. If you change one line of code, Docker usually rebuilds all dependencies. cargo-chef fixes this by analyzing your Cargo.lock and building dependencies separately from your code.
Dockerfile:
# ---------------------------------------------------
# 1. PLANNER STAGE
# Computes the recipe file from your dependencies
# ---------------------------------------------------
FROM rust:1.80 as planner
WORKDIR /app
RUN cargo install cargo-chef
COPY . .
RUN cargo chef prepare --recipe-path recipe.json
# ---------------------------------------------------
# 2. CACHER STAGE
# Builds dependencies based on the recipe
# ---------------------------------------------------
FROM rust:1.80 as cacher
WORKDIR /app
RUN cargo install cargo-chef
COPY --from=planner /app/recipe.json recipe.json
# Build dependencies - this is the caching layer!
RUN cargo chef cook --release --recipe-path recipe.json
# ---------------------------------------------------
# 3. BUILDER STAGE
# Builds the actual application
# ---------------------------------------------------
FROM rust:1.80 as builder
WORKDIR /app
COPY . .
# Copy over the cached dependencies
COPY --from=cacher /app/target target
RUN cargo build --release --bin my_actix_app
# ---------------------------------------------------
# 4. RUNTIME STAGE
# The final tiny image
# ---------------------------------------------------
# We use debian:bookworm-slim for a balance of size and compatibility (glibc)
# Alpine (musl) is smaller but can be tricky with some Rust crates (OpenSSL).
FROM debian:bookworm-slim AS runtime
WORKDIR /app
# Install OpenSSL (needed for many Rust web apps)
RUN apt-get update -y \
&& apt-get install -y --no-install-recommends openssl ca-certificates \
&& apt-get autoremove -y \
&& apt-get clean -y \
&& rm -rf /var/lib/apt/lists/*
# Copy the binary from the builder stage
COPY --from=builder /app/target/release/my_actix_app my_app
COPY .env .env
# Expose the port
EXPOSE 8080
# Run
ENTRYPOINT ["./my_app"]Commands:
docker build -t my-actix-app .
docker run -p 8080:8080 --env-file .env my-actix-appFunny Fact: A Rust Docker image is often smaller than the source code of a Node.js node_modules folder.
4. Setting up HTTPS/TLS with Rustls
The Problem
HTTP is clear text. Anyone on the wifi can see the passwords users send to your API. You need HTTPS (TLS).
The Solution: rustls
We use rustls instead of OpenSSL because it's written in Rust (memory safe) and is generally faster and more modern.
Note: In large production systems (AWS, Kubernetes), TLS is often handled by a "Load Balancer" or "Ingress" before the request hits your app. However, running TLS in the app is safer (End-to-End Encryption) and necessary for standalone servers.
Dependencies:
[dependencies]
actix-web = { version = "4", features = ["rustls-0_23"] }
rustls = "0.23"
rustls-pemfile = "2"Generate Self-Signed Certs (For Testing):
You can't buy a cert for "localhost". Run this command (requires openssl installed):
openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'The Code:
We need to load the certificates and tell Actix to use them.
use actix_web::{get, App, HttpServer, Responder};
use rustls::ServerConfig;
use rustls_pemfile::{certs, pkcs8_private_keys};
use std::fs::File;
use std::io::BufReader;
#[get("/")]
async fn index() -> impl Responder {
"π Secure Connection Established!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// 1. Load config for TLS
let config = load_rustls_config();
println!("π₯ HTTPS Server running at https://localhost:8443");
HttpServer::new(|| {
App::new().service(index)
})
// 2. Bind using rustls
.bind_rustls_0_23("127.0.0.1:8443", config)?
.run()
.await
}
fn load_rustls_config() -> ServerConfig {
// Init crypto provider (required in rustls 0.23+)
let _ = rustls::crypto::ring::default_provider().install_default();
// Open certificate file
let cert_file = &mut BufReader::new(File::open("cert.pem").expect("cert.pem missing"));
let key_file = &mut BufReader::new(File::open("key.pem").expect("key.pem missing"));
// Parse PEM
let cert_chain = certs(cert_file)
.collect::<Result<Vec<_>, _>>()
.unwrap();
let mut keys = pkcs8_private_keys(key_file)
.collect::<Result<Vec<_>, _>>()
.unwrap();
// Build config
ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(cert_chain, keys.remove(0))
.unwrap()
}Now, go to https://localhost:8443. Your browser will warn you "Connection not private" (because it's a self-signed cert), but if you click "Proceed", you are using encrypted TLS!
π References & Extra Reading
- 12-Factor App: 12factor.net
- Actix Docker: Official Actix Docker Example
- Cargo Chef: LukeMathWalker/cargo-chef
- Rustls: github.com/rustls/rustls
- Config Crate: docs.rs/config
- Rust Container Security: Google Distroless Images
Challenge
Your task is to write a production-grade, multi-stage Dockerfile for a Rust web application. The application's source code is located in the current directory, and the final compiled binary will be located at /app/target/release/my-api-server within the build environment.
Your Dockerfile must adhere to the following requirements:
- Multi-Stage Build: Implement at least three distinct stages:
planner,builder, and a final runtime stage. - Dependency Caching: Use
cargo-cheffor intelligent dependency caching. Theplannerstage will create arecipe.json. Thebuilderstage will use this recipe to build dependencies separately from the application code. - Optimized Release Build: The application must be compiled in
releasemode. - Minimal Final Image: The final stage must be based on a minimal Linux distribution, specifically
debian:bookworm-slim. - Security Best Practices:
- Create a dedicated, non-root user named
appuser. - The final image must run the application as this
appuser. - Only the compiled binary should be copied to the final stage. No source code, build tools, or intermediate artifacts should be included.
- Create a dedicated, non-root user named
- Execution: The final container should expose port
8080and set the default command (CMD) to execute the application binary.
Expected result
A complete and valid Dockerfile that correctly implements a three-stage build process for a Rust application.
- Planner Stage: Must be aliased as
planner. It should be based on a full Rust image, installcargo-chef, copy the necessary project files (Cargo.toml,Cargo.lock,src), and generate arecipe.jsonfile. - Builder Stage: Must be aliased as
builder. It should also use a Rust image, copy therecipe.jsonfrom theplannerstage, usecargo chef cook --release --recipe-path recipe.jsonto build dependencies, and then copy the application source to build the final binary withcargo build --release. - Runtime Stage: Must be based on
debian:bookworm-slim. It needs to create a non-root user and group, copy the compiled binary from thebuilderstage (e.g., from/app/target/release/my-api-server), set file ownership, switch the user with theUSERinstruction, expose port8080, and define theCMDto run the application.