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.
What's the difference between an image tag (like v1.2.3 or latest) and a content-addressable digest (sha256:...)? Why would you deploy by digest in production rather than by tag, and what commands would you use to get an image's digest after pushing it and reference that exact digest when pulling or deploying?
Sample Answer
Direct answer
A tag like v1.2.3 or latest is a mutable, human-friendly pointer that can be reassigned to a different image at any time. A digest like sha256:... is a content-addressable hash of the image's manifest: it can only ever refer to one exact set of bytes, and if the image content changes, the digest changes with it. You deploy by digest in production so that "deploy version 1.2.3" cannot silently mean a different image today than it meant yesterday.
Why tags are not enough for production
Nothing stops someone (or an automated pipeline) from pushing a new image and re-pointing an existing tag at it; latest is the most obvious case, but even a version-looking tag like v1.2.3 can be overwritten by a re-push. If your deployment manifests reference myapp:v1.2.3, a rollback, an incident replay, or a second cluster pulling the "same" tag at a different time can end up running genuinely different bytes without any change to your deployment configuration. A digest closes that gap: myapp@sha256:abc123... is the same image forever, because the hash is computed from the image's actual manifest content.
Worked example
Getting an image's digest after pushing it, verified directly against a local image:
$ docker inspect --format='{{index .RepoDigests 0}}' alpine:3.20
alpine@sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc
(docker push also prints the digest directly in its final output line when you push to a registry.) To reference that exact digest afterward, whether pulling manually or writing a deployment manifest, you swap the tag for the digest in the same repository[:tag] position:
$ docker pull alpine@sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc
or, in a Kubernetes (a system for orchestrating containers across many machines) pod spec or a docker run/Compose file, image: myregistry/myapp@sha256:abc123... instead of image: myregistry/myapp:v1.2.3. Whoever runs that reference, on whatever machine, on whatever day, gets the identical image content, because the reference is the content's hash rather than a label someone assigned to it.
Trade-offs
Digests are unreadable to a human glancing at a deployment manifest (nobody can tell sha256:abc123... is "the release from last Tuesday" without cross-referencing a build log), so most teams keep both: a semantic or commit-SHA tag for humans and CI/CD (continuous integration and continuous delivery) tooling to reason about, and pin the actual deployed reference by digest so the running artifact is provably immutable regardless of what the tag does later.
Design a health-check strategy for a containerized service whose startup can take several minutes and whose dependencies may be temporarily unavailable. How would you configure HEALTHCHECK (start period, interval, retries) and restart policy so deployments are safe without being overly fragile, and what would you still want in logs and metrics on top of the health check itself?
Sample Answer
Direct answer
For a service with a genuinely slow startup and flaky dependencies, size HEALTHCHECK's start_period to comfortably exceed the worst realistic startup time (including retries against a slow dependency), keep interval and retries tight enough that a true failure is caught within your deployment tool's own timeout, and keep the restart policy focused on crashes, not on health status, since plain Docker does not restart a container just because it reports unhealthy. On top of the health check itself, add startup-phase logging and a small number of metrics (time to first healthy, dependency-connect latency, restart count) so you can tell "slow but fine" apart from "actually stuck" without staring at docker inspect.
Structured elaboration
Sizing the HEALTHCHECK knobs
start_period: failures during this window do not count towardretriesand do not flip the container tounhealthy; the status showsstartinginstead. Set it to comfortably exceed your measured p99 startup time (dependency waits included), not your typical case. If startup can occasionally take three minutes when a dependency is slow, a sixty-secondstart_periodwill produce exactly the flapping this design is meant to avoid.intervalandtimeout: once paststart_period, these control how quickly you detect a real regression. A shorter interval catches problems sooner but adds load; atimeoutshorter than the check's own worst-case latency will produce false failures under normal load, not just real outages.retries: the number of consecutive failures required to flip tounhealthy. Combined withinterval, this is your total detection latency afterstart_periodends (interval x retries, roughly). Tune it against whatever consumes the status: a deployment tool waiting for containers to become healthy before proceeding, or an operator dashboard.
Restart policy, and the boundary it does not cross
- A restart policy (
on-failure[:max-retries],always,unless-stopped) reacts to the container's process exiting, not to the health status. A container can sit atunhealthyindefinitely without ever being restarted by Docker itself. This matters here specifically: if a dependency is temporarily unavailable, you want the health check to sayunhealthy(so the status is honest and load balancers or an orchestrator can act on it) without the container being torn down and restarted, which would only add restart churn on top of an already-degraded dependency and could reset any warm state (caches, pooled connections) for no benefit. - Use
on-failure:Nfor genuine crash protection (the process actually exits), and let the health status, not the restart policy, communicate "temporarily degraded, dependency down."
What still belongs in logs and metrics, beyond the health check
- A single structured log line per startup phase (config loaded, dependency connected, ready to serve) so a human can see exactly where a slow startup is spending its time, rather than staring at a binary
unhealthyflag. - A startup-duration metric (time from process start to first successful health check) so a slow trend is visible before it becomes an outright failure.
- A dependency-connect-attempt counter or histogram, so "dependency flaky" is a graph, not a guess reconstructed from timestamps in raw logs after the fact.
- The count of consecutive health-check failures and the current status, exported as a metric, so dashboards and alerting do not have to poll
docker inspectto know what Docker already knows internally.
Worked example
A service depends on a message broker that occasionally takes up to 90 seconds to accept connections during a rolling broker upgrade, and the service itself otherwise starts in about 5 seconds. Setting start_period=120s, interval=5s, timeout=3s, retries=3 gives the connection up to two minutes to succeed before any failure counts at all, and once past that window, a real failure is confirmed within about 15 seconds (3 retries x 5s). The restart policy is on-failure:5: if the process actually crashes (a bug, not a slow dependency), it gets a bounded number of automatic restarts, but a container that is merely waiting on a slow broker is never killed by Docker itself; it stays starting, then unhealthy if the broker genuinely does not come back, and an operator or orchestrator layered on top decides what to do about that, informed by the startup-phase logs showing exactly which dependency it was still waiting on.
Trade-offs & pitfalls
- A
start_periodset too long delays real detection: a container that is actually broken (not just slow) will look identical to a healthy one for that entire window. - A
start_periodset too short reintroduces the original problem: legitimate slow starts get flagged as failures, and if something downstream (a deployment tool, an orchestrator) does act on that status, you get exactly the premature restart churn this design is trying to prevent. - Relying on the restart policy to "fix" a container stuck at
unhealthyis a common but wrong instinct on plain Docker: it will not restart on health status alone, so the actual remediation (alerting a human, or letting an orchestrator's own readiness/liveness model act) has to live somewhere else.
Compare three ways to deliver runtime secrets (API keys, database credentials) to a running container: plain environment variables, a mounted secret file, and fetching from an external secrets provider at startup. Discuss the security and operational trade-offs of each.
Sample Answer
Direct answer
All three approaches get a secret into a running container, and they trade off along the same two axes every time: how easily the secret leaks to somewhere it should not, process listings, logs, crash dumps, and how much operational machinery, rotation, an external dependency at startup, the approach requires. Environment variables are the easiest to wire up and the easiest to leak. A mounted file is a meaningfully better default for most services. An external secrets provider fetched at startup is the strongest option once rotation and centralized audit actually matter enough to justify the added dependency.
Comparison
| Method | How it works | Leak surface | Rotation | Operational cost |
|---|---|---|---|---|
| Environment variable | Set via a run flag or the orchestrator's own secret-as-env-var feature | Visible in docker inspect, often readable from the process's own environment file under /proc, frequently and accidentally logged by frameworks that dump their configuration on startup or in a crash report, inherited automatically by every child process the application spawns | Requires a full container restart with a new value | Lowest; no extra tooling |
| Mounted secret file | Secret content written to a file, for example /run/secrets/db_password, via a volume, a tmpfs mount, or the orchestrator's native secrets object | Confined to a filesystem path with normal file permissions, not exposed in docker inspect or the process environment, not automatically inherited by child processes, but still readable in plaintext by anything with filesystem access inside the container | The orchestrator can often update the file's content in place without restarting the container, if the application re-reads the file | Low; most orchestrators provide this as a first-class primitive |
| External secrets provider fetched at startup | The application, or an init process, calls a secrets manager over the network at startup and holds the value only in memory | Never touches disk or a layer at all if handled carefully; centralizes access logging, who fetched which secret and when, at the provider itself; a bug that dumps process memory is still a real risk | Best: can rotate centrally and have the application re-fetch on an interval or a signal, with no container restart at all | Highest; a network dependency at container startup, plus its own availability and authentication concerns |
The decision
For most services, a mounted file beats a plain environment variable for the same delivery need, because it closes off the two most common accidental-leak paths, inspect output and inherited child-process environment, for close to zero extra operational cost; most orchestrators already support this as a first-class primitive. Paying for an external provider makes sense once rotation genuinely matters operationally, credentials that must rotate on a schedule or be revoked immediately after an incident, or once there are enough services that centralized access auditing is worth more than the added startup dependency. For a small number of low-change-frequency secrets, an external provider is often more machinery than the risk actually justifies.
What none of these three replace
Choosing among them is never a substitute for restricting who can execute into the container or read its filesystem and inspect output in the first place. All three assume some baseline of access control around the host and orchestrator; the delivery mechanism narrows the leak surface, it does not eliminate the need for that baseline.
Worked example
Take one database password, CorrectHorseBattery9, delivered three ways to a running container; the environment-variable and mounted-file cases below were built and run directly to confirm the claims above.
As a plain environment variable (docker run -e DB_PASSWORD=CorrectHorseBattery9 ...): docker inspect <container> --format='{{json .Config.Env}}' prints it straight back in cleartext, ["DB_PASSWORD=CorrectHorseBattery9", ...]. A shell spawned inside that same container inherits it with no extra step: running sh -c "env | grep DB_PASSWORD" from inside the container shows the child shell already has it, which is the concrete evidence behind "inherited automatically by every child process" in the table above.
As a mounted file instead (docker run -v ./db_password:/run/secrets/db_password:ro ...): the identical docker inspect --format='{{json .Config.Env}}' on this container comes back with no trace of the secret at all, and docker inspect's Mounts entry shows only the path, /run/secrets/db_password, never the file's content. Inside the container, ls -l /run/secrets/db_password shows whatever permission the source file had on the host, -rw-r--r-- for a file created with a plain shell redirect under a default umask; a bind mount does not tighten this on its own, so getting a genuinely restrictive -rw------- needs an explicit chmod 600 on the host file before mounting it, or a secrets primitive that manages file modes itself. Only an explicit cat of that exact path reveals the value regardless of the exact mode bits; a spawned child shell's own env | grep db_password comes back empty, confirming the file is not inherited the way an environment variable is.
An external secrets provider fetched at startup does not appear in docker inspect output or on any container filesystem path at all; the value exists only in the application's own process memory after it calls out over the network at startup, which is exactly why it closes off the two leak paths the other options cannot, at the cost of a real network dependency the moment the container starts.
Trade-offs and pitfalls
An external provider fetched at startup adds a genuine availability coupling: if the secrets service is unreachable when the container tries to start, the container fails to start too, which needs its own retry and alerting story, exactly the kind of failure mode that stays invisible until the one time it matters. A mounted file is only as good as the orchestrator's own storage of it before mounting; if the orchestrator's own secret store is itself an unencrypted value at rest, mounting it into the container is a real improvement over an environment variable, but not a complete solution on its own.
A container is showing unhealthy in production according to its HEALTHCHECK, and it keeps restarting before it ever receives real traffic. Walk through a step-by-step troubleshooting process: what you'd check in the Dockerfile and application startup path, and how you'd replicate the health probe locally to isolate the cause.
Sample Answer
Direct answer
A container that is marked unhealthy and keeps getting restarted before it ever serves traffic is, on plain Docker or Compose, almost always the application process itself exiting (crashing), not the health status "causing" a restart. Docker's health status is informational: a restart policy reacts to the container's process actually exiting, not to HEALTHCHECK reporting unhealthy by itself. So the fastest path is to confirm what actually killed the process first, then work outward through the Dockerfile and the startup path, and finally reproduce the exact health probe locally to separate "the app never came up" from "the app came up but fails this specific check."
Structured elaboration
1. Confirm what is actually happening, before touching any code
docker inspect --format='{{json .State}}' <container>forExitCode,OOMKilled,Status, and.State.Health.Log(the last several probe attempts, each with its own exit code and output).docker logs --tail=200 --timestamps <container>to see stdout and stderr right up to the crash.- If
docker ps -akeeps showing new container IDs (or the same container's restart count keeps climbing under a--restartpolicy), this is a genuine crash loop: the process is exiting. If instead one container ID just sits atUp ... (unhealthy)and never gets recreated, the process is alive and only the probe itself is failing, which is a narrower problem than "restarting."
2. Dockerfile-side checks
- Read the
HEALTHCHECKinstruction exactly as built:docker inspect --format='{{json .Config.Healthcheck}}' <image>. Confirm the tool it invokes (curl,wget, a custom binary) is actually present in the final image. A hardened or distroless (a minimal base image with no shell, package manager, or other OS tooling beyond what the application itself needs) final stage that droppedcurlmakes the probe itself fail with a shell or exec error, which is indistinguishable from "the app is broken" until you look closely at.State.Health.Log. - Confirm the checked port and path match what the app actually binds, and that the app listens on
0.0.0.0, not only127.0.0.1. - Check whether
CMD/ENTRYPOINTuse shell form (CMD myapp, which runs under/bin/sh -c, making the shell PID 1, the first and special process in the container's own process namespace, responsible for reaping child processes and receiving signals) or exec form (CMD ["myapp"], which makes the application itself PID 1). If the app is not written to handleSIGTERMand reap children as PID 1, shutdowns get slow and messy, which is worth ruling out even if it is not this incident's root cause.
3. Application startup-path checks
- Does startup do a single, no-retry dependency check (a database ping, a config-service fetch) that calls
panic(),os.Exit(), orSystem.exit()on the very first failure, instead of retrying with backoff? This is the most common real cause: a dependency is briefly not ready, the app gives up immediately, the process exits, the restart policy relaunches it into the same race, and it loops forever. - Are all required environment variables and secrets actually present in this environment? A value that only exists in a local
.envfile is a common gap between a workstation and production. - Is there a legitimately slow one-time step (schema migration, cache warm-up, model load) that takes longer than the health check's timing allows before the app can answer the probe at all?
4. Replicate the health probe locally
- Run the same image in the foreground, without
-d, so stdout is visible directly:docker run --rm -p 8080:8080 myimage. - Extract the literal
HEALTHCHECK CMDand run it by hand against a live container:docker exec <container> <the exact command>, and read its real exit code and output instead of trusting the summarizedunhealthylabel. - If the container dies before you can attach, override the entrypoint to keep it alive for inspection:
docker run --rm -it --entrypoint sh myimage, then execute the startup steps one at a time to isolate the exact failing line.
Worked example
A team's Dockerfile ends with HEALTHCHECK CMD curl -f http://localhost:8080/health || exit 1, and the container flaps every few seconds. docker inspect shows ExitCode: 1 and a new container ID on each cycle, a genuine crash loop. docker logs shows Starting application... followed immediately by panic: dial tcp db:5432: connect: connection refused. The startup code opens a database connection and calls a single ping, panicking on any error instead of retrying. Running docker run --rm myimage locally against a database that is not yet reachable reproduces the exact panic in under a second, confirming this has nothing to do with the health check or the Dockerfile. The fix is to make the startup path retry the database connection with backoff and only begin listening (so HEALTHCHECK can start passing) once the dependency is actually reachable, and separately to widen HEALTHCHECK's start_period so a slow but legitimate first connection is not flagged before the app has had a fair chance.
Trade-offs & pitfalls
- Do not "fix" this by only loosening the health check (longer timeout, fewer retries, more lenient
start_period). That hides a real startup-ordering bug and defers discovering it to a worse moment, such as a live outage. - A probe that fails only because its own tool was stripped out of a hardened final image gets misread as "the app is broken," wasting time on the wrong layer. Check the probe command's exit code and output specifically before assuming the application is at fault.
depends_on: condition: service_healthyin Compose reduces this exact class of bug at startup by not starting a dependent service until the thing it needs is already healthy, but it does not replace retry logic inside the app itself: a dependency can still disappear later, after the container is already running and serving traffic.
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.
Unlock Full Question Bank
Get access to all Containerization and Docker Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.