Containers with Docker

Package your app and its dependencies into images that run the same on your laptop, CI and production.

Intermediate · about 8 hours · difficulty 2/5

Learn first: Linux and the Command Line

"Works on my machine" disappears when the machine ships with the code. A container bundles your app, runtime and system libraries into an isolated process that starts in milliseconds, and Docker is the standard toolchain for building and running them.

Core concepts

  • An image is a read-only template built from a Dockerfile; a container is a running instance of it.
  • Images are made of cached layers; order Dockerfile steps from least to most frequently changing (install dependencies before copying source) for fast rebuilds.
  • Registries (Docker Hub, GitHub Container Registry, ECR) store and distribute images.
  • Volumes persist data outside the container's disposable filesystem; networks let containers reach each other by name.

A production-quality Dockerfile

  • Start from a small, pinned base image (node:22-slim, python:3.12-slim, distroless).
  • Use multi-stage builds: compile in one stage, copy only the output into a slim runtime stage.
  • Run as a non-root user, add a .dockerignore, and never bake secrets into the image.
  • Read configuration from environment variables so the same image runs everywhere.

Docker Compose

compose.yaml describes a local stack (API, Postgres, Redis) that starts with docker compose up. It is the easiest way to give every developer the same environment.

Pitfalls

  • Using latest tags, which makes deploys unreproducible.
  • Huge images full of build tools, slowing every deploy and widening the attack surface.
  • Storing database data inside a container without a volume and losing it on restart.

You are ready to move on when your service builds into a small multi-stage image that runs as non-root, and a Compose file brings up the full stack with one command.

Key concepts

  • Images vs containers
  • Writing a Dockerfile
  • Layer caching
  • Multi-stage builds
  • Volumes and networks
  • Docker Compose
  • Registries and image tags
  • Image security scanning

Mini project

Containerize your API with a multi-stage Dockerfile under 200 MB, write a Compose file with Postgres and Redis, and push the image to GitHub Container Registry from CI.

Check yourself

Why should you copy the dependency manifest and install packages before copying the rest of your source code?

Free resources