Skip to content
🎉 Launch sale:50% off everything over $22 — automatically applied at checkout· ends Aug 2Shop the sale →
DevOps AI ToolKit
Newsletter
intermediate Premium Images & Dockerfiles · ⏱ 40 min

Build an Optimized Python Image

Scenario

You inherited a 1.1 GB Python image that builds slowly and runs as root. Re-engineer the Dockerfile: multi-stage, minimal runtime, non-root user, and a working health check — without breaking the app.

Learning objectives

  • Build the app image
  • Convert to a multi-stage Dockerfile
  • Reduce the final image size
  • Run as a non-root user
  • Add a working HEALTHCHECK

Before you start

Required software: Docker Engine 24+

Prerequisites: Docker Fundamentals path

  1. Download and unzip the lab.
  2. Build the starter image and note its size: docker build -t pyapp:before starter/ && docker images pyapp:before.

Instructions

Full instructions are part of Individual Pro

Unlock the step-by-step instructions, the solution guide, validation scripts, and downloadable files.

Unlock with Pro

Hints

💡 Where does the size come from?

Build tooling (compilers, caches, dev headers) shouldn’t reach the runtime image. A builder stage that produces a wheel/venv, copied into a slim final stage, removes most of it.

💡 Health check keeps failing

HEALTHCHECK runs inside the container — the tool it calls (e.g. curl) must exist in the final image, or use Python itself to probe.

Validate your work

From the lab folder, run:

bash validation/validate.sh

The script reads only your local Docker state, never transmits data off your machine, and returns a status code:

  • 0 — Lab successfully completed
  • 1 — Validation failed
  • 2 — Required dependency missing
  • 3 — Lab environment not running
  • 4 — Configuration error
  • 5 — Validation timed out

Note: validation targets Linux first. On Docker Desktop (macOS/Windows) some host-level checks (e.g. disk usage) may report differently; each script documents its limitations.

Solution

The full solution + troubleshooting explanation is available to Individual Pro members. Try to solve it first — that’s where the learning is.

Upgrade to Pro

Reset the lab

  • docker compose down -v && docker compose up -d from the original lab files restores the starting (broken) state.

Interview questions

  • What is the difference in a `RUN` layer between `pip install` in a builder vs the final stage?
  • Why run containers as non-root?
  • What makes a good container HEALTHCHECK?

Finished this lab?

Sign in to record your completion and track progress across the path. Completion is recorded server-side.

Related labs