Rana Maninder Singh
Lesson 6 of 12DevOps & Platform Engineering

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:

  1. Explain the difference between an image, a container, and a registry.
  2. Write a production-quality Dockerfile using multi-stage builds and a non-root user.
  3. Understand how layer caching works and arrange layers to maximise cache hits.
  4. Add health checks and apply runtime resource limits.
  5. Scan an image for vulnerabilities and interpret the results.
  6. Handle logs correctly so that containerised applications integrate with standard tooling.
  7. 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

ConceptWhere 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 bottom

If 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

RoleResponsibility
Backend engineerWrites and maintains the Dockerfile
Platform engineerConfigures registry, CI pipeline image build step
Security engineerReviews scan results, sets CVE policy (#cyber9)
On-call SRESets 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 root in 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:

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=512Mi

Logs

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).

Security: what not to put in an image

ForbiddenWhyCorrect alternative
.env files with real valuesStored in image layer history, readable by anyone with pull accessUse runtime secret injection (#cyber5, #cloud11)
Private SSH keys or API tokensSame reasonMount at runtime or use a secrets manager
Hardcoded database passwordsSame reasonEnvironment variable injected by orchestrator
--no-check-certificate in package installAllows MITM of dependenciesUse 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 added

The .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:

  1. FROM python:3.11 — uses a full image; should use python:3.11-slim or a multi-stage build.
  2. COPY . . before pip install — busts dependency cache on every code change.
  3. ENV SECRET_KEY=... — bakes a secret into the image; it appears in docker history. (Critical)
  4. No non-root user — runs as root in production.
  5. Tests run in the same stage as the runtime image — test dependencies end up in the image.
  6. No health check.
  7. No .dockerignore referenced — .git, tests/, .env may 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:

Acceptance criteria:


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:

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:

⚠️ 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

MistakeConsequencePrevention
Putting secrets in ENV or COPYVisible in docker history; a permanent security exposureInject secrets at runtime via orchestrator
Running as rootContainer escape risk is much higherAlways define and switch to a non-root user
Large, unoptimised base imageLonger pulls, larger attack surface, more CVEsUse -slim, distroless, or alpine; prefer multi-stage
COPY . . before dependency installCache busted every commit; slow buildsCopy dependency manifests first, install, then copy source
No .dockerignoreSensitive files, test data, .git end up in imageTreat .dockerignore as mandatory, reviewed in PR
Logging to files inside the containerLogs lost when container restarts; not collected by platformAlways log to stdout/stderr
Using :latest tag in productionRollbacks unreliable; undetermined what is runningUse semver tags and digest references
No registry retention policyStorage cost accumulates; old vulnerable images remain pullableImplement 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 questionLesson section
Image vs container vs registryPlain English
Layer caching orderPlain English → Layers
Non-root justificationWalkthrough → Non-root
Multi-stage build purposeWalkthrough → Multi-stage
Secret handling in imagesWalkthrough → Security table, Failure chain

Takeaways


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:

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.