Learn Actix Web Β· 13/13

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:

  1. Manage secrets (passwords/keys) securely.
  2. Make the binary tiny and fast.
  3. Package it into a container (so it runs anywhere).
  4. 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.

rust
// ❌ 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 .env file (for local dev).
  • config: Merges config from files and environment variables into a nice Rust struct.

Add dependencies:

toml
[dependencies]
dotenvy = "0.15"
config = "0.14"
serde = { version = "1.0", features = ["derive"] }

Step 1: Create a .env file (Add this to .gitignore!)

env
SERVER_HOST=127.0.0.1
SERVER_PORT=8080
DATABASE_URL=postgres://user:pass@localhost/mydb

Step 2: Create a type-safe Config struct
Instead of reading strings everywhere, we define a struct that represents our settings.

rust
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

rust
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.

toml
[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?

  1. lto = true: Like a trash compactor. It finds code used across different libraries and merges/deletes duplicates.
  2. 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.
  3. 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.
  4. 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:

  1. Stage 1 (Builder): Heavy image (Rust, GCC, Cargo). We build the app here.
  2. 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:

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:

bash
docker build -t my-actix-app .
docker run -p 8080:8080 --env-file .env my-actix-app

Funny 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:

toml
[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):

bash
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.

rust
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

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-chef for intelligent dependency caching. The planner stage will create a recipe.json. The builder stage will use this recipe to build dependencies separately from the application code.
  • Optimized Release Build: The application must be compiled in release mode.
  • 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.
  • Execution: The final container should expose port 8080 and 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.

  1. Planner Stage: Must be aliased as planner. It should be based on a full Rust image, install cargo-chef, copy the necessary project files (Cargo.toml, Cargo.lock, src), and generate a recipe.json file.
  2. Builder Stage: Must be aliased as builder. It should also use a Rust image, copy the recipe.json from the planner stage, use cargo chef cook --release --recipe-path recipe.json to build dependencies, and then copy the application source to build the final binary with cargo build --release.
  3. Runtime Stage: Must be based on debian:bookworm-slim. It needs to create a non-root user and group, copy the compiled binary from the builder stage (e.g., from /app/target/release/my-api-server), set file ownership, switch the user with the USER instruction, expose port 8080, and define the CMD to run the application.
dockerfile

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.