Day 5 – Image Optimisation and Hardening
Today's Focus
Optimise image size and startup time, and apply container security best practices.
Tasks
- Audit your current images with
docker scout quickview(ortrivy image your-image:latestif Trivy is installed). Count the number of CVEs. Switch your base image frompython:3.12topython:3.12-slimorgcr.io/distroless/python3and rescan. Record the reduction in vulnerabilities. - Minimise layer count: combine multiple
RUNcommands into one using&&and clean up package manager caches in the same layer (apt-get clean && rm -rf /var/lib/apt/lists/*). Compare image sizes before and after. - Add a
HEALTHCHECKinstruction to your backend Dockerfile:HEALTHCHECK --interval=30s --timeout=5s --retries=3 CMD curl -f http://localhost:8080/health || exit 1. Run the container and watchdocker psto see the health status change fromstartingtohealthy. - Pin your base image to a specific digest for deterministic builds:
FROM python:3.12-slim@sha256:<digest>. Get the digest withdocker inspect python:3.12-slim | grep Id. Explain why using:latestis risky in production. - Measure container startup time: run
time docker run --rm your-image echo hi. Identify what makes startup slow (large image, slow init process) and fix one issue. - Write a short
DOCKER.mddocumenting: how to build, how to run locally, available environment variables, the Compose workflow, and how to run tests inside the container.
Reading / Reference
- Docker: Best practices for writing Dockerfiles.
- Trivy documentation — Container Image scanning.
- Chainguard images — distroless-style minimal secure images for various runtimes.