LESSON 3

Containerization

Package applications into small, secure, reproducible container images: Dockerfile practices, image layers, local multi-service environments, health checks, scanning, and registries.

Introduction

“It works on my machine” has a precise cause: the application depends on things that differ between machines, such as the operating system, library versions, tools, and configuration. A container packages the application and its runtime dependencies into one portable unit, so that what runs in the pipeline is what runs in production.

Containers are not magic. A badly built image can be huge, insecure, and non-reproducible. This lesson covers building images well.

Learning Objectives

  • Explain what containers and images are and what they do not isolate.
  • Write Dockerfiles that are small, cacheable, reproducible, and secure.
  • Run multi-service environments locally with a composition file.
  • Add health checks and handle signals so containers behave in orchestrators.
  • Scan, tag, sign, and store images in a registry.
  • Use AI to draft and review container definitions.

1. Concepts

  • An image is an immutable, layered filesystem snapshot plus metadata (the command to run, exposed ports).
  • A container is a running instance of an image, isolated by the operating system’s process, filesystem, and network namespaces.
  • A registry stores and distributes images.
  • A tag is a mutable label (1.4.0, latest); a digest (sha256:...) identifies exact content and never changes.

Containers share the host kernel. They provide packaging and process isolation, not the strong isolation of a virtual machine, so they must still be run with least privilege.

2. A Good Dockerfile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# syntax=docker/dockerfile:1

# ---- build stage: tools needed only to build ----
FROM python:3.12-slim AS build
WORKDIR /app
COPY pyproject.toml poetry.lock ./
RUN pip install --no-cache-dir poetry==1.8.3 \
 && poetry export --without dev -o requirements.txt \
 && pip wheel --no-cache-dir -r requirements.txt -w /wheels
COPY src/ ./src/

# ---- runtime stage: only what is needed to run ----
FROM python:3.12-slim AS runtime
RUN useradd --create-home --uid 10001 appuser
WORKDIR /app
COPY --from=build /wheels /wheels
RUN pip install --no-cache-dir --no-index --find-links=/wheels /wheels/*.whl \
 && rm -rf /wheels
COPY --from=build /app/src ./src
USER 10001
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"
CMD ["python", "-m", "signaldesk.api"]

Practices illustrated:

Practice Reason
Multi-stage build Build tools stay out of the final image: smaller and with fewer vulnerabilities
Pinned base image (version, ideally digest) Reproducible builds; no surprise upgrades
Copy dependency files first Layer caching: dependencies rebuild only when they change
Non-root user Limits damage if the process is compromised
Minimal base image Smaller attack surface and faster pulls
No secrets in the image Images are copied and shared; anything inside is exposed
One process per container Simpler scaling, logging, and restarts
Exec-form CMD The process receives signals and shuts down gracefully
Health check Lets orchestrators know whether it is ready

Also maintain a .dockerignore file that excludes version control data, local environment files, test data, and build output, so that secrets and junk never enter the build context.

3. Configuration and State

Follow the twelve-factor ideas that make services portable:

  • Configuration via environment variables or mounted files, not baked into the image (lesson 5).
  • Containers are stateless and disposable. Persistent data lives in a database or volume, not the container filesystem.
  • Logs go to standard output in a structured format; the platform collects them.
  • Graceful shutdown: on a termination signal, finish in-flight requests and stop accepting new ones. For the import worker, finish or safely release the current job so that it can be retried (idempotency from the quality course).
  • Fast startup, so scaling and deployment are quick.

4. Health Checks

Distinguish two questions:

Probe Question Used for
Liveness Is the process alive, or stuck and needing a restart? Restarts
Readiness Can it serve traffic now (database reachable, migrations done)? Routing traffic, rolling deployments

A readiness check that always returns “ok” makes every deployment look healthy. Make it reflect real dependencies, but avoid failing readiness on a non-essential dependency, which could take the whole service down because of a minor outage. For SignalDesk, the API’s readiness depends on the database; the model provider being slow should degrade summaries, not mark the API as down.

5. Local Multi-Service Environments

Developers need the whole system locally. A composition file describes it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: local-dev-only
    volumes: [dbdata:/var/lib/postgresql/data]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
  queue:
    image: redis:7
  api:
    build: .
    command: python -m signaldesk.api
    environment:
      DATABASE_URL: postgresql://postgres:local-dev-only@db/signaldesk
      QUEUE_URL: redis://queue:6379
    depends_on:
      db: { condition: service_healthy }
    ports: ["8000:8000"]
  worker:
    build: .
    command: python -m signaldesk.worker
    environment:
      DATABASE_URL: postgresql://postgres:local-dev-only@db/signaldesk
      QUEUE_URL: redis://queue:6379
volumes:
  dbdata:

Use clearly fake local credentials. This same file supports the quality course’s integration tests (a real database) and the developer guide’s quickstart (make setup).

6. Images in the Pipeline

  • Tag each image with the commit and version, and record its digest. Deploy by digest.
  • Scan the image and its dependencies for known vulnerabilities, and scan for secrets before pushing. Decide the policy: which severities block, and how exceptions are recorded and expire (the security course goes deeper).
  • Generate a software bill of materials (SBOM) and sign images where your tooling supports it, so that you can verify provenance.
  • Use a private registry with access control, and set retention rules so that old images are cleaned but those in use or recent releases are kept.
  • Rebuild base images regularly to pick up security patches; unchanged application code still needs fresh bases.
  • Test the image, not only the code: run the container in the pipeline and call its health endpoint and a smoke test.

7. Orchestration, Briefly

Running many containers across machines needs an orchestrator (Kubernetes is the best-known; managed container services are simpler). They provide scheduling, restarts, scaling, service discovery, and rolling updates. You need one when you run more than a few services or need automatic scaling and recovery. For a small pilot, a managed container service or even a single host with a composition file may be the right trade-off; record the choice as an ADR (documentation course) and revisit it as load grows. Lessons 4 and 6 use generic terms that map to any of these.

8. Common Mistakes

  • Using latest as a base or deployment tag.
  • Running as root, or with the whole filesystem writable when it need not be.
  • Installing build tools, caches, or test data in the final image.
  • Baking environment-specific configuration or secrets into the image.
  • Ignoring signals, so deployments hang until killed.
  • Huge images that slow every deployment and widen the attack surface.
  • Treating a container as a small server that is patched in place.

9. Using AI for Container Work

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Act as a container security and build expert.

Inputs:
- The application's language, dependency files, and entry command: [paste]
- Existing Dockerfile and composition file (if any): [paste]
- Runtime requirements: port, health endpoint, signals, user: [paste]

Tasks:
1. Draft a multi-stage Dockerfile and a .dockerignore.
2. Explain each decision briefly: base image choice, layer order,
   user, health check.
3. List risks in the result: secrets, root, unpinned versions,
   missing signal handling, large layers.
4. Suggest the pipeline checks for the image: scan, SBOM, smoke test.

Pin versions. Do not add secrets. Mark any base image tag you cannot
verify as needing confirmation.

Check recommendations against reality: build the image, run it, inspect its size and layers, confirm it runs as a non-root user, and attempt a graceful shutdown. Models often suggest base image tags or package names that do not exist or that are outdated.

10. Practical Exercise

For SignalDesk (or your project):

  1. Write multi-stage Dockerfiles for the API and the worker (or one image with different commands), plus .dockerignore.
  2. Add liveness and readiness endpoints, and make readiness reflect real dependencies.
  3. Verify non-root execution and graceful shutdown, including a worker interrupted mid-job.
  4. Write the composition file so that make setup starts the whole system.
  5. Add to the pipeline: build, scan for vulnerabilities and secrets, generate an SBOM, push by digest, and run a smoke test against the running container.
  6. Record image size and build time, then optimize layers and measure again.
  7. Run the AI prompt, build and test what it proposes, and fix its mistakes.
  8. Document the image, configuration, and run instructions in the developer guide.

Verification

You are ready to continue when:

  • The image builds from a clean checkout and runs identically in the pipeline and locally.
  • It runs as a non-root user, contains no secrets, and shuts down gracefully.
  • Readiness reflects real dependencies, and liveness does not restart a healthy service.
  • Base images and tools are pinned, and scans run with a recorded policy.
  • Images are identified by digest and stored in a registry with retention rules.
  • A new developer can start the full local environment with one command.

Key Takeaways

  • Containers package the application and its dependencies, giving identical artifacts across environments.
  • Use multi-stage builds, pinned minimal bases, non-root users, and no secrets in images.
  • Keep containers stateless and configurable, with health checks and graceful shutdown.
  • Scan, tag by digest, and store images with metadata; test the image itself.
  • AI drafts container files quickly, but you must build, run, and inspect them.

What’s Next?

Containers run somewhere. Next, we define that somewhere as code: networks, databases, queues, and compute created from versioned, reviewed definitions instead of console clicks.