Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 132 ยท Testing and Tooling

Release Builds, Cross-Compilation and Deployment

Ship Rust programs: release profiles, Cargo features and cfg, cross-compiling targets, static musl binaries, Docker builds and WebAssembly.

Writing a program is half the job; the other half is getting it onto another machine. Rust makes this unusually pleasant: the compiler produces a single native executable with no runtime to install, and the same source can target Linux, Windows, macOS, a Raspberry Pi or a web page. But a few decisions deserve attention. Which optimizations do you want? Which optional parts of your code ship? How do you build for a machine that is not your own, and how do you package the result?

This lesson walks the path from cargo build --release to a small container image. Most commands here run in a terminal with a Cargo project, so they appear as read-only blocks. The compile-time switches that decide what gets built, cfg and cfg!, do run in our editor, and we use them to explain features and target differences with real output.

Debug and release profiles

Cargo builds with a profile, a named bundle of compiler settings. Two exist by default:

Command Profile Output folder Typical use
cargo build / cargo run dev target/debug/ Everyday development: fast compile, slow program
cargo build --release release target/release/ Shipping and benchmarking: slow compile, fast program
Terminal
$ cargo build --release
   Compiling demo v0.1.0 (/home/me/demo)
    Finished `release` profile [optimized] target(s) in 4.21s
$ ls -lh target/release/demo
-rwxr-xr-x 2 me me 436K demo
$ ./target/release/demo

The binary is self-contained apart from the system C library (and a few system libraries on Windows). You can copy target/release/demo to another machine of the same operating system and CPU family and run it.

The two profiles differ in more than speed. Debug builds check integer overflow and keep debug_assert!; release builds do not by default. The program below prints which one it was compiled as, so you can see the switches the editor uses:

Rust What kind of build is this?

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.

The last three lines print None, 4 and 255 in every profile, because you asked for an explicit behaviour. A plain big + 10 would panic here (attempt to add with overflow) but wrap to 4 in a default release build. Relying on the difference is a bug; see Integer Overflow. If you want the checks in release too, set overflow-checks = true in the profile.

Tuning the release profile

Settings live in Cargo.toml under [profile.release] (or [profile.dev]). The ones that matter most:

TOML
# Cargo.toml (read-only: needs a Cargo project)
[profile.release]
opt-level = 3          # 0..3, "s" (small) or "z" (smallest)
lto = "fat"            # link-time optimization across all crates: true/"fat"/"thin"/false
codegen-units = 1      # fewer units = better optimization, slower build
panic = "abort"        # no unwinding: smaller and slightly faster
strip = "symbols"      # remove debug symbols from the binary
debug = false          # no debug info (the default for release)
overflow-checks = false

What each choice trades:

Setting Effect Cost
opt-level = 3 Fastest code (default for release) Larger binary, longer compile
opt-level = "s" / "z" Smaller code size Often slower at run time
lto = "thin" / "fat" Inlines and removes dead code across crates Much longer link step
codegen-units = 1 The optimizer sees the whole crate at once Compile cannot use all CPU cores
panic = "abort" A panic ends the process immediately; no unwinding tables catch_unwind and panic recovery no longer work; destructors do not run on panic
strip = "symbols" Binary may shrink by half or more Crash backtraces lose function names

Start with the defaults. Add lto = "thin" when you have measured a gain. Turn on codegen-units = 1 and panic = "abort" for a final production build of a service or CLI. Choose opt-level = "z" only when size is the goal, as in embedded or WebAssembly work (Embedded, no_std and WebAssembly).

You can also define your own profile that inherits from another, handy for a "fast-to-compile but optimized" test build:

TOML
# Cargo.toml (read-only)
[profile.release-small]
inherits = "release"
opt-level = "z"
lto = true
strip = true
Terminal
$ cargo build --profile release-small

Cargo features: optional parts of a crate

A feature is a named switch on a crate that includes optional code or optional dependencies. They keep a library small by default, and let the application choose extras. You declare them in Cargo.toml:

TOML
# Cargo.toml (read-only: needs a Cargo project)
[package]
name = "textkit"
version = "0.3.0"
edition = "2024"

[features]
default = ["colors"]          # on unless the user opts out
colors = []                   # a plain feature: just a cfg flag
json = ["dep:serde_json"]     # enabling "json" also enables the optional dependency
full = ["colors", "json"]     # a feature can enable other features

[dependencies]
serde_json = { version = "1", optional = true }

In source code, a feature is a conditional compilation flag: #[cfg(feature = "json")] includes an item only if the feature is on, and cfg!(feature = "json") gives a bool.

Rust
// src/lib.rs (read-only: features need Cargo)
#[cfg(feature = "json")]
pub fn to_json(items: &[String]) -> String {
    serde_json::to_string(items).unwrap()
}

pub fn banner(text: &str) -> String {
    if cfg!(feature = "colors") {
        format!("\x1b[1m{text}\x1b[0m")
    } else {
        text.to_string()
    }
}

Users pick features in their own Cargo.toml or on the command line:

Terminal
$ cargo build --features json
$ cargo build --no-default-features --features "colors json"
$ cargo build --all-features

Two rules keep features sane. Features must be additive: turning one on may add API, but must never remove or change existing behaviour, because Cargo unifies the features requested by every crate in the dependency tree, and your crate gets the union. And test the combinations: cargo test --no-default-features and cargo test --all-features catch code that only compiles with some features on.

The same mechanism, shown with built-in flags

Our editor runs one file with plain rustc, so Cargo features are not available. But cfg is a compiler feature, and the built-in flags work identically. This program includes different functions depending on the platform, and a const plays the role of an on/off feature:

Rust Conditional compilation with cfg

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.

The attribute form #[cfg(...)] removes the item before type checking, so an item for another platform can use APIs that do not exist here. The expression form cfg!(...) only picks a branch at run time; both branches must compile on every platform. Use the attribute when code is platform-specific, and cfg! for simple values. Conditions combine with all(...), any(...) and not(...). More on attributes in Attributes and cfg.

Information from Cargo at compile time

Cargo sets environment variables during a build, and the macros env! and option_env! read them. A common use is printing the package version in --version:

Rust
// Needs Cargo (read-only)
const VERSION: &str = env!("CARGO_PKG_VERSION");

Outside Cargo the variable does not exist, and the build fails. This is deliberate: env! is a compile-time guarantee, while option_env! gives an Option.

Rust env! needs the variable at compile time (fails on purpose)

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.

Rust option_env! is the forgiving version

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.

The first fails with error: environment variable `CARGO_PKG_VERSION` not defined at compile time and two help lines, one saying the variable may not be available for the current Cargo target. The second prints built without Cargo and commit: unknown here. In a Cargo project you set a value like GIT_HASH from a build.rs script with println!("cargo::rustc-env=GIT_HASH={hash}").

Cross-compiling

Cross-compiling means building on one machine for another: develop on a Windows laptop, run on a Linux server or an ARM board. Rust's compiler, rustc, is itself a cross compiler; every target is identified by a target triple like x86_64-unknown-linux-gnu (CPU, vendor, operating system, and sometimes the C library).

Terminal
$ rustc --print target-list | head -5         # all known targets
$ rustup target list --installed
$ rustup target add aarch64-unknown-linux-gnu  # download the standard library for it
$ cargo build --release --target aarch64-unknown-linux-gnu
# binary: target/aarch64-unknown-linux-gnu/release/demo

Rust code itself is portable, but the final step, linking, needs a linker and C library for the target. That is where cross-compiling gets awkward. You have three practical routes:

  1. Install a cross linker and tell Cargo about it in .cargo/config.toml:

    TOML
    # .cargo/config.toml (read-only)
    [target.aarch64-unknown-linux-gnu]
    linker = "aarch64-linux-gnu-gcc"
    
  2. Use cross, a tool that runs the build inside a Docker image containing the right toolchain: cargo install cross, then cross build --release --target aarch64-unknown-linux-gnu.

  3. Use cargo zigbuild, which uses the Zig compiler as a drop-in cross linker and can even target an old glibc version.

Or avoid the problem entirely by building in CI on each target (a matrix of Linux, macOS and Windows runners). For pure-Rust programs it is the simplest and most reliable approach.

You can still ask the compiler about the target from inside code. These are the cfg values that change per target; on our server they print Linux, x86_64, unix and gnu:

Rust Target information in code

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.

Static binaries with musl

The default Linux target, x86_64-unknown-linux-gnu, links dynamically to glibc. A binary built on a new distribution may refuse to start on an older one with an error like version `GLIBC_2.38' not found. The fix for servers and tools you hand to other people is a static binary using the musl C library, which has no external dependencies at all:

Terminal
$ rustup target add x86_64-unknown-linux-musl
$ cargo build --release --target x86_64-unknown-linux-musl
$ ldd target/x86_64-unknown-linux-musl/release/demo
        not a dynamic executable

The result runs on any Linux of the same CPU architecture, including a bare scratch container with nothing in it. Caveats: crates that bind to C libraries (OpenSSL, for instance) need the C library built for musl too, so prefer pure-Rust options such as rustls where you can. musl's default memory allocator is also slower under heavy multi-threaded allocation; replacing it with mimalloc or jemalloc is a common one-line fix in server code.

On Windows, RUSTFLAGS="-C target-feature=+crt-static" links the C runtime statically so users do not need the Visual C++ redistributable.

Docker multi-stage builds

A Rust compiler image is over a gigabyte. A multi-stage build compiles in a big image and copies only the finished binary into a tiny one:

DOCKERFILE
# Dockerfile (read-only: needs Docker)
# --- stage 1: build ---
FROM rust:1.99 AS build
WORKDIR /app

# Cache the dependency build: copy only manifests first.
COPY Cargo.toml Cargo.lock ./
RUN mkdir src && echo "fn main() {}" > src/main.rs \
 && cargo build --release \
 && rm -rf src

# Now build the real code.
COPY src ./src
RUN touch src/main.rs && cargo build --release

# --- stage 2: run ---
FROM debian:bookworm-slim
RUN useradd --system --no-create-home app
COPY --from=build /app/target/release/demo /usr/local/bin/demo
USER app
EXPOSE 8080
ENTRYPOINT ["/usr/local/bin/demo"]

The dummy main.rs trick builds all dependencies in their own cached layer, so editing your own code does not recompile them. The final image contains only Debian's small base and the binary, usually 80 MB or less. With a musl static build you can use FROM scratch (or gcr.io/distroless/static) and get an image of just a few megabytes:

DOCKERFILE
# Static variant (read-only)
FROM scratch
COPY --from=build /app/target/x86_64-unknown-linux-musl/release/demo /demo
ENTRYPOINT ["/demo"]

Remember to copy CA certificates into a scratch image if the program makes HTTPS requests, and to run as a non-root user where you can. Tools such as cargo-chef automate the dependency-caching layer.

WebAssembly

Rust compiles to WebAssembly (Wasm), a compact binary format that runs in browsers and in server-side runtimes. Add the target and build:

Terminal
$ rustup target add wasm32-unknown-unknown   # for browsers, with wasm-bindgen
$ cargo build --release --target wasm32-unknown-unknown

$ rustup target add wasm32-wasip2            # for WASI runtimes (wasmtime, wasmer)
$ cargo build --release --target wasm32-wasip2
$ wasmtime target/wasm32-wasip2/release/demo.wasm

The browser target has no operating system: no files, no threads, no std::time::Instant that works. You talk to JavaScript through wasm-bindgen, and the wasm-pack tool packages the result for npm. For the smallest download use opt-level = "z", lto = true, panic = "abort" and run wasm-opt -Oz on the output. See Embedded, no_std and WebAssembly for the full picture. Our editor cannot produce or run Wasm output.

A release checklist

  1. Test the exact build you ship: cargo test --release can reveal bugs hidden by debug-only behaviour, such as overflow.
  2. Pin the toolchain with rust-toolchain.toml, and commit Cargo.lock for applications so the build is reproducible. Use cargo build --locked in CI to fail if the lock file is out of date.
  3. Audit dependencies: cargo audit and cargo deny (Clippy, rustfmt and Code Quality).
  4. Strip and compress only if size matters; keep a copy of the unstripped binary so you can symbolize crash reports.
  5. Version the binary: embed CARGO_PKG_VERSION and a git hash, and print them with --version.
  6. Publish with a tagged release in CI (binaries per target), a container image, or cargo publish for libraries and cargo install --locked <crate> for tools.

cargo install --path . builds your project in release mode and copies the executable into ~/.cargo/bin, which is on PATH. That is the easiest way to install your own command-line tools on your own machine.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which command builds an optimized executable into target/release/?

    cargo build --release uses the release profile (opt-level 3 by default). cargo run and plain cargo build use the dev profile.
  2. 2. What is the rule for Cargo features in a library?

    If crate A asks for feature x and crate B does not, the build gets x for both. Code must still work when more features are enabled than you expected.
  3. 3. What does panic = "abort" in the release profile change?

    Without unwinding there are no unwind tables and destructors do not run on panic. catch_unwind can no longer recover.
  4. 4. Why build for x86_64-unknown-linux-musl instead of the default gnu target?

    A musl binary carries its own C library, so it runs on any Linux of that architecture, even in a scratch container.
  5. 5. How does #[cfg(target_os = "linux")] differ from cfg!(target_os = "linux")?

    Use the attribute for code that cannot compile elsewhere (platform-specific APIs). cfg! only picks a value, so all branches are type-checked on every platform.

Summary

  • cargo build --release produces the optimized binary in target/release/; the dev profile adds overflow checks and debug assertions and is much slower.
  • Tune [profile.release] with lto, codegen-units = 1, panic = "abort", strip and opt-level ("s"/"z" for size), and define custom profiles with inherits.
  • Cargo features are additive named switches ([features], #[cfg(feature = "...")]); built-in cfg flags (target_os, debug_assertions, unix) work the same way.
  • env! needs the variable at compile time, option_env! returns an Option; Cargo supplies CARGO_PKG_VERSION and friends.
  • Cross-compile with rustup target add plus a linker, cross or cargo zigbuild, or build on each target in CI; use musl for static Linux binaries.
  • Docker multi-stage builds keep images small, and Rust compiles to WebAssembly with wasm32-unknown-unknown and wasm32-wasip2.

Next: Advanced Trait Techniques