πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹

Building Docker containers is just the beginning! To run containers in production, they must be optimized for security, performance, and reliability.

Today, we focus on multi-stage builds, security hardening, image optimization, and best practices for running containers in production.

⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:


πŸ’‘ Learning points:

πŸ”Ή Multi-Stage Builds – Reduce image size by separating build and runtime stages.
πŸ”Ή Security Hardening – Using non-root users, minimizing attack surface, and avoiding secrets in images.
πŸ”Ή Image Optimization – Choosing lightweight base images (alpine, scratch) and reducing layers.
πŸ”Ή Build Caching & Layer Management – Optimizing the Dockerfile for faster builds.
πŸ”Ή Health Checks – Ensuring the container is running correctly using HEALTHCHECK.
πŸ”Ή Logging & Monitoring – checking logs properly and monitoring them.



🧠 Learn here:

Multi-Stage Builds in Docker

What Are Multi-Stage Builds?

Multi-stage builds in Docker allow you to use multiple FROM statements in your Dockerfile to separate the build environment from the runtime environment. This reduces the final image size and eliminates unnecessary build tools and dependencies in production.

βœ… Benefits

  • 🐳 Smaller Image Size
  • πŸ” Better Security (minimal tools/libraries)
  • πŸš€ Faster Deployments

Example: Go Application Using Multi-Stage Builds

# Stage 1: Build
FROM golang:1.26 AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -o myapp .

# Stage 2: Run
FROM alpine:3.22
WORKDIR /root/
COPY --from=builder /app/myapp .
CMD ["./myapp"]

Before Multi-Stage Build (Single Stage Example)

FROM golang:1.26
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -o myapp .
CMD ["./myapp"]

Result:

  • Image Size: ~900MB
  • Contains: Go compiler, source code, build cache

After Multi-Stage Build (CGO_ENABLED=0 builds a static binary; without it the binary links against the Go image's glibc and fails to start on Alpine, which uses musl)

# Stage 1: Build
FROM golang:1.26 AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -o myapp .

# Stage 2: Run
FROM alpine:3.22
WORKDIR /root/
COPY --from=builder /app/myapp .
CMD ["./myapp"]

Result:

  • Image Size: ~15MB
  • Contains: Only the binary myapp

Security Hardening

  • Always use non-root users to run applications.
  • Minimize the image by removing unnecessary tools and dependencies.
  • Avoid storing secrets in Dockerfiles or images.

Example:

FROM node:24-alpine
RUN addgroup -S app && adduser -S app -G app
USER app
COPY . /app
WORKDIR /app
CMD ["node", "app.js"]

Image Optimization

  • Prefer lightweight base images such as alpine or scratch.
  • Flatten image layers to reduce overhead.

Example:

FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "main.py"]

Build Caching & Layer Management

Structure your Dockerfile to leverage build caching efficiently. Keep frequently unchanged instructions at the top.

Example:

FROM node:24-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
CMD ["node", "server.js"]

Health Checks

Use the HEALTHCHECK instruction to define a command that can be used to determine whether the container is still functioning properly.

Example:

# The probe tool must exist in the image: Alpine/BusyBox images have wget, not curl
HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
  CMD wget -qO- http://localhost:3000/health || exit 1

Logging & Monitoring

  • Redirect logs to stdout/stderr for easier collection by log drivers.
  • Integrate container logs with centralized monitoring tools like ELK, Loki, or Fluent Bit.

Example:

# Write logs to stdout/stderr and let Docker's log driver collect them
CMD ["node", "server.js"]

# For software that insists on log files, link them to stdout/stderr
# (this is what the official nginx image does)
RUN ln -sf /dev/stdout /var/log/nginx/access.log \
 && ln -sf /dev/stderr /var/log/nginx/error.log

πŸ“Œ Additional Tips

  • Pin image versions to prevent unexpected changes (python:3.11-slim instead of python:latest).
  • Use .dockerignore to exclude unnecessary files and reduce context size.
  • Keep images small and secure using tools like slim (SlimToolkit), trivy, or Dive.

πŸ“šοΈ Resources:

πŸ“Œ Docker Multi-Stage Builds – Docker Docs
πŸ“Œ Best Practices for Secure Containers – Docker Blog
πŸ“Œ Docker Logging & Monitoring – Docker Docs
πŸ“Œ Docker Image Size Optimization – Best Practices Docker Docs
πŸ“Œ Scanning Docker Images for Vulnerabilities – Aqua Security



πŸš€ Initial Tasks

βœ… Task 1: Learn about Multi-Stage Builds

  • Understand how multi-stage builds help create smaller, secure, and production-ready Docker images.
  • Focus on:
    • Separating build and runtime environments.
    • Minimizing attack surface and image size.
    • Removing unnecessary build dependencies from the final image.

βœ… Task 2: Write a Basic Dockerfile

  • Create a Dockerfile for a simple Python or Node.js app.
  • Build and analyze the image size using:
docker images
  • Explore optimization opportunities like .dockerignore, base image choice, and caching layers.

βœ… Task 3: Check Container Logs Using Docker Logging

docker logs <container_id>
  • Default Docker log path:
    /var/lib/docker/containers/<container_id>/
  • Default logging driver: json-file

To rotate logs for all new containers, set this in /etc/docker/daemon.json and restart Docker (sudo systemctl restart docker):

{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  }
}
  • Useful for inspecting logs and managing disk usage.

πŸ”₯ Challenges

πŸ”Ή Challenge 1: Convert an existing Dockerfile into a multi-stage build and compare image sizes.
πŸ”Ή Challenge 2: Run a lightweight Alpine-based container (python:3.13-alpine or node:24-alpine).
πŸ”Ή Challenge 3: Add a HEALTHCHECK in a Dockerfile for a web application (curl or wget).
πŸ”Ή Challenge 4: Run a container without root privileges and ensure the app runs correctly.
πŸ”Ή Challenge 5: Scan your Docker image using Docker Scout or Trivy, and fix vulnerabilities.
πŸ”Ή Challenge 6: Implement log management by redirecting container logs to a file.
πŸ”Ή Challenge 7: Set up resource limits (memory, CPU) for a container using --memory and --cpus.
πŸ”Ή Challenge 8: Use docker build --progress=plain to analyze layer caching and optimize the build process.

βœ… Solutions

βœ… Challenge 1: Convert an existing Dockerfile into a multi-stage build and compare image sizes.

e.g. Dockerfile

# Original Dockerfile (Single-Stage)
FROM python:3.13
# Set working directory
WORKDIR /app
# Copy all files
COPY . .
# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Expose port 5000
EXPOSE 5000
# Run the Flask app
CMD ["python", "app.py"]

The app.py and requirements.txt used throughout these challenges:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Multi-Stage Flask App Running!"

@app.route("/health")
def health():
    return "OK"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)
flask

Answer:

Step 1: Build & Check Image Size of the Single-Stage Build

docker build -t flask-single-stage .
docker images | grep flask-single-stage

Example Output:

flask-single-stage   latest   850MB

Step 2: Convert to a Multi-Stage Build

Optimized Multi-Stage Dockerfile

# Stage 1: install dependencies into a virtualenv
FROM python:3.13 AS builder
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Stage 2: slim runtime with only the venv and the code
# (copying just /app would leave the installed packages behind)
FROM python:3.13-slim
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY . .
EXPOSE 5000
CMD ["python", "app.py"]

Step 3: Build & Compare Image Sizes

docker build -t flask-multi-stage .
docker images | grep flask

Example Output:

flask-single-stage   latest   850MB
flask-multi-stage    latest   120MB

βœ… Reduced image size from 850MB β†’ 120MB!

Step 4: Test the Optimized Image

docker run -d --rm --name flask-test -p 5000:5000 flask-multi-stage
curl http://localhost:5000
docker stop flask-test

Expected Output:

Multi-Stage Flask App Running!

βœ… Challenge 2: Run a lightweight Alpine-based container (python:3.13-alpine or node:24-alpine).

Answer:
To further reduce the image size, build both stages on python:3.13-alpine. Packages installed on the Debian-based image are built for glibc and don't run on Alpine's musl libc:

Final Dockerfile:

# Both stages on Alpine so compiled packages match its musl libc
FROM python:3.13-alpine AS builder
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

FROM python:3.13-alpine
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY . .
EXPOSE 5000
CMD ["python", "app.py"]

Rebuild & compare:

docker build -t flask-alpine .
docker images | grep flask

Example Output:

flask-multi-stage latest 120MB
flask-alpine      latest  50MB

βœ… Challenge 3: Add a HEALTHCHECK in a Dockerfile for a web application (curl or wget).

Answer:

Step 1: Update the Dockerfile with HEALTHCHECK

FROM python:3.13-alpine AS builder
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

FROM python:3.13-alpine
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY . .
EXPOSE 5000
# Alpine has BusyBox wget but no curl
HEALTHCHECK --interval=10s --timeout=3s --retries=3 \
  CMD wget -qO- http://localhost:5000/health || exit 1
CMD ["python", "app.py"]

Step 2: Build the Image

docker build -t flask-app-healthcheck .

Step 3: Run the Container

docker run -d --name flask-container -p 5000:5000 flask-app-healthcheck

Step 4: Verify Container Health Status

docker ps

Example Output:

CONTAINER ID  IMAGE                   STATUS                   NAMES
abc123456789  flask-app-healthcheck   Up 30s (healthy)         flask-container

Step 5: Inspect Health Check Details

docker inspect --format='{{json .State.Health}}' flask-container | jq

βœ… Challenge 4: Run a container without root privileges and ensure the app runs correctly.

Answer:

Step 1: Modify the Dockerfile to Run as a Non-Root User

FROM python:3.13 AS builder
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

FROM python:3.13-slim
WORKDIR /app
RUN groupadd -r appgroup && useradd -r -g appgroup appuser
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY --chown=appuser:appgroup . .
USER appuser
EXPOSE 5000
CMD ["python", "app.py"]

Step 2: Build the Image

docker build -t flask-nonroot-app .

Step 3: Run the Container as a Non-Root User

docker run -d --name flask-nonroot-container -p 5000:5000 flask-nonroot-app

Step 4: Verify the Running User in the Container

docker exec -it flask-nonroot-container whoami

Expected Output:

appuser

Step 5: Test the Application

curl http://localhost:5000

Expected Output:

Multi-Stage Flask App Running!

Step 6: Check the Process User

# slim images have no ps; id shows which user the app runs as
docker exec flask-nonroot-container id

Expected Output (Shows appuser instead of root):

uid=999(appuser) gid=999(appgroup) groups=999(appgroup)

βœ… Challenge 5: Scan your Docker image using Docker Scout or Trivy, and fix vulnerabilities.

Answer:

Step 1: Build the Docker Image

docker build -t flask-app-secure .

Step 2: Scan the Image Using Docker Scout

# docker scan was removed; Docker Scout ships with Docker Desktop
# (on Linux, install the docker-scout CLI plugin)
docker scout quickview flask-app-secure
docker scout cves flask-app-secure

Example Output:

    βœ“ Indexed 182 packages

  Target     β”‚  flask-app-secure:latest  β”‚    0C     2H     6M    35L
    digest   β”‚  3f1c2a9b8e7d             β”‚
  Base image β”‚  python:3.13-slim         β”‚    0C     1H     5M    33L

Step 3: Scan the Image Using Trivy (More Detailed)

brew install trivy          # macOS
# Linux: install from Aqua's apt/rpm repository (see the Trivy docs)
trivy --version             # 0.69.4–0.69.6 were malicious builds (March 2026 supply-chain attack)
trivy image flask-app-secure

Example Output:

Total: 5 vulnerabilities
Critical: 1
High: 2
Medium: 2
Low: 0

Step 4: Fix Vulnerabilities

  • Replace python:3.13 with python:3.13-slim or python:3.13-alpine
  • Update system packages:
RUN apt-get update && apt-get upgrade -y \
    && apt-get install -y --no-install-recommends curl \
    && rm -rf /var/lib/apt/lists/*
  • Use non-root user:
RUN useradd -m appuser
USER appuser

Step 5: Rebuild the Image and Re-Scan

docker build -t flask-app-secure-fixed .
trivy image flask-app-secure-fixed

βœ… If vulnerabilities are reduced, the security improvements were successful!


βœ… Challenge 6: Implement log management by redirecting container logs to a file.

Answer:

Option 1: Redirect Logs to a File Inside the Container

FROM python:3.13-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
CMD ["sh", "-c", "python app.py > /app/app.log 2>&1"]

Run & View Logs

docker build -t flask-app-logs .
docker run -d --name flask-log-container flask-app-logs
docker exec -it flask-log-container tail -f /app/app.log

Option 2: Redirect Logs to a Host File

mkdir -p logs
# the image writes to /app/app.log, so point the redirect at the mounted folder
docker run -d --name flask-log-host \
  -v "$(pwd)/logs:/app/logs" \
  flask-app-logs sh -c "python app.py > /app/logs/app.log 2>&1"
tail -f logs/app.log

Option 3: Use Docker's Default Log File Location

# With the json-file driver, a container's stdout/stderr is stored in a file on the host
docker run -d --name flask-stdout -p 5001:5000 flask-multi-stage
sudo tail -f "$(docker inspect --format '{{.LogPath}}' flask-stdout)"

# or save a copy
docker logs flask-stdout > flask-container.log 2>&1

Option 4: Use Docker Logging Drivers

docker run -d --name flask-rotated \
  --log-driver json-file \
  --log-opt max-size=10m \
  --log-opt max-file=3 \
  flask-multi-stage

βœ… Challenge 7: Set up resource limits (memory, CPU) for a container using --memory and --cpus.

Answer:

Step 1: Build the Docker Image

docker build -t flask-resource-limited .

Step 2: Run the Container with CPU & Memory Limits

docker run -d --name flask-container \
  --memory="512m" \
  --cpus="0.5" \
  -p 5000:5000 \
  flask-resource-limited

Step 3: Verify Resource Limits

docker stats --no-stream flask-container
docker inspect --format 'Memory={{.HostConfig.Memory}} NanoCpus={{.HostConfig.NanoCpus}}' flask-container
# Memory=536870912 NanoCpus=500000000

Step 4: Test Resource Limits

# The image has no stress tool, so use Python to push past the limits
docker exec flask-container python -c "b = bytearray(700 * 1024 * 1024)"
echo $?   # 137: killed by the OOM killer at the 512m limit

docker exec -d flask-container python -c "while True: pass"
docker stats --no-stream flask-container   # CPU % stays around 50%

βœ… Challenge 8: Use docker build --progress=plain to analyze layer caching and optimize the build process.

Answer:

Step 1: Modify Dockerfile for Layer Optimization

Inefficient Dockerfile:

FROM python:3.13
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 5000
CMD ["python", "app.py"]

Optimized Dockerfile:

FROM python:3.13
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["python", "app.py"]

Step 2: Build the Image with Plain Progress Output

docker build --progress=plain -t flask-app-optimized .

# change only the code and rebuild: the pip install step should now say CACHED
touch app.py
docker build --progress=plain -t flask-app-optimized . 2>&1 | grep -E "CACHED|pip install"

βœ… This uses cache efficiently for faster builds!

πŸ–οΈ How to Participate?

βœ… Complete the tasks and challenges.
βœ… Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
βœ… Share the above in a LinkedIn post tagging me (Sandip Das) and use #60DaysOfDevOps to engage with the community!


⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:

Share this post