Containerization and Docker Fundamentals Questions
Packaging applications into containers: images and layers, Dockerfiles, registries, image optimization and security, container networking and storage, and the container runtime model. Covers how containers differ from virtual machines, image build and management, and the fundamentals that underpin any orchestration platform. The container primitive before orchestration.
Write a production-ready Dockerfile for a Python web service (for example a Flask or FastAPI app reading requirements.txt). Requirements: use a slim base image, install dependencies without leaving the pip cache in the final image, run as a non-root user, define a HEALTHCHECK, and order instructions to maximize build-cache reuse. Briefly justify your main choices.
Sample Answer
Direct answer
A production-ready Python web service Dockerfile needs, in order: a slim base image, dependencies installed from a copied requirements.txt before the rest of the source is copied (for cache reuse), no leftover pip cache in the final image, a non-root user for the running process, and a HEALTHCHECK that actually exercises the running service. Below is a Dockerfile that was built and run to confirm all five requirements hold, not just written to look right.
The Dockerfile, and why each choice was made
FROM python:3.12-slim AS base
RUN addgroup --system app && adduser --system --ingroup app app
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN chown -R app:app /app
USER app
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/')" || exit 1
CMD ["python", "app.py"]
python:3.12-sliminstead of the fullpython:3.12image keeps the base itself small (roughly 200 MB versus over a gigabyte for the full image), without giving up glibc compatibility for common data/ML wheels.COPY requirements.txt .thenRUN pip installhappens beforeCOPY . .: dependencies rarely change, source changes often, so this ordering means a source-only change does not invalidate the (often slow) dependency install layer.--no-cache-dironpip installstops pip from writing its download cache into the image at all, rather than writing it and deleting it in a later step (which would not shrink the layer that wrote it).- A dedicated
appsystem user and group are created, ownership of/appis fixed withchown, andUSER appswitches the running process off root before any application code executes. HEALTHCHECKactually opens a connection to the service's own port rather than just checking the process is alive, so a hung-but-still-running process gets correctly marked unhealthy.
Verified build and run
$ docker build -t python-service .
...
$ docker run -d --name svc -p 18000:8000 python-service
$ docker exec svc whoami
app
$ curl http://127.0.0.1:18000/
{"status":"ok"}
$ docker images python-service --format '{{.Size}}'
221MB
$ docker inspect --format='{{.State.Health.Status}}' svc # after the start period elapsed
healthy
Every requirement was confirmed against the running container: non-root (whoami returns app, not root), the service actually responds, the image is 221 MB (slim base plus a small dependency, not the multi-gigabyte size a full base would produce), and Docker's own health status reports healthy once the check has run.
Edge cases and trade-offs
If requirements.txt needs a package with native extensions not available as a prebuilt wheel for this base image, pip install will try to compile from source and fail without a compiler present; that is a deliberate trade-off of a slim image, not a bug, and the fix is either a multi-stage build (compile in a fuller stage, copy only the installed packages across) or confirming manylinux wheels exist for every dependency. The chown -R app:app /app step touches every file copied in and adds a small amount of build time proportional to the number of files; for a very large codebase, narrowing it to just the directories the running process actually needs to read (rather than the whole /app tree) keeps that cost down. Finally, the HEALTHCHECK's --start-period needs to be long enough to cover the application's real startup time (framework initialization, warming any connection pools); too short a start period will mark a slow-starting but otherwise fine service as unhealthy during its first few checks.
Design a retention and cleanup policy for a private registry that's accumulated hundreds of tags from experiments, feature branches, and old releases. Balance storage cost against developer convenience, reproducibility, and rollback capability: lifecycle rules (keep latest N per branch pattern), tag immutability, and how you'd schedule garbage collection.
Sample Answer
Direct answer
I design retention as tiers keyed to what a tag actually represents, not a single blanket rule: release and production-facing tags are protected and effectively kept forever, branch and experiment tags decay automatically on a short clock, and garbage collection runs as a scheduled, low-traffic maintenance job rather than an ad hoc cleanup, so nobody has to manually decide what is safe to delete.
The design
| Tag class | Retention rule | Immutability | Rationale |
|---|---|---|---|
Release / semantic-version tags (v1.4.2, prod-*) | Keep indefinitely (or until an explicit, reviewed deprecation) | Immutable: once pushed, the tag can never be overwritten | These are the rollback targets; losing one or letting it silently change content is a production incident waiting to happen |
main/default-branch build tags | Keep last N (for example, last 20) plus anything referenced by a currently-deployed environment | Mutable is acceptable, but each build gets a unique tag (commit SHA or build number) so nothing is overwritten in place | Bounds storage growth from continuous integration while preserving enough history for a same-day rollback |
Feature-branch tags (feature/*, pr-*) | Keep the last 3 to 5 pushes per branch pattern, and expire automatically after a fixed idle window (for example, 14 days with no new push and no pull) | Mutable | These exist for review and short-lived testing; nobody rolls back to a feature branch's image in production |
Experiment / scratch tags (exp-*, ad hoc developer pushes) | Keep for a short fixed window (for example, 3 to 7 days) regardless of activity | Mutable | Genuinely disposable; the cost of keeping hundreds of these indefinitely outweighs the rare case someone wants one back |
Garbage collection (GC, the process of reclaiming storage for image layers no longer referenced by any remaining tag or manifest) is scheduled during low-traffic hours rather than triggered manually, because a naive GC run that walks the whole blob store while pushes are actively happening can race with an in-flight push and, on registries that require it, needs the registry put into a read-only or maintenance mode for the duration. This differs sharply by registry implementation and matters when choosing one: a self-hosted registry (the open-source Docker Registry, or Harbor, a registry that adds retention policies and tag immutability rules on top of it) needs an explicit, scheduled GC job and, on the open-source registry specifically, historically needs the registry to be read-only while GC runs to avoid corrupting in-flight uploads. A managed registry like Amazon ECR (Elastic Container Registry, AWS's managed container registry) has no manual GC step at all: you configure lifecycle policies (rules like "expire untagged images after 14 days" or "keep only the last 10 images matching feature/*") and the service reclaims storage automatically and continuously.
Worked example
For a registry that has accumulated hundreds of tags from months of unmanaged experimentation, the rollout is staged rather than a one-shot deletion: first, tag every existing image against the classification above (a one-time audit script that reads push metadata and branch-name patterns), then apply the new lifecycle rules going FORWARD only (new pushes obey the tiers immediately), then run a single manual cleanup pass on the pre-existing backlog using the same rules with a dry-run flag first, so the retention design is validated against real data before anything is actually deleted. Concretely, an ECR lifecycle policy rule expressing the feature-branch tier looks like: match tag prefix feature/, keep the most recently pushed 5 images matching that prefix, expire the rest. A second rule expresses the experiment tier: match tag prefix exp/, expire any image pushed more than 7 days ago, with no count-based exception.
Trade-offs and pitfalls
The main cost-versus-convenience trade-off is the idle-window length on feature and experiment tags: a shorter window saves more storage but increases the chance someone needs an image that already expired (usually recoverable by rebuilding from source, since the tag was never a durable artifact, but still a real interruption). The most common design mistake is applying one retention rule uniformly across all tag classes, which either keeps release tags too loosely (a rollback target could theoretically be garbage-collected) or expires experimental tags too slowly (storage cost creeps up for images nobody was ever going to reuse). Tag immutability on release tags specifically closes a separate but related risk: without it, someone can accidentally push new content to an existing release tag, which silently breaks reproducibility for anyone who redeploys that "same" version later, independent of whatever the retention window is set to.
Write a minimal, secure multi-stage Dockerfile for a statically-linked Go service: build the binary in a builder stage and produce a minimal final image using scratch or a distroless base, running as a non-root user. Explain how CGO_ENABLED affects which final base image you can use, and how you'd embed build metadata (version, build time) into the binary.
Sample Answer
Direct answer
Build the static binary in a golang builder stage with CGO_ENABLED=0 (which disables cgo, Go's mechanism for calling C code, and forces a fully self-contained, statically linked binary with no dynamic C library dependency), then copy just that binary into a scratch (an entirely empty base image) or distroless (a minimal image with no shell, package manager, or other OS tooling beyond what the language runtime needs) final stage, running as a non-root user. CGO_ENABLED=0 is what makes scratch or distroless usable at all: with cgo enabled, the binary dynamically links against the host's C library, and a scratch image has no C library for it to find at runtime. Build metadata (version, build time) gets embedded at compile time via -ldflags -X, which sets the value of specific Go package-level string variables directly in the compiled binary, without any config file or environment variable needed at runtime.
Structured elaboration
The Dockerfile
# syntax=docker/dockerfile:1
FROM golang:1.23-alpine AS builder
WORKDIR /src
COPY go.mod ./
COPY main.go main_test.go ./
ARG VERSION=dev
ARG BUILD_TIME=unknown
RUN CGO_ENABLED=0 GOOS=linux go build \
-ldflags "-s -w -X main.version=${VERSION} -X main.buildTime=${BUILD_TIME}" \
-o /out/svc .
# A discrete test stage: CI runs `docker build --target test .` as a gate
# before it ever builds the `final` target below. It never appears in the
# final image's own dependency chain, so a plain `docker build .` (which
# resolves to the last stage, `final`) does not pay for the Go toolchain
# or re-run tests as part of shipping the artifact.
FROM builder AS test
RUN CGO_ENABLED=0 go test ./... -v
FROM gcr.io/distroless/static-debian12:nonroot AS final
COPY --from=builder /out/svc /svc
USER nonroot:nonroot
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
CMD ["/svc", "-healthcheck"]
ENTRYPOINT ["/svc"]
-ldflags "-s -w -X main.version=${VERSION} -X main.buildTime=${BUILD_TIME}" does two things: -s -w strip debug symbols to shrink the binary, and -X main.version=... -X main.buildTime=... overwrite the value of the named package-level string variables (declared in the Go source as var version = "dev") at link time, which is how the running binary can report its own version and build time without reading any file.
Why CGO_ENABLED decides your final base image
CGO_ENABLED=0: the Go toolchain avoids cgo entirely and produces a statically linked binary with no external C library dependency at all. That binary runs correctly onscratch(nothing else in the image) or a distroless static base, because it needs nothing from the base image except its own bytes.CGO_ENABLED=1(the default when cgo is used, for example by some database drivers ornetpackage DNS resolution modes): the binary dynamically links against the host's C library at build time and needs a compatible one present at run time. Shipping that binary onscratchfails outright (no C library exists there to load); it needs at minimum a distroless base variant that includes glibc, or a small distribution image, not the fully emptyscratchimage or the static distroless variant.
A discrete test stage, and why it is separate from final
Defining FROM builder AS test as its own stage lets CI run docker build --target test . as an explicit quality gate: if go test fails, that build step fails, and the pipeline stops before ever producing a shippable artifact. Because test is not in final's FROM chain, a plain build that targets final (the default target, being the last stage) never executes the tests as part of producing the production image; the test run is a separate, addressable step in CI, not baked into every build.
Non-root and why it matters here specifically
scratch and distroless images have no /etc/passwd, so USER nonroot:nonroot on the gcr.io/distroless/static-debian12:nonroot base relies on that image already defining a numeric non-root user (uid 65532, conventionally). Running as non-root means that even if the application were compromised through some other flaw, the compromised process would not hold root privileges inside its own container, narrowing what an attacker who gained code execution could do next (for example, it cannot bind privileged ports below 1024 or, on a properly configured host, escalate as easily through kernel-level capabilities that root retains by default).
A HEALTHCHECK with no shell available
Distroless and scratch images have no shell and no curl or wget to run as a health-check command. The pattern that still works is to have the binary itself perform the check: a small -healthcheck flag on the same binary that makes an HTTP request to its own /healthz endpoint and exits 0 or 1 accordingly, invoked directly (CMD ["/svc", "-healthcheck"], exec form, no shell involved).
Why multi-stage matters here beyond image size
Multi-stage builds improve security by keeping the Go compiler, source code, and build-time tooling entirely out of the shipped image (there is nothing in a distroless final stage for an attacker to use to compile or run arbitrary code, and no build-time secrets or cache files can leak into it if the COPY --from=builder only ever names the compiled binary). They improve deployability because the resulting image is a single small, self-contained binary with no OS package manager or shell to patch, version, or scan for unrelated vulnerabilities, and it starts as fast as the binary itself starts, with no runtime dependency resolution.
Worked example
Building the Dockerfile above with --build-arg VERSION=1.3.0 --build-arg BUILD_TIME=2026-09-24T00:12:54Z produces a final-stage image measuring 14.6 MB. Running docker build --target test . executes go test ./... -v, which prints --- PASS: TestVersionString (0.00s) and exits 0; a broken versionString() implementation would instead fail this build step, before final is ever built. Running the resulting container and calling its /version endpoint returns version=1.3.0 build_time=2026-09-24T00:12:54Z, exactly the values passed as build arguments, confirming the -ldflags -X substitution took effect. docker inspect on the running container shows Health.Status: healthy, produced by the binary's own -healthcheck flag rather than any shell command, since the final image has no shell to run one.
Trade-offs & pitfalls
- Leaving
CGO_ENABLEDat its default and only discovering the dynamic-linking requirement when ascratch-based image fails at container start (a missing shared library error) is a common and entirely avoidable mistake; decide the flag deliberately based on whether anything in the dependency tree actually needs cgo. - A fully empty
scratchfinal stage has no CA certificate bundle either, which breaks outbound TLS connections silently; either copy/etc/ssl/certs/ca-certificates.crtfrom the builder stage or use a distroless base (notstatic) variant that already includes it, depending on whether the service needs to make outbound HTTPS calls. - Debugging a distroless container in production is harder by design (no shell to
docker execinto); that is the intended trade-off for a smaller attack surface, and it means logging and the-healthcheck-style self-diagnostic pattern have to carry more of the debugging burden than they would in a full-featured base image.
Write an efficient multi-stage Dockerfile for a Node.js application with a package.json build script: use npm ci for reproducible installs, build static assets in one stage, and produce a minimal runtime image in the final stage. Order instructions so dependency installation is cached across builds when only source code changes, and set a sensible HEALTHCHECK and non-root user.
Sample Answer
Direct answer
An efficient multi-stage Node.js Dockerfile separates a build stage (install all dependencies with npm ci, build static assets) from a minimal runtime stage (install only production dependencies, copy in the built output), ordered so dependency installation is cached across builds when only source changes. Below is a Dockerfile that was built, run, and specifically re-built after a source-only change to confirm the caching claim, not just written to look right.
The Dockerfile
# Stage 1: install deps and build static assets
FROM node:20-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
# Stage 2: minimal runtime image
FROM node:20-slim AS runtime
RUN groupadd --system app && useradd --system --gid app app
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
COPY server.js ./
RUN chown -R app:app /app
USER app
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node -e "require('http').get('http://127.0.0.1:3000/', r => process.exit(r.statusCode === 200 ? 0 : 1)).on('error', () => process.exit(1))"
CMD ["node", "server.js"]
npm ci (not npm install) is used in both stages because it installs exactly what package-lock.json specifies and fails if the lockfile and package.json disagree, which is what makes the install reproducible across machines and CI runs. Both stages copy package.json/package-lock.json and run their own npm ci before copying the rest of the source, for the same cache-ordering reason as any other language: the dependency list changes far less often than the source. The runtime stage also creates a dedicated app system user and group and switches to it with USER app before the process starts, so the running container is non-root, and it declares a HEALTHCHECK that opens a real connection to the service rather than only checking the process is alive.
Verified build, cache behavior, and run
$ docker build -t node-app .
$ docker run -d --name napp -p 13000:3000 node-app
$ docker exec napp whoami # confirms the container is running as the non-root app user, not root
app
$ curl http://127.0.0.1:13000/
<h1>built asset</h1>
$ docker images node-app --format '{{.Size}}'
310MB
$ docker inspect --format='{{.State.Health.Status}}' napp
healthy
Then, changing only server.js (not package.json or package-lock.json) and rebuilding:
=> CACHED [build 4/6] RUN npm ci
=> CACHED [runtime 5/8] RUN npm ci --omit=dev
=> [runtime 7/8] COPY server.js ./
Both npm ci steps, in both stages, stayed CACHED; only the layer copying the changed server.js file re-ran. That confirms the ordering requirement is actually met, not just plausible-looking in the Dockerfile.
Edge cases and trade-offs
Running npm ci twice, once per stage, means the runtime stage re-downloads production dependencies rather than reusing the build stage's node_modules directly; this is deliberate (it guarantees the runtime stage never accidentally ships a dev-only dependency that leaked into the build stage's tree) but it does mean two separate installs to keep in sync, and both must read the same lockfile or they can drift. If npm run build needs devDependencies to run (bundlers, TypeScript) but the build fails silently because a dependency was pruned too early, that is a sign the --omit=dev install happened in the wrong stage; it must stay in the runtime stage only. Finally, a package-lock.json that is missing or out of sync with package.json makes npm ci fail outright (by design), which is the correct, loud failure mode compared to npm install's tendency to silently resolve a different dependency tree than what was tested.
Design a safe image-promotion pattern so the same artifact moves from development to staging to production with minimal drift: how tags, digests, and registry permissions ensure the exact image that was tested is the one that gets deployed, and how you'd prevent accidental rebuilds or tag-drift surprises along the way.
Sample Answer
Direct answer
The core principle is build once, promote everywhere: an artifact is built and given an immutable identity exactly once, and every later environment, staging and then production, references that same identity rather than triggering a second build from source. Drift, and the class of bug where something works in staging but not in production, overwhelmingly comes from an environment quietly building its own slightly different copy of "the same" release instead of promoting the one that was already tested.
The design
Build once. CI builds the image a single time per release candidate, tags it immutably and uniquely (a commit hash or a semantic release version), and records its digest (a digest is a cryptographic hash of the image's exact bytes; two images with the same digest are guaranteed to be byte-for-byte identical, unlike a tag, which can later be moved to point at different bytes) at that moment. No later pipeline stage is allowed to rebuild this artifact; staging and production only ever pull or reference it.
Promotion is a metadata operation, not a build. Promoting an artifact from staging to production re-tags the same digest for the next environment, for example adding app:v1.4.2-prod-approved alongside the existing app:v1.4.2, or a promotion tool simply records that this digest is now the production candidate. In a digest-pinned deploy configuration, promotion can be as simple as updating production's deploy manifest to reference the already-tested digest directly.
Registry permissions enforce the guardrail. CI's build identity gets write access to push new images and tags. Production's deploy identity gets read-only access, able to pull, never to push. If the registry supports tag immutability or protected tags, lock release tags so nothing, accidental or malicious, can silently repoint a tag after staging has already tested it. A human or an approval step gets permission to move a "promoted" pointer or write a deployment record, never to trigger a rebuild.
Preventing accidental rebuilds. The biggest practical source of drift is a Dockerfile or CI configuration that is not fully deterministic: a base image referenced by a floating tag like python:3.12-slim instead of a pinned digest, or an install step with no version pins, meaning two builds from "the same" source a day apart can legitimately produce different bytes. Pin base images by digest, pin dependency versions, and treat anything environment-specific, a database URL, a feature flag, as runtime configuration injected into the same image, never as a build-time difference that forces separate, environment-specific images.
flowchart LR
Commit["source commit"] --> Build["CI build (once)"]
Build --> Registry["registry: immutable digest"]
Registry --> Staging["staging deploy (pull-only)"]
Staging -->|"tests pass, promote"| Prod["production deploy (pull-only, same digest)"]
Worked example
A release pipeline for a checkout service: CI builds on merge to the main branch, tags checkout-service:2026.09.23-abc1234, and records the digest in a release manifest. Staging's deploy configuration is templated to always deploy checkout-service@<digest from the latest release manifest>. After staging's smoke tests pass, a promotion job, not a rebuild, copies that exact digest reference into the production deploy configuration and opens the standard change-approval process. Production's deploy identity has pull-only registry permissions, so even a compromised production deploy credential cannot push a different image under that same tag.
Trade-offs and pitfalls
Locking down write access this tightly adds real friction for a legitimate emergency change: a hotfix now has to go through the same build-once pipeline rather than a quick local build pushed straight to production, a deliberate trade of speed for guaranteed provenance. "Build once" is easy to violate by accident the moment any Dockerfile step reaches for something mutable, an unpinned base image tag, an unpinned package install, or a dependency resolved with no lockfile, so this whole design only holds if the Dockerfile itself is actually reproducible; otherwise the promotion discipline is being built on top of a build that was never deterministic to begin with.
Unlock Full Question Bank
Get access to all 18 Containerization and Docker Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.