Learn Axum · 13/13

Production Readiness & Deployment

7 min read

Production Readiness & Deployment

Welcome back, code artisan! 🦀

So far, you’ve built a blazing-fast Axum API. It handles routes, talks to databases, and creates errors faster than you can say "borrow checker." But right now, it likely lives on localhost:3000. If you close your terminal, your users get a 404 error. That is not optimal.

In this module, we are moving from "It works on my machine" to "It works while I sleep." We will cover how to stop the server without losing data, how to manage secrets, how to package the app efficiently, and how to automate the boring stuff.


1. Graceful Shutdown: Handling SIGTERM Safely

Definition

Graceful Shutdown is the procedure where a program programmatically handles a termination signal (like a stop command), stops accepting new connections, finishes processing active requests, and only then exits.

The Problem

Imagine a user is uploading a large file to your server. Suddenly, the cloud provider decides to move your server to a new node and sends a "kill" command.
If you force-quit (Hard Shutdown), that connection is severed instantly. The file is half-uploaded, the database transaction might be left open (ghost lock), and the user is frustrated.

The Solution

We use tokio::signal to listen for termination signals (like CTRL+C or SIGTERM from Kubernetes/Docker). When received, we tell Axum to stop listening for new requests but keep the process alive until current tasks finish.

Implementation

Axum makes this incredibly easy with the .with_graceful_shutdown() method.

Steps:

  1. Define a function that awaits a signal.
  2. Pass that function to the server builder.
rust
use axum::{Router, routing::get};
use tokio::net::TcpListener;
use tokio::signal;

#[tokio::main]
async fn main() {
    // 1. Build our application with a single route
    let app = Router::new().route("/", get(|| async { "Hello, World!" }));

    // 2. Create the listener
    let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap();
    println!("🚀 Server listening on port 3000");

    // 3. Run the server with graceful shutdown
    axum::serve(listener, app)
        .with_graceful_shutdown(shutdown_signal()) // <--- Magic happens here
        .await
        .unwrap();
}

// This function waits for a Ctrl+C or a specific termination signal
async fn shutdown_signal() {
    let ctrl_c = async {
        signal::ctrl_c()
            .await
            .expect("failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("failed to install signal handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }
    
    println!("🛑 Signal received, starting graceful shutdown...");
}

Fun Fact: When you press Ctrl+C in your terminal, you are actually sending a hardware interrupt signal (SIGINT). If you don't handle it, the OS just mercilessly murders the process. Be polite to your processes.


2. Configuration Management: Environment Variables

Definition

Configuration Management involves externalizing parameters that are likely to vary between deploys (like database URLs, API keys, or port numbers) into the environment, rather than hardcoding them in the source code.

The Problem

  1. Security: If you push your AWS keys or Database password to GitHub, bots will find it in seconds.
  2. Flexibility: If you hardcode port: 3000, and you want to deploy on a server that requires port: 8080, you have to change the code and recompile.

The Solution

We use Environment Variables. In development, we use a .env file to simulate these variables. In Rust, the crate dotenvy (a maintained fork of dotenv) is the industry standard for loading these files, and std::env reads them.

Implementation

1. Add dependencies:

toml
[dependencies]
dotenvy = "0.15"

2. Create a .env file in your project root:

text
DATABASE_URL=postgres://user:password@localhost:5432/mydb
SERVER_PORT=3000
RUST_LOG=debug

3. Access them in Rust:

rust
use std::env;
use dotenvy::dotenv;

#[tokio::main]
async fn main() {
    // Load .env file (if it exists)
    dotenv().ok();

    // Read variables
    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let port_str = env::var("SERVER_PORT").unwrap_or_else(|_| "3000".to_string());
    
    println!("Connecting to DB at: {}", database_url);
    println!("Starting on port: {}", port_str);
    
    // ... rest of your server code
}

Pro Tip: Never commit your .env file to Git. Add it to your .gitignore. Commit a .env.example instead with dummy values so other developers know what keys are required.


3. Dockerizing Axum: Crafting a Lean Dockerfile

Definition

Dockerizing is the process of packaging your application and its dependencies (the OS, libraries) into a single standard unit called a Container Image.

The Problem

Rust compilation is... let's say, "thorough." It takes time. Furthermore, the binary you build on your Mac won't run on a Linux server. Also, the target folder (build artifacts) can be massive (gigabytes). We need a small, portable Linux environment to run our app.

The Solution

We use a Multi-Stage Build.

  1. Builder Stage: Uses a heavy image with the Rust compiler to build the app.
  2. Runtime Stage: Uses a tiny, stripped-down Linux image (like Debian Slim or Distroless) just to run the binary.

This results in an image size of ~50MB instead of 2GB.

Implementation

Create a file named Dockerfile (no extension) in your root.

dockerfile
# ---------------------------------------------------
# 1. Builder Stage
# ---------------------------------------------------
FROM rust:1.75-slim-bookworm as builder

WORKDIR /usr/src/app

# Trick to cache dependencies:
# We copy only Cargo files first, create a dummy main.rs, and build.
# This downloads and compiles all crates. Docker caches this layer.
COPY Cargo.toml Cargo.lock ./
RUN mkdir src && echo "fn main() {}" > src/main.rs
RUN cargo build --release

# Now copy the actual source code
COPY . .

# Touch main.rs to ensure cargo rebuilds it (since we modified it in the previous step)
# Then build the actual release binary
RUN touch src/main.rs
RUN cargo build --release

# ---------------------------------------------------
# 2. Runtime Stage
# ---------------------------------------------------
# Use a minimal linux image
FROM debian:bookworm-slim

# Install OpenSSL (usually required for DB connections/HTTPS)
RUN apt-get update && apt-get install -y libssl-dev ca-certificates && rm -rf /var/lib/apt/lists/*

# Create a non-root user for security
RUN useradd -ms /bin/bash appuser
USER appuser
WORKDIR /app

# Copy the binary from the builder stage
COPY --from=builder /usr/src/app/target/release/my-axum-app ./app

# Expose the port
EXPOSE 3000

# Run the binary
CMD ["./app"]

Common Pitfall: If your app uses OpenSSL (most do for Postgres/reqwest), you must install libssl in the runtime image, or the binary will fail to start with a cryptic "file not found" error.


4. CI/CD Basics: Automating Tests and Builds

Definition

CI (Continuous Integration) is the practice of automatically testing your code every time you push to Git.
CD (Continuous Deployment) is the practice of automatically deploying that code if the tests pass.

The Problem

Humans are bad at repetition. You will forget to run cargo test before merging a PR. You will forget to compile the release build before deploying.

The Solution

We use a workflow engine. GitHub Actions is the most popular for open source and industry right now. We define a YAML file that tells GitHub what to do when we push code.

Implementation

Create a file at .github/workflows/rust.yml.

yaml
name: Rust CI

# Trigger on push to main or pull requests
on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

env:
  CARGO_TERM_COLOR: always

jobs:
  build_and_test:
    runs-on: ubuntu-latest

    steps:
    # 1. Check out the code
    - uses: actions/checkout@v4

    # 2. Cache dependencies (Speeds up future runs significantly)
    - uses: actions/cache@v3
      with:
        path: |
          ~/.cargo/bin
          ~/.cargo/registry
          ~/.cargo/git
          target
        key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}

    # 3. Check for formatting errors
    - name: Check Formatting
      run: cargo fmt -- --check

    # 4. Run the linter (Clippy)
    - name: Run Clippy
      run: cargo clippy -- -D warnings

    # 5. Run Tests
    - name: Run Tests
      run: cargo test --verbose

    # 6. Check if it builds
    - name: Build Release
      run: cargo build --release --verbose

What does this do?

Every time you push code:

  1. It downloads your code.
  2. It checks if your code is ugly (formatting).
  3. It checks if your code is bad (clippy).
  4. It checks if your code is broken (tests).
  5. It ensures it actually compiles.

If any step fails, you get a red X on your GitHub repo, and you know not to deploy that mess.


Summary

You have transformed a fragile "localhost-only" script into a production-ready artifact.

  1. Graceful Shutdown ensures you don't drop users mid-request.
  2. Env Vars keep your secrets secret and your config flexible.
  3. Docker packages your app into a lightweight, portable container.
  4. CI/CD acts as your safety net, preventing bad code from reaching production.

References & Extra Reading

Challenge

Challenge: Create a Robust Data Fetching Function

Write an asynchronous JavaScript function named fetchAndProcessData that takes a single argument: an API endpoint URL string.

Your function must perform the following actions:

  1. Use the fetch API to make a GET request to the provided URL.
  2. The function must handle the promise returned by fetch. Check if the HTTP response was successful. The ok property on the response object is the standard way to do this.
  3. If the response is not successful (e.g., a 404 or 500 error), the function should throw a new Error with a specific message: "HTTP error! status: [status]", where [status] is the status code of the response.
  4. If the response is successful, parse the response body as JSON.
  5. The function should then return the parsed JSON data.
  6. Your implementation must include error handling for network failures or any other issues that might occur during the fetch operation itself. Use a try...catch block to accomplish this.

Expected result

Your code should define a single async function named fetchAndProcessData that accepts a url parameter.

Inside this function, you should use a try...catch block.

Inside the try block:

  • It must use await with the fetch(url) call.
  • It must check the response.ok property of the awaited fetch response.
  • If response.ok is false, it must throw new Error() with the specified message format, including the response.status.
  • If response.ok is true, it must call response.json() using await and return the result.

Inside the catch block:

  • It should catch any errors that occurred in the try block and log a message to the console like "Fetch operation failed:" followed by the error object.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.