Lesson 6: Docker and Container Engineering
Lesson opener
In one line: A container packages your application and its dependencies into a portable, isolated unit that runs the same way on a laptop, a CI runner, and a production server.
Why it matters: At Northline, "it works on my machine" used to be the single most common cause of staging failures. Containers eliminated that class of bug and, when built correctly, also become the primary security and compliance boundary around each service.
Before this lesson: Install Docker Desktop on your workstation (#setup8). You should understand the CI/CD pipeline (#devops1–4) that builds and publishes the images you will create here. Secrets hygiene (#cyber5) is essential before writing any Dockerfile.
Learning objectives
By the end of this lesson you will be able to:
- Explain the difference between an image, a container, and a registry.
- Write a production-quality Dockerfile using multi-stage builds and a non-root user.
- Understand how layer caching works and arrange layers to maximise cache hits.
- Add health checks and apply runtime resource limits.
- Scan an image for vulnerabilities and interpret the results.
- Handle logs correctly so that containerised applications integrate with standard tooling.
- Identify when a container is not the right packaging choice.
Lesson deliverable: A Dockerfile for a fictional Northline Python API service, using multi-stage build, non-root user, health check, and .dockerignore, accompanied by a short written rationale for each decision.
Prerequisites
| Concept | Where covered |
|---|---|
| CI pipeline artifact publishing | #devops1–4 |
| Docker Desktop installed | #setup8 |
| Secrets management basics | #cyber5 |
| Deployment strategies that consume images | #devops5 |
| Cloud registry concepts | #cloud1, #cloud8 |
Plain English: what is a container?
Think of shipping containers on a cargo ship. Before standardised containers, every port needed to know the shape, weight, and handling instructions for every item. With standard containers, the port only needs to know how to move a 20-foot steel box — the contents are someone else's problem.
A Docker image is the blueprint for a container — a read-only, layered filesystem snapshot that includes your code, the runtime, and all dependencies. A container is a running instance of that image, with its own isolated process space, network interface, and filesystem overlay. A registry (like Docker Hub, GitHub Container Registry, or a Northline private registry) is the warehouse where images are stored and versioned.
The key insight: the image is immutable. You do not patch a running container — you build a new image, scan it, and deploy it. This immutability is what makes rollbacks reliable (see #devops5).
Layers and caching
A Dockerfile is a sequence of instructions. Each instruction creates a new filesystem layer. Docker caches layers: if the instruction and its inputs have not changed since the last build, Docker reuses the cached layer instead of re-running the instruction. This makes builds fast.
The practical rule: put the things that change least frequently at the top, and the things that change most frequently at the bottom.
FROM python:3.12-slim ← changes only when you upgrade Python
COPY requirements.txt . ← changes when dependencies change
RUN pip install -r requirements.txt ← expensive; cached unless requirements.txt changed
COPY . . ← changes every commit; always near the bottomIf you put COPY . . before pip install, you bust the dependency-install cache on every commit, adding minutes to every build.
Walkthrough: building the Northline API service image
Business objective
The northline-billing-api is a FastAPI service (#api5) that must run in CI, staging, and production with identical behaviour. The image must be minimal (small attack surface), built by a non-root user, scannable for CVEs, and compatible with the Kubernetes runtime (#devops7).
Owners
| Role | Responsibility |
|---|---|
| Backend engineer | Writes and maintains the Dockerfile |
| Platform engineer | Configures registry, CI pipeline image build step |
| Security engineer | Reviews scan results, sets CVE policy (#cyber9) |
| On-call SRE | Sets and monitors runtime resource limits |
Repository layout
billing-api/
├── Dockerfile
├── .dockerignore
├── requirements.txt
├── pyproject.toml
├── app/
│ └── main.py
└── tests/The .dockerignore file is as important as the Dockerfile. Everything not needed at runtime — tests, .git, local environment files, tmp/ — must be excluded. Leaking a .env file into an image is a critical security incident.
Full production Dockerfile
# ── Stage 1: build/test ──────────────────────────────────────────────────────
FROM python:3.12-slim AS builder
WORKDIR /build
# Install build dependencies separately for better caching
COPY requirements.txt .
RUN pip install --no-cache-dir --upgrade pip \
&& pip install --no-cache-dir -r requirements.txt
# Copy source; run tests at build time so a failing test fails the build
COPY . .
RUN python -m pytest tests/ -q --tb=short
# ── Stage 2: runtime ─────────────────────────────────────────────────────────
FROM python:3.12-slim AS runtime
# Create a non-root user and group
RUN groupadd --gid 1001 appgroup \
&& useradd --uid 1001 --gid appgroup --shell /bin/false --no-create-home appuser
WORKDIR /app
# Copy only installed packages and source from builder
COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
COPY --from=builder /build/app ./app
# Drop to non-root before the CMD
USER appuser
EXPOSE 8000
# Health check: hits the /healthz endpoint every 30 s; 3 consecutive failures = unhealthy
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthz')"
CMD ["python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]Why multi-stage?
The builder stage installs build tools and runs tests. None of those tools (compilers, test frameworks, build metadata) belong in the runtime image. The runtime stage starts fresh from the same base and copies only what is needed. The resulting image is smaller and has a reduced attack surface — a win for both security (#cyber9) and pull times.
Why non-root?
Running a container as root means that if a vulnerability in your application allows code execution, the attacker has root-level access inside the container and a much easier path to container escape. Non-root is the default expectation in any Kubernetes security policy (see #devops7) and is required in Northline's security baseline (#cyber5).
Some workflows require elevated permissions (e.g., binding to port 80, writing to certain host paths). These cases require explicit justification and documented compensating controls reviewed by the security team. Do not use
USER rootin a production image without that review on record.
Health checks
The HEALTHCHECK instruction tells the Docker daemon (and by extension, Kubernetes) whether the container is actually serving traffic, not just running. A process can be alive without being ready. The health check endpoint (/healthz) should:
- Return
200 OKwithin the timeout. - Check that the application can connect to its database and any critical dependencies.
- Never return sensitive information in its response body.
Kubernetes uses liveness and readiness probes (#devops7) instead of Docker's HEALTHCHECK directly, but defining the check in the Dockerfile makes it available for local development and non-Kubernetes runtimes.
Vulnerability scanning
After building, the image is scanned in CI before being pushed to the registry. Northline uses Trivy (open source):
trivy image --exit-code 1 --severity CRITICAL northline-billing-api:2.3.0-rc1--exit-code 1 fails the CI step if any CRITICAL CVE is found, blocking promotion (see #devops5 gates). HIGH severity results are reviewed by a human before UAT promotion. ⚠️ Scanner availability and policy thresholds are environment-dependent; confirm with the security team which severities block the pipeline in your context.
The scan result is stored as a CI artifact (not in the image). Never log CVE details to standard output in production; they belong in the security tooling, not in application logs.
Runtime resource limits
A container without resource limits can consume all CPU and memory on a host, starving other workloads. Limits are set at the orchestrator level (#devops7), not in the Dockerfile. However, the Dockerfile author should document expected resource requirements in a comment or accompanying README:
# Expected resource profile (set in Kubernetes manifests):
# requests: cpu=250m, memory=256Mi
# limits: cpu=500m, memory=512MiLogs
Containers must log to stdout and stderr — never to files inside the container filesystem. The container runtime (Docker, Kubernetes) collects these streams and forwards them to the centralised logging platform (#sad5).
- Use structured JSON logging (one JSON object per line) so that the log platform can index fields.
- Never log secrets, tokens, PII, or full request payloads (#cyber5, #sad9).
- Include a correlation ID on every log line so distributed traces can be reconstructed (#sad7).
Security: what not to put in an image
| Forbidden | Why | Correct alternative |
|---|---|---|
.env files with real values | Stored in image layer history, readable by anyone with pull access | Use runtime secret injection (#cyber5, #cloud11) |
| Private SSH keys or API tokens | Same reason | Mount at runtime or use a secrets manager |
| Hardcoded database passwords | Same reason | Environment variable injected by orchestrator |
--no-check-certificate in package install | Allows MITM of dependencies | Use verified registries; pin package hashes |
Worked examples
Example A: Node.js multi-stage build
A Northline frontend tool is built with Node.js. The build step transpiles TypeScript, runs unit tests, and produces a dist/ folder. The runtime only needs node and dist/. The Dockerfile uses a builder stage with full Node.js toolchain and a runtime stage from node:20-alpine that copies only dist/ and node_modules (production only). The final image is 120 MB instead of 850 MB.
Example B: When a container is not the answer
A data science team wants to containerise their Jupyter environment for model training. The training job needs GPU drivers that are version-pinned to the host OS. The overhead of matching CUDA drivers inside the container to the host drivers adds significant complexity and the training jobs run on bare-metal nodes anyway. The team uses a virtual environment with pinned dependencies and a direct job scheduler instead. This is a legitimate case where a container adds friction without proportionate benefit. See #mlops\* for ML-specific packaging patterns.
Failure chain: the image that became a security incident
Engineer copies .env file into image for "convenience" during debugging
→ .env contains a staging database password
→ Image pushed to shared registry (internal, but accessible to all engineers)
→ Image pulled for unrelated debugging session six months later
→ Engineer runs `docker history` and sees the ENV layer
→ Password found — credential rotation required
→ Post-incident: .dockerignore audit, registry access review, pre-push hook addedThe .env file was in a layer that was never used by the CMD — it was invisible in the running container but permanently visible in the image history. docker history --no-trunc is all it takes to read it.
Guided exercise
Scenario: A junior engineer has written the following Dockerfile for a Python service:
FROM python:3.11
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
ENV SECRET_KEY=mysupersecretkey123
RUN python -m pytest tests/
CMD ["python", "app.py"]Task: Identify every problem in this Dockerfile and write a corrected version with brief comments explaining each fix.
Solution
Problems identified:
FROM python:3.11— uses a full image; should usepython:3.11-slimor a multi-stage build.COPY . .beforepip install— busts dependency cache on every code change.ENV SECRET_KEY=...— bakes a secret into the image; it appears indocker history. (Critical)- No non-root user — runs as root in production.
- Tests run in the same stage as the runtime image — test dependencies end up in the image.
- No health check.
- No
.dockerignorereferenced —.git,tests/,.envmay be copied in.
Corrected version:
# ── Stage 1: builder ─────────────────────────────────────────────────────────
FROM python:3.11-slim AS builder
WORKDIR /build
# Copy dependencies first; cached unless requirements.txt changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy source and run tests
COPY . .
RUN python -m pytest tests/ -q
# ── Stage 2: runtime ─────────────────────────────────────────────────────────
FROM python:3.11-slim AS runtime
RUN groupadd --gid 1001 app && useradd --uid 1001 --gid app --no-create-home appuser
WORKDIR /app
COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=builder /build/app.py .
USER appuser
# SECRET_KEY is injected at runtime via the orchestrator's secret store — never baked in
HEALTHCHECK --interval=30s --timeout=5s CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/healthz')"
CMD ["python", "app.py"]Note: .dockerignore must exclude tests/, .env, .git, *.pyc, __pycache__/.
Independent exercise
Task: Write a production Dockerfile for a Northline Go service (northline-jobs-api) that:
- Compiles the Go binary in a builder stage.
- Copies only the binary (statically linked) to a
scratchordistrolessruntime image. - Runs as a non-root user (UID 1001).
- Exposes port 9090.
- Includes a health check.
Acceptance criteria:
- [ ] Multi-stage build with named stages.
- [ ] Runtime image is
gcr.io/distroless/static-debian12orscratchwith a copied passwd entry. - [ ] No build tools in the runtime image (verify with
docker run --rm <image> sh— should fail). - [ ] Non-root user defined and used.
- [ ] Health check present and syntactically valid.
- [ ] No secrets,
.envfiles, or test directories copied into any stage. - [ ]
.dockerignoreexcludes_test.gofiles,.git, andvendor/if not used.
Registry hygiene and image lifecycle
Building a secure image is half the work. The other half is managing images in the registry responsibly.
Tagging strategy
Never use :latest in production. latest is a mutable pointer — it can change without warning and makes rollbacks unreliable. Northline uses:
- Semantic version tags for releases:
billing-api:2.3.0 - Git SHA tags for traceability:
billing-api:abc1234f - Both together in CI: the same image is pushed with both tags, so you can find it by version or by commit.
An image tagged with only a semver tag can be overwritten if someone re-runs the build. To guarantee immutability, use the image digest (a SHA-256 hash of the manifest) in production manifests:
# Kubernetes manifest: reference by digest, not tag
image: registry.northline.internal/billing-api@sha256:d4e8f3c1...This digest is immutable. Even if the tag is reused with a different image, the digest always refers to the exact same layer set.
Image retention and cleanup
A registry that accumulates thousands of images incurs storage cost and becomes a security liability (old images are never scanned again but remain pullable). Northline's registry policy:
- Keep the last 10 semver tags per image.
- Keep any image referenced in an active Kubernetes deployment.
- Delete everything else after 90 days.
- Images with known CRITICAL CVEs that are no longer deployed are deleted within 7 days.
⚠️ Retention policies are environment-dependent. Some regulated industries require longer retention for compliance. Confirm with your security and compliance teams before configuring deletion.
Image signing (awareness)
Image signing (via tools like Sigstore/Cosign) creates a cryptographic attestation that the image was built by a trusted CI system and has not been tampered with. Northline's Kubernetes admission controller verifies signatures before allowing an image to run. This prevents a compromised registry push from deploying an unauthorised image.
This is an awareness topic at this stage — refer to #cyber9 for the full supply-chain security curriculum.
Common mistakes
| Mistake | Consequence | Prevention |
|---|---|---|
| Putting secrets in ENV or COPY | Visible in docker history; a permanent security exposure | Inject secrets at runtime via orchestrator |
| Running as root | Container escape risk is much higher | Always define and switch to a non-root user |
| Large, unoptimised base image | Longer pulls, larger attack surface, more CVEs | Use -slim, distroless, or alpine; prefer multi-stage |
| COPY . . before dependency install | Cache busted every commit; slow builds | Copy dependency manifests first, install, then copy source |
No .dockerignore | Sensitive files, test data, .git end up in image | Treat .dockerignore as mandatory, reviewed in PR |
| Logging to files inside the container | Logs lost when container restarts; not collected by platform | Always log to stdout/stderr |
Using :latest tag in production | Rollbacks unreliable; undetermined what is running | Use semver tags and digest references |
| No registry retention policy | Storage cost accumulates; old vulnerable images remain pullable | Implement a retention policy reviewed by security and compliance |
Quick checks
Q1: What is the difference between an image and a container?
A: An image is an immutable, layered filesystem snapshot (the blueprint). A container is a running instance of that image with its own isolated process space and writable layer.
Q2: Why does layer order matter in a Dockerfile?
A: Docker caches layers; a change to any layer invalidates all layers below it. Placing frequently-changing instructions (COPY source code) after rarely-changing ones (installing dependencies) maximises cache hits and reduces build time.
Q3: Why is running a container as root a security risk?
A: If an attacker exploits a vulnerability and achieves code execution, they have root-level access inside the container, significantly lowering the bar for container escape to the host.
Q4: What is the purpose of a multi-stage build?
A: To separate build-time tools and test dependencies from the runtime image, producing a smaller, cleaner image with a reduced attack surface.
Q5: Where should a containerised application write its logs?
A: To stdout and stderr. The container runtime collects these streams and forwards them to the centralised log platform. Writing to files inside the container loses logs on restart and bypasses platform observability.
Quiz alignment
| Quiz question | Lesson section |
|---|---|
| Image vs container vs registry | Plain English |
| Layer caching order | Plain English → Layers |
| Non-root justification | Walkthrough → Non-root |
| Multi-stage build purpose | Walkthrough → Multi-stage |
| Secret handling in images | Walkthrough → Security table, Failure chain |
Takeaways
- Images are immutable. Never patch a running container — rebuild, scan, and redeploy.
- Layer order is a performance decision; always put slow, stable steps before fast, changing ones.
- Multi-stage builds produce smaller, safer runtime images. Use them by default.
- Non-root is the baseline. Document any exception and have it security-reviewed.
- Secrets do not belong in images at any stage, including ENV instructions. Inject at runtime.
- Log to stdout/stderr; use structured JSON; include correlation IDs; never log secrets.
Container runtime and orchestrator relationship
Docker Desktop (#setup8) is the local development runtime. In production, Northline's Kubernetes cluster (#devops7) uses containerd as the container runtime — Docker is not involved at runtime. The interface between Kubernetes and the container runtime is the Container Runtime Interface (CRI). This means:
- The same image (built with Docker, OCI-compliant) runs identically in both contexts.
- Runtime resource limits, security contexts, and volume mounts are applied by the Kubernetes runtime, not Docker.
- Local
docker runtesting is useful for validating the image, but resource limits and security policies set in Kubernetes manifests are not exercised locally. Always test the full manifest in a staging cluster before promotion (#devops5).
Understanding this boundary prevents a common confusion: "it works in docker run with no issues" and "it fails in Kubernetes with a permission error" are not contradictions — they reflect the difference between local defaults and cluster-enforced security policies.
Bridge to next lesson
You now know how to build and secure a container image. The next lesson (#devops7) shows how Kubernetes takes that image, runs many copies of it, routes traffic between them, manages rolling updates, and enforces resource and security policies at scale — and when Kubernetes is more complexity than the problem warrants.