Docker Scenario Based Interview Questions: Diagnose First, Then Defend the Fix

Branko Petric
Branko Petric

- 16 min read

The short answer

Docker scenario questions test whether you diagnose before you change anything. Read docker history before shrinking an image, fix layer order before disabling the cache, check OOMKilled before raising memory, and treat a mounted Docker socket or a secret in a layer as a security problem. Name the trade-off out loud and hold it under pushback.

Junior Docker questions ask for definitions: what is an image, what is a container, what is the difference between CMD and ENTRYPOINT. Experienced candidates usually get a different kind of question. The interviewer describes a slow pipeline, a container stuck in a restart loop or a risky CI shortcut, and asks what you would do. Then they argue with you.

Below are six common Docker scenarios, each with the prompt, the commands you would run, the pushback to expect, and a weak answer next to a strong one. For the general shape of a DevOps loop, see how to pass a DevOps interview.

What these questions are really testing

Three things, in every scenario below:

  1. Do you look before you change anything? docker history, docker inspect and docker logs answer most of these questions in under a minute. A candidate who reaches for a flag before running them is guessing.
  2. Do you understand layers? An image is a stack of read-only layers, and each instruction's cache depends on everything above it. The image size, build speed and secret leak scenarios are all layer questions in disguise.
  3. Do you know where the isolation boundary is? A container is a process on the host with namespaces and cgroups around it. Knowing what weakens that boundary (the Docker socket, --privileged) and what lives inside it (localhost, memory limits) is what separates a strong answer.

A weak answer names a flag. A strong one says what the command will show and what you will decide from it.

Scenario 1: "The image is 1.6GB, so let's add more CI runners"

The prompt: "Your Node app's Docker image is 1.6GB and every code change rebuilds dependencies from scratch, so CI takes 8 minutes. A teammate says just add more CI runners. How do you fix the image, and why?"

This is the docker image size optimization interview question with a cost argument attached. Start by showing where the size and time actually go:

docker image ls myapp
docker history --format 'table {{.Size}}\t{{.CreatedBy}}' myapp:latest
REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
myapp        latest    7d1e4f2a9b3c   12 minutes ago   1.6GB

SIZE      CREATED BY
0B        CMD ["node" "dist/server.js"]
14.2MB    RUN /bin/sh -c npm run build # buildkit
412MB     RUN /bin/sh -c npm install # buildkit
186MB     COPY . . # buildkit
0B        WORKDIR /app
...       (node:22 base layers, roughly 1GB in total)

Three problems are visible. The base is the full node:22 image with compilers and a full Debian userland. COPY . . comes before npm install, so any source change invalidates the install layer, which is where the 8 minutes goes. And the 186MB COPY layer says the build context includes things it should not, most likely a local node_modules and .git.

The fix is a Dockerfile change, not a hardware change:

# syntax=docker/dockerfile:1
FROM node:22-bookworm-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev

FROM node:22-bookworm-slim
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/package.json ./
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]
# .dockerignore
node_modules
.git
coverage
*.log
.env

Copying only the manifest and lockfile before npm ci means a code-only change reuses the cached dependency layer. The multi-stage build keeps dev dependencies and build tooling out of the shipped image. The .dockerignore shrinks the context sent to the builder and keeps a local .env out of the image.

The pushback: "I will just rm -rf the build tools in the last RUN step. Same result, no refactor."

Weak answer Strong answer
"Sure, that removes them from the image." "Layers are additive. Deleting files in a later layer hides them, but the earlier layer still ships with every pull. A multi-stage build is how they never get into the final image."
"More runners are cheaper than my time." "More runners rebuild a badly cached image in parallel. The 1.6GB still gets pushed and pulled on every deploy and rollback. The Dockerfile fix is an hour of work."

The rest of the argument, how to keep the cache warm in CI, whether alpine is worth the musl trade-off for your native modules, and what size actually costs you at deploy time, is what the challenge scores you on.

Practice this one: /challenges/docker-image-bloat

Scenario 2: "Builds are slow and stale, so add --no-cache everywhere"

The prompt: "Docker builds in CI are taking 11 minutes and sometimes ship stale dependencies. A teammate says just add --no-cache to every build so we always get a clean image and stop debugging cache weirdness. What do you do, and why?"

The two symptoms look contradictory: the cache is missing too often (slow) and hitting when it should not (stale). Both usually come from the Dockerfile, not from caching itself.

Slow: COPY . . before the install step busts the dependency layer on every commit, as in Scenario 1. Stale: the cache key for a RUN step is the instruction text plus its parent layers, not what the command would download today. These lines produce a correct-looking cache hit with old contents:

FROM node:lts
RUN apt-get update
RUN apt-get install -y curl
RUN npm install

node:lts is whatever your builder pulled last time. RUN apt-get update on its own line is cached forever, so a later apt-get install change installs against an old package index. npm install without a committed lockfile resolves version ranges, and the cached layer keeps whatever it resolved weeks ago.

Make every input explicit, so a cache hit is a correct hit:

# syntax=docker/dockerfile:1
FROM node:22-bookworm-slim@sha256:<digest>
RUN apt-get update && apt-get install -y --no-install-recommends curl \
    && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .

Pinning the base by digest means a base image update shows up as a reviewed change (a bot like Renovate or Dependabot can open those PRs). npm ci installs exactly what the lockfile says. The cache mount keeps npm's download cache between builds without putting it in a layer.

Then give CI a cache to reuse, because runners start cold:

docker buildx create --use --driver docker-container
docker buildx build \
  --cache-from type=registry,ref=registry.example.com/myapp:buildcache \
  --cache-to type=registry,ref=registry.example.com/myapp:buildcache,mode=max \
  -t registry.example.com/myapp:${GIT_SHA} --push .

The registry cache backend needs a builder with the docker-container driver; on the default docker driver, --cache-to type=inline is the simpler option. If you deliberately want the newest base for a floating tag, --pull re-checks it on each build, which is far cheaper than throwing away every layer with --no-cache.

The pushback: "We literally shipped an old dependency to production because of the cache. That proves the cache is dangerous."

Weak answer Strong answer
"Fair, a clean build every time is safer." "It proves our inputs were not pinned. With a lockfile and a pinned base, the same inputs always produce the same layer, so a cache hit cannot be stale."
"Let's add --no-cache now and fix it next sprint." "That makes every build pay the full 11 minutes and hides the ordering bug. Moving two lines in the Dockerfile is a smaller change than the flag."

Practice this one: /challenges/docker-cache-bust-rebuild

Scenario 3: "Mount the Docker socket and run the job --privileged"

The prompt: "A CI job inside a container needs to build images, and a teammate says just bind-mount /var/run/docker.sock and run the job with --privileged so it can do whatever it needs. What do you do, and why?"

This is a security question, and the answer starts with what the socket actually is:

ls -l /var/run/docker.sock
srw-rw---- 1 root docker 0 Nov 25 09:12 /var/run/docker.sock

It is the API of a daemon that runs as root on the host. Anything that can talk to it can start a new container that mounts the host filesystem:

docker run --rm -it -v /:/host alpine chroot /host sh

That is a root shell on the CI host, with access to every other job's checkout, cached credentials and runner tokens. --privileged is a separate problem: it gives the container all capabilities and access to host devices, and turns off the default seccomp and AppArmor profiles, so escaping the container stops being hard.

If that CI runner builds pull requests from outside contributors, both together mean any PR can own the host.

What to do instead depends on what the job really needs:

  • It only needs to build and push images. Use a builder that does not need the host daemon: BuildKit in rootless mode (moby/buildkit:rootless with buildctl-daemonless.sh), Buildah, or kaniko. Note the original Google kaniko repository was archived in 2025, so check which fork you would depend on. Rootless BuildKit usually still needs seccomp and AppArmor relaxed for its container, which is a much narrower grant than --privileged.
  • It really needs a Docker daemon (for example, integration tests that start containers). Give the job its own daemon on an ephemeral VM per job, not a shared host. Be accurate here: the standard docker:dind image itself requires --privileged, so dind is only acceptable when the machine it runs on is single-use and holds nothing else worth stealing.
  • Separate trust levels. Untrusted PR builds run on different runners from jobs that hold deploy credentials.

The pushback: "The runner is torn down after every job. Even if it is compromised, it only lives for a few minutes."

Weak answer Strong answer
"True, ephemeral runners make it low risk." "The container is ephemeral, the host is not. The socket gives root on the host that runs the next job, and a few minutes is enough to read secrets and runner tokens."
"Docker-in-Docker with the socket is what everyone does." "Common is not the same as safe. Mounting the socket is not even Docker-in-Docker, it is sharing the host daemon. If we need a daemon, it should be per job on a throwaway VM."

Practice this one: /challenges/docker-privileged-socket-mount

Scenario 4: "The container keeps restarting with exit code 137"

The prompt: "An API container on a single Docker host keeps restarting. docker ps shows exit code 137. A teammate wants to bump the memory limit to 2GB and move on. Walk me through it."

This is the most common docker troubleshooting interview question, and the trap is assuming 137 means out of memory. Exit code 137 is 128 + 9: the process was killed with SIGKILL. The kernel OOM killer sends SIGKILL, but so does docker stop when the process ignores SIGTERM for the grace period (10 seconds by default). Find out which:

docker ps -a --filter name=api --format 'table {{.Names}}\t{{.Status}}'
docker inspect --format '{{.State.OOMKilled}} {{.State.ExitCode}} {{.RestartCount}}' api
NAMES     STATUS
api       Restarting (137) 8 seconds ago

true 137 14

OOMKilled is true, so the container hit its cgroup memory limit. Check the limit and watch usage climb toward it:

docker inspect --format '{{.HostConfig.Memory}}' api
docker stats --no-stream api
536870912

CONTAINER ID   NAME   CPU %    MEM USAGE / LIMIT   MEM %    NET I/O         BLOCK I/O   PIDS
3f2a9c1b7d4e   api    87.12%   498.3MiB / 512MiB   97.32%   1.2MB / 845kB   0B / 0B     23

For the application's side of the story, read the logs. There is no docker logs --previous; that flag is kubectl. A restarted container is the same container, so its log history is still there:

docker logs --tail 50 api
docker events --since 1h --filter container=api

docker events shows an oom event followed by die with exitCode=137 for each restart, which gives you the timeline.

If OOMKilled is false and the code is still 137, look elsewhere. Something sent SIGKILL: often a docker stop or redeploy where the app never exited on SIGTERM. A process running as PID 1 gets no default signal handling, so without its own SIGTERM handler it ignores the signal, and a shell or wrapper in front of it may not forward it. Exec-form CMD ["node", "server.js"] plus a signal handler, or docker run --init, fixes that. A kill from the host-wide OOM killer, or one that hit a child process instead of PID 1, may not set the flag, so check journalctl -k for Out of memory: Killed process.

Once you know it is a real OOM, the question is why. A memory leak grows steadily after each restart. A runtime sized for the host rather than the container does too: set the heap below the limit (--max-old-space-size for Node, -XX:MaxRAMPercentage for the JVM). Then raise the limit if the workload genuinely needs it, based on the usage you measured.

The pushback: "It is a memory problem. Just set the limit to 2GB, the restart policy keeps it up anyway."

Weak answer Strong answer
"Yes, 2GB should be plenty." "First I check OOMKilled. If it is false, more memory changes nothing. If it is true, I want to know whether usage plateaus or keeps growing, because a leak eats 2GB too, just later."
"The restart policy handles it." "The restart policy turns a crash into a quiet loop. Every restart drops in-flight requests. It buys time, it is not the fix."

The same symptoms in a cluster show up as OOMKilled and CrashLoopBackOff, covered in the Kubernetes troubleshooting interview questions. The Docker debugging guide covers inspect, logs, events and exec in more depth.

Scenario 5: "A token is baked into the image, but we deleted it"

The prompt: "A Dockerfile copies .npmrc with a private registry token to install packages, then removes it in the next step. The image is pushed to your registry and used in production. A reviewer flags it. Is it a problem?"

Yes, and you can prove it in one command:

COPY .npmrc /root/.npmrc
RUN npm ci
RUN rm /root/.npmrc
docker history --format 'table {{.Size}}\t{{.CreatedBy}}' myapp:1.4
SIZE      CREATED BY
0B        RUN /bin/sh -c rm /root/.npmrc # buildkit
388MB     RUN /bin/sh -c npm ci # buildkit
95B       COPY .npmrc /root/.npmrc # buildkit

The 95-byte COPY layer still holds the file. The rm adds a new layer that hides it in the running filesystem, but anyone who can pull the image can docker save it and read the layer tarballs. Passing the token as a build argument is no better: Docker's own docs warn that build argument values are visible with docker history on any RUN step that uses them.

So answer in order:

  1. Rotate the token. Anyone with pull access to that image, and any cache or mirror it went through, has it. Removing the image does not un-leak a credential. This is the same rotate-first logic as the leaked credentials in git challenge.
  2. Rebuild without it, using a BuildKit secret mount, which is only present while that one RUN step executes and never written to a layer:
# syntax=docker/dockerfile:1
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
docker build --secret id=npmrc,src=$HOME/.npmrc -t myapp:1.5 .
  1. Clean up and prevent. Delete the old tags from the registry, add .npmrc and .env to .dockerignore, and add a secret scan to CI, for example trivy image --scanners secret myapp:1.5.

The pushback: "The registry is private, and the file is deleted in the final image. Nobody outside the company can see it."

Weak answer Strong answer
"Private registry, so the risk is low." "Everyone and every system with pull access has the token, for as long as the old tag exists. I rotate it and rebuild with a secret mount. That costs less than auditing who pulled the image."
"Squash the image so the layer disappears." "Squashing the new build does not change the images already pushed and pulled. The token is still compromised, so rotation comes first either way."

The Docker security guide covers secret mounts, non-root users and image scanning.

Scenario 6: "The two containers cannot reach each other"

The prompt: "You start an API container and a Redis container on the same host with docker run. The API logs connect ECONNREFUSED 127.0.0.1:6379. A teammate suggests --network host. What is going on?"

This is the classic docker networking interview question, and it hides two separate mistakes. Reproduce the first one:

docker run -d --name cache redis:7
docker run --rm alpine ping -c1 cache
ping: bad address 'cache'

On the default bridge network, containers get IPs but there is no DNS for container names. User-defined networks have an embedded DNS server that resolves container names:

docker network create appnet
docker run -d --name cache --network appnet redis:7
docker run --rm --network appnet redis:7 redis-cli -h cache ping
PONG

The second mistake is in the error message itself: 127.0.0.1 inside a container is that container, not the host and not Redis. The API must connect to cache:6379. Publishing Redis with -p 6379:6379 is not needed for container-to-container traffic on the same network; it only exposes Redis on the host. Docker Compose does this for you by putting every service on a project network where service names resolve.

The pushback: "Just run both with --network host and use localhost. Fewer moving parts."

Weak answer Strong answer
"Sure, host networking works." "It removes network isolation, puts every container port on the host's interfaces and causes port clashes. On Docker Desktop it is a separate opt-in and still does not behave exactly like Linux. A user-defined network fixes the real problem, which is name resolution."

The Docker networking guide covers bridge, host and overlay networks and published ports.

A pattern you can reuse in any Docker scenario

  1. Do not change anything yet. Say it first, especially before adding --no-cache, --privileged or a bigger limit.
  2. Inspect the image. docker history shows which layer holds the size, the cache bust or the secret.
  3. Inspect the container. docker inspect for State.OOMKilled, ExitCode, RestartCount and HostConfig, then docker logs and docker events for the timeline.
  4. Fix the cause in the Dockerfile. Layer order, multi-stage builds, pinned inputs and secret mounts are cheaper than hardware.
  5. Check the boundary. Ask what the socket, --privileged, host networking or a baked-in credential gives away, and to whom.
  6. Name the trade-off. Alpine vs glibc, a registry cache vs build time, dind on a throwaway VM vs rootless builds.

The free optimization guide, Dockerfile guide and Docker in CI/CD guide cover the build side in more depth.

A short practice plan

  • Day 1: Take any Node or Python Dockerfile you have, run docker history on it, and rewrite it as a multi-stage build. Compare the size and the rebuild time after a one-line code change.
  • Day 2: Start a container with --memory 64m and a process that allocates past it, then read OOMKilled, docker events and the exit code yourself. Then run docker run -d --name t alpine sleep 300 and time docker stop t: sleep as PID 1 ignores SIGTERM, so it takes the full 10 seconds and exits with 137.
  • Day 3: Argue the three challenges above out loud, including the pushback. The full set of Docker prompts is on the Docker interview questions hub.

Practicing under pushback

Reading these answers is the easy part. In the interview, someone pushes back with a reasonable-sounding argument and watches whether you fold. A general chatbot makes up an answer on the spot. DevOps Ledger grades you against an answer key written before you started. Each challenge above lets you defend your call against that kind of pushback and see which arguments held up.

FAQ

What are Docker scenario based interview questions?

They describe a situation instead of asking for a definition: a bloated image, a slow or stale build, a risky CI shortcut, a container stuck in a restart loop, a leaked secret or two containers that cannot talk. You are scored on what you check first, what you decide and how you defend it.

What Docker questions are asked for experienced engineers?

Expect layer and build cache questions, multi-stage builds, what the Docker socket and --privileged grant, debugging exit codes with docker inspect and docker logs, secrets in images, and container networking. Interviewers also push back on your answer to see whether you hold a correct position.

What does exit code 137 mean in Docker?

The process was killed with SIGKILL (128 + 9). Check docker inspect --format '{{.State.OOMKilled}}': true means the container hit its memory limit. false usually means something else sent SIGKILL, such as docker stop after the app ignored SIGTERM for the grace period.

How do you reduce Docker image size?

Use a slim base image, a multi-stage build that copies only the runtime output into the final stage, and a .dockerignore. Deleting files in a later RUN step does not help, because the earlier layer still contains them. docker history shows which layer to fix.

Why can't my Docker containers reach each other by name?

The default bridge network has no DNS for container names. Put both containers on a user-defined network with docker network create and connect by container name. Also remember that localhost inside a container refers to that container, not to the host or another container.

Practice these scenarios

Free guides to read next

Practice defending your decisions

DevOps Ledger is a scenario-based DevOps and SRE interview practice platform: you pick a real production incident, defend your decision in a chat against a senior-engineer AI that pushes back, and get scored against an answer key written before you started.

One payment. 12 months of access. No subscription, nothing renews.

Get full access - $19