How to deploy Rust web server with Docker

Deploy a Rust web server by building a release binary and containerizing it with a multi-stage Dockerfile for a minimal, secure runtime image.

To deploy a Rust web server with Docker, build a release binary, create a minimal Dockerfile using the rust image to compile and alpine to run, then build and run the container.

  1. Build the release binary with cargo build --release.
  2. Create a Dockerfile with the following content:
FROM rust:1.90 as builder
WORKDIR /app
COPY . .
RUN cargo build --release

FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/target/release/my-server .
CMD ["./my-server"]
  1. Build the Docker image with docker build -t my-rust-server ..
  2. Run the container with docker run -p 8080:8080 my-rust-server.