Skillversitas

Docker Rust

How to run a Rust application in Docker.

Rust Dockerfile

# Stage 1: Build
FROM rust:1.73 AS builder
WORKDIR /app
COPY . .
RUN cargo build --release

# Stage 2: Production
FROM debian:bullseye-slim
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/server /server
EXPOSE 8080
CMD ["/server"]

docker-compose.yml

version: '3.8'

services:
  api:
    build: .
    ports:
      - "8080:8080"
    environment:
      - DATABASE_URL=postgresql://user:pass@database:5432/myapp
    networks:
      - app-net

  database:
    image: postgres:15
    environment:
      POSTGRES_DB: myapp
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
    volumes:
      - postgres-data:/var/lib/postgresql/data
    networks:
      - app-net

networks:
  app-net:

volumes:
  postgres-data:

Use Case: Rust Application

# Run Rust
docker-compose up -d

# Build
docker-compose build

# Test
docker-compose exec api cargo test

Everyday Use Case

Case: A developer needs to run Rust.

# Build
docker-compose build

# Run
docker-compose up -d

# Rust commands
docker-compose exec api cargo test
docker-compose exec api cargo build --release

Best Practices

  1. Multi-stage build: For a smaller image
  2. Debian slim: For production
  3. Non-root user: For security
  4. Health check: For monitoring

Conclusion

Rust in Docker is easy to set up. Use a multi-stage build to produce a smaller image.