Skip to content

Interview PrepDocker

Docker Troubleshooting and Platform Design ​

149. A container exits immediately after starting; which commands and checks would you run first? ​

The short answer

First docker ps -a to see the exit code, then docker logs to see what the app printed, then docker inspect for the exact command, the error field and whether it was killed for memory. The exit code usually points at the cause. If the logs are not enough, start the same image with a shell instead of its normal command and run the command by hand.

Step 1: what exit code?

bash
docker ps -a --filter name=api --format 'table {{.Names}}\t{{.Status}}'
NAMES   STATUS
api     Exited (127) 3 seconds ago

The exit code is the first clue:

CodeUsual meaning
0The command finished normally. Nothing kept it running
1The app reported an error
126The command was found but could not be run, for example not executable
127The command was not found
137Killed by SIGKILL, often out of memory (question 151)
139Crashed with a memory access error, a segmentation fault
143Stopped by SIGTERM

Step 2: what did it say?

bash
docker logs api

Step 3: how was it started, and what did Docker record?

bash
docker inspect -f 'cmd={{json .Config.Cmd}} entry={{json .Config.Entrypoint}} err={{.State.Error}} oom={{.State.OOMKilled}}' api

State.Error holds Docker's own error when the start itself failed, such as exec: "node": executable file not found in $PATH.

Step 4: get inside and try it by hand.

bash
docker run -it --rm --entrypoint sh shop/api:1.4

Now you are in the same image with a shell. Run the real command and watch what happens.

The most common causes of an immediate exit:

  1. Exit code 0: the program is not long-running. It did its job and finished. A classic example is a server that runs itself in the background. nginx does this unless told daemon off;. The process that Docker started exits after launching the background one, PID 1 is gone, and the container stops.
  2. A shell with nothing to do. docker run ubuntu bash exits at once, because bash has no input. Add -it to keep it open.
  3. Missing configuration. A required environment variable or file is missing, and the app exits with code 1. The logs usually say so.
  4. A wrong command. Code 127 or 126, a typo in CMD, or a script with Windows line endings (question 84).

150. A container is in a restart loop; how would you distinguish an application error from a configuration or infrastructure issue? ​

The short answer

Read the evidence from each crash: the exit code, the last log lines, and OOMKilled. An application error leaves a stack trace or an error message and fails the same way everywhere. A configuration error mentions a missing or wrong setting, and the same image works elsewhere with different settings. An infrastructure error shows up as being killed for memory, being unable to reach something, a full disk or a permission problem, and often depends on the host. Pausing the restarts makes it easier to look.

Step 1: stop the loop so you can look.

bash
docker update --restart=no api      # (1)
docker inspect -f 'restarts={{.RestartCount}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}}' api   # (2)
docker logs --tail 50 api           # (3)
  1. Turns off the restart policy without recreating the container, so the next crash stays crashed.
  2. How many times it has restarted, and how it died last time.
  3. The last lines it printed. These belong to the most recent run.

Step 2: sort the evidence.

EvidencePoints to
Stack trace, TypeError, assertion failedApplication bug
"missing env var", "cannot read config", "invalid credentials"Configuration
Exit 137 with OOMKilled: trueMemory limit or leak
"ECONNREFUSED", "no such host", timeoutsA dependency or the network
"permission denied" on a mounted pathVolume ownership (question 94)
"no space left on device"Host disk full
"address already in use"Port clash (question 118)

Step 3: confirm with a comparison. Run the same image with known-good configuration, for example the settings from staging. If it works, the image is fine and the problem is configuration or environment. If it fails the same way, it is the application. If it works on another host but not this one, it is the host: its disk, its network, its kernel or its other containers.

One detail that misleads people: the restart backoff (question 106). After many crashes, Docker waits longer between restarts, so the container can look "stuck" when it is simply waiting before its next attempt.

151. A container reports exit code 137; what are the likely explanations, and how would you confirm the cause? ​

The short answer

137 means the process was killed with SIGKILL: 128 plus signal number 9. There are a few common causes. The kernel may have killed it for going over its memory limit. A docker stop may have run out of grace period, because the app ignored SIGTERM. Someone or something may have run docker kill. The host itself may have run out of memory. Or, in Kubernetes, a liveness probe failed. Confirm with the OOMKilled flag, the kernel log, and Docker's event log.

The candidates:

  1. Over its memory limit. The kernel's OOM killer ends it inside its cgroup (question 97).
  2. A stop that timed out. docker stop sent SIGTERM, the app did not exit within 10 seconds, so Docker sent SIGKILL (question 104).
  3. A deliberate kill. docker kill, a script, or a person.
  4. The whole host ran out of memory. The kernel's system-wide OOM killer picked this process, even though it was under its own limit.
  5. In Kubernetes: the kubelet killed it because a liveness probe kept failing, or because the node was short of memory and evicted it.

How to tell them apart:

bash
docker inspect -f 'oom={{.State.OOMKilled}} finished={{.State.FinishedAt}}' api   # (1)
docker events --since 1h --filter container=api                                     # (2)
sudo journalctl -k --since "1 hour ago" | grep -i -E 'oom|killed process'           # (3)
  1. oom=true means Docker saw a cgroup memory kill. That is cause 1 confirmed.
  2. Docker's event log for the container. A kill event shortly after a stop event points to cause 2. An oom event confirms cause 1. A kill with no stop points to cause 3.
  3. The kernel's own log. A line like Memory cgroup out of memory: Killed process 4211 (node) confirms a cgroup limit. A line saying Out of memory: Killed process without "Memory cgroup" means the whole host ran out, which is cause 4.

Also check memory over time, with docker stats or your monitoring, up to the moment of the kill. A steady climb is a different problem from a sudden spike. Question 156 shows how to tell a leak from a limit that is too low.

Only after you know the cause, change something: a higher limit for a real, stable need, a code fix for a leak, a shutdown handler for a stop that times out (question 105).

152. A container exits with code 1 but its logs are empty; what would you inspect next? ​

The short answer

Empty logs usually mean the app wrote its output somewhere other than standard output, held it in a buffer that was never flushed, or failed before it could print anything. Check docker inspect for Docker's own error and the exact command. Run the image by hand with a shell and execute the command yourself. If the entrypoint is a script, run it with sh -x to see which line fails.

Why the logs can be empty:

  1. The app logs to a file, not to standard output, so docker logs has nothing (question 42).
  2. Output was buffered. When output does not go to a terminal, many runtimes collect it in a buffer and write it out in chunks. If the process dies first, the buffer is lost. Python is the classic case. PYTHONUNBUFFERED=1 fixes it.
  3. A script failed silently. An entrypoint script with set -e stops at the first failing command, and if that command printed nothing, neither does the script.
  4. The logging driver does not support docker logs (question 472).

What to inspect next:

bash
docker inspect -f 'err={{.State.Error}} cmd={{json .Config.Cmd}} entry={{json .Config.Entrypoint}}' api   # (1)
docker run --rm -it --entrypoint sh shop/api:1.4                                                         # (2)
# inside:
sh -x /usr/local/bin/docker-entrypoint.sh node dist/server.js                                            # (3)
echo $?                                                                                                  # (4)
  1. Docker's own error message, and exactly what was run.
  2. The same image, with a shell instead.
  3. sh -x runs the script while printing every line before executing it, so you see which command fails.
  4. Prints the last command's exit code.

Other places to look: the app may have written its log into files. Copy them out with docker cp api:/app/logs ./logs, which works even on a stopped container. Also try the app's own debug setting, such as LOG_LEVEL=debug or NODE_DEBUG, which often reveals a failure during start-up.

153. A container works interactively but fails when started by the normal entrypoint; how would you investigate it? ​

The short answer

Something differs between your interactive shell and the real start. Compare them one at a time. Start with the exact command and arguments. Then the environment, because interactive shells load profile files that set extra variables. Then whether a terminal is attached, the user, and the working directory. Last, check whether shell features such as variable expansion were available. Reproduce the real start exactly, without -it, using docker inspect to get the real command.

What an interactive shell gives you that the normal start does not:

  1. Profile files. An interactive bash reads files like /etc/profile and ~/.bashrc, which may set PATH or other variables. The normal start runs the command directly, without them. So a tool "found" interactively may be "not found" for real.
  2. A shell. Typing node server.js --port $PORT in a shell expands $PORT. Exec-form CMD does not (question 49).
  3. A terminal. With -t, programs behave differently: output is not buffered, colours are on, and some programs wait for keyboard input.
  4. Standard input. With -i, input stays open. Without it, a program that reads from standard input gets "end of file" at once and may exit.
  5. The user. docker exec and an overridden entrypoint may run as a different user than the image's USER.
  6. The working folder. You may have changed into a folder before running the command.

How to reproduce the real start exactly:

bash
docker inspect -f '{{json .Config.Entrypoint}} {{json .Config.Cmd}} {{.Config.User}} {{.Config.WorkingDir}}' shop/api:1.4   # (1)
docker run --rm shop/api:1.4                                    # (2)
docker run --rm --entrypoint /usr/local/bin/docker-entrypoint.sh shop/api:1.4 node dist/server.js   # (3)
  1. The real entrypoint, command, user and working folder from the image.
  2. The normal start, with no -it: exactly what production does.
  3. The entrypoint and command written out by hand, so you can change one part at a time and see which change makes it work.

Two script problems only show up in the normal start. The entrypoint file may not be executable, which gives "permission denied". Or it may have Windows line endings, which gives "no such file or directory" for a file that clearly exists. The second one fools everyone once.

154. A container receives no traffic even though the process is running; what would you check at the process, port, network, and application layers? ​

The short answer

Work from the inside out and find the first layer where a request stops getting through. Process: is it listening, on which port, and on 0.0.0.0 rather than 127.0.0.1? Port: is that port published, to the right host port? Network: is the caller on the same Docker network, and is a firewall in the way? Application: is the proxy configured with the right address, path, host name and protocol? Test with a request at each layer.

① insidecurl localhost:8080tests the processand its port② next doorcurl api:8080tests the Dockernetwork and name③ hostcurl localhost:80tests publishingand port mapping④ outsidecurl https://shop...tests firewalls,DNS and the proxyThe first test that fails is the broken layer.Everything before it works, so you never debug the wrong place.
Find the first failing layer. Each step adds one more layer between the caller and the app. When a step fails, the problem is in the layer that step added.

Layer 1: the process.

bash
docker exec api sh -c 'ss -ltnp || netstat -ltnp'
  • Is anything listening at all? An app can be running but stuck before it opens its port.
  • Which port? An app on port 3000 behind a mapping to 8080 receives nothing.
  • Which address? 127.0.0.1:8080 means only the container itself can connect (question 119). It must be 0.0.0.0:8080.

Layer 2: the port.

bash
docker port api

Is the container port published, and to which host port and address? Question 114 shows the options.

Layer 3: the network.

  • Is the caller, such as the reverse proxy, on a network shared with api? docker network inspect shop lists the members.
  • Does the name resolve from the caller? docker exec proxy nslookup api.
  • From outside: does the host's firewall, or a cloud security group, allow the port (question 115)?

Layer 4: the application.

  • Does the proxy point at the right name and port, such as api:8080, not localhost:8080?
  • Right protocol? Sending plain HTTP to an HTTPS port, or the reverse, fails in confusing ways.
  • Right path and host name? A proxy may forward /api/orders as /orders, or send a host name the app does not serve.
  • Is the app rejecting requests, for example because it is not ready yet? Its own logs will show requests arriving and being refused.

155. A container is unexpectedly using a large amount of memory; how would you investigate it? ​

The short answer

First find out what kind of memory it is. Check docker stats and the cgroup's own breakdown, which separates the app's own memory from cached file data the kernel can free. Then look inside: which process uses it, and how much is the language runtime's heap. Use the runtime's own tools, such as a heap snapshot, to see which objects fill the heap. Compare with traffic and with the previous version to see whether it is normal growth or something new.

Step 1: how much, and against what limit?

bash
docker stats --no-stream api
NAME   CPU %   MEM USAGE / LIMIT   MEM %
api    4.2%    1.71GiB / 2GiB      85.5%

Step 2: what kind of memory? The cgroup's memory.stat file splits it up:

bash
docker exec api cat /sys/fs/cgroup/memory.stat | grep -E '^(anon|file|shmem) '
anon 1288490188
file 545259520
shmem 0
  • anon is memory the app itself allocated: its heap, its stacks, its buffers. This is the memory that matters for leaks.
  • file is the kernel's cache of files the container read or wrote. The kernel can drop it when memory runs short, so high file alone is rarely a problem.
  • shmem includes tmpfs mounts (question 470).

Step 3: which process, and how much is heap?

bash
docker exec api top -b -n 1     # which process, and its resident memory

Then use the language's own tools:

RuntimeTool
Node.jsHeap snapshot through --inspect, or process.memoryUsage()
Javajcmd <pid> GC.heap_info, a heap dump with jcmd <pid> GC.heap_dump
PythonThe tracemalloc module, or memray
GoThe pprof heap profile

A heap snapshot lists which kinds of object fill the memory, for example 400,000 cached session objects. That usually points straight at the code responsible.

Step 4: put it in context. Does memory rise with traffic and fall after? That is normal. Did it start with a particular release? Compare with the previous version. Does it rise steadily even at night? That looks like a leak. Question 156 shows how to tell for sure.

156. How would you distinguish a memory leak from a memory limit that is simply too low? ​

The short answer

Look at the shape of memory over time. A leak keeps climbing whatever the traffic, never levels off, and eventually hits any limit you give it: raising the limit only delays the crash. A limit that is too low shows a plateau tied to load: memory rises to a level the app genuinely needs, the crash comes at start-up or at peak traffic, and a modestly higher limit makes it stable.

Leaklimitclimbs whatever the load, killed, starts againLimit too lowlimitrises with traffic, killed only at the peak
Two shapes of trouble. A leak is a sawtooth that never levels off. A limit that is too low shows memory following traffic, and crashes only when traffic peaks.

Signs of a leak:

  1. Memory rises steadily, even when traffic is flat or falling, for example overnight.
  2. It never levels off. After a restart, it starts low and climbs again, giving a sawtooth shape.
  3. Kills come at fairly regular intervals: "it dies every 9 hours".
  4. Heap snapshots taken an hour apart show one kind of object growing and never shrinking.

Signs of a limit that is too low:

  1. Memory follows traffic: up at busy times, down at quiet times.
  2. It levels off at a working size, which is just above the limit.
  3. Kills happen at start-up, while the app loads everything it needs, or at peak traffic.
  4. Heap snapshots look the same over time.

The experiment that settles it. Raise the limit by, say, 50%, and watch for a day:

  • If it was too low, memory levels off below the new limit and the kills stop.
  • If it is a leak, it keeps climbing to the new limit and gets killed again, just later.

Do not "fix" a leak by raising the limit. That only stretches the sawtooth. The real fix is in the code: an unbounded cache, a list that only grows, event listeners that are never removed, or connections that are never closed. A safety net while you find it is a scheduled restart, but say clearly that it is a stopgap.

157. How would you diagnose unexpectedly high CPU usage inside a container? ​

The short answer

Confirm it with docker stats and look at it next to traffic: is CPU per request higher, or is there just more traffic? Find which process and which threads are busy. Check whether the container is being throttled by its CPU limit. Then profile the app with its runtime's profiler to see which functions use the time. Common causes are retry storms, garbage collection under memory pressure, inefficient code paths, heavy logging and pathological regular expressions.

Step 1: is it real, and is it the app or the load?

Compare CPU with requests per second. If both doubled, the app is fine and simply busier. If CPU doubled with the same traffic, each request now costs more, which is the real problem.

Step 2: which process, and is it throttled?

bash
docker exec api top -b -n 1 -H                              # (1)
docker exec api cat /sys/fs/cgroup/cpu.stat                  # (2)
nr_periods 18000
nr_throttled 4100
throttled_usec 210000000
  1. -H shows individual threads, so you can see whether one thread is spinning or all of them are busy.
  2. The cgroup's CPU statistics. nr_throttled counts how many 100-millisecond periods the container hit its CPU limit and was paused. Here it was throttled in about 23% of periods. That is a big cause of slow requests (question 392).

Step 3: profile. A profiler samples what the program is doing many times a second, and shows which functions take the most time:

RuntimeProfiler
Node.jsnode --cpu-prof, or the inspector's profiler
Javaasync-profiler, or jcmd <pid> Thread.print for a quick look
Pythonpy-spy top --pid <pid>, which needs no code change
Gopprof CPU profile

Common causes it reveals:

  1. Retry storms. A dependency is failing, and every request retries in a tight loop.
  2. Garbage collection. Memory near its limit makes the runtime spend most of its time collecting garbage (question 155).
  3. A slow code path. A new feature does something expensive per request, such as rebuilding a large object.
  4. Regular expressions. Some patterns take exponentially long on certain inputs. This is called catastrophic backtracking, and one bad request can pin a CPU.
  5. Logging. Writing and formatting huge volumes of log lines.

158. A Docker image is several gigabytes; how would you find the largest layers and safely reduce its size? ​

The short answer

Use docker history to find the largest layers and the instructions that made them, and dive to see which files are inside. The usual culprits are compilers and build tools in the final image, development dependencies, package caches, a copied .git folder or test data, and files deleted in a later layer. Fix them with a multi-stage build, a slimmer base, a .dockerignore and same-layer clean-up. Then prove the smaller image still works before shipping it.

Find:

bash
docker history --format '{{.Size}}\t{{.CreatedBy}}' shop/api:1.4 | sort -h -r | head
dive shop/api:1.4

Question 88 explains both tools. Each large layer usually maps to one of these causes:

What you findFixQuestion
Compiler, build-essential, an SDKMulti-stage build65
Development dependenciesProduction-only install67
/var/lib/apt/lists, ~/.npm, ~/.cache/pipClean up in the same layer, or cache mounts74, 76
.git, node_modules from the host, test data.dockerignore60
A big file deleted in a later layerDelete in the same step73
Files duplicated by RUN chownCOPY --chown468
A full operating system baseA slim or distroless base70

Reduce safely. Smaller is only better if it still works:

  1. Change one thing at a time, and rebuild.
  2. Run the full pipeline checks against the new image, not only a build.
  3. Run the image and exercise its main paths, including HTTPS calls, time zone handling and any feature that loads a system library. These are the things most often broken by an over-eager clean-up (question 72).
  4. Compare the file lists of the old and new images, so you know exactly what was removed:
bash
docker run --rm --entrypoint sh shop/api:1.4 -c 'find / -xdev -type f | sort' > old.txt

For distroless images without a shell, export the filesystems instead with docker export and compare the archives.

159. A build that used to take one minute now takes ten; how would you isolate the cause? ​

The short answer

Find which step got slow, then ask what changed. Build with --progress=plain to see each step's time and whether it was cached. If many steps that used to be cached now run, the cache broke: look at recent Dockerfile, .dockerignore and dependency changes, and at the CI cache setup. If a step that always ran is now slow, look at downloads, the network, the build machine, and new emulation for another processor type.

Step 1: time every step.

bash
docker build --progress=plain -t api . 2>&1 | grep -E '^#[0-9]+ (\[|DONE|CACHED)'

Each step prints CACHED, or DONE with the seconds it took. Compare with a log from a fast build, if your CI keeps one.

Step 2: if cache hits disappeared, the cache chain broke early (question 64):

  1. Recent changes. Look at the Git history of the Dockerfile and .dockerignore. A COPY . . moved up, or a new file in the build context that changes every run, breaks everything after it.
  2. A changing build argument declared early.
  3. The CI cache. Did the cache export or import stop working? A renamed cache tag, an expired token for the cache registry, or a cache that grew past its storage limit and is being evicted all look like "the cache vanished".
  4. A new CI machine type, with no warm local cache.

Step 3: if a step itself got slow:

  1. Downloads. A dependency server or mirror got slow, or traffic now goes through a proxy. Time a download by hand from the build machine.
  2. A bigger build context. Someone added large files. Check the size of the folder being sent.
  3. Emulation. If the build now targets another processor type through QEMU, compile steps can be ten times slower (question 83).
  4. The machine. Fewer CPU cores, slower disks, or a crowded shared builder.
  5. The base image. A bigger new base image means more to pull before the build can start.

Step 4: fix and guard. Once found, add a check so it cannot silently return: track build duration as a metric, and alert when it doubles (question 168).

160. A deployment is failing because a registry pull is slow or returns authorization errors; what would you check? ​

The short answer

For authorization errors: is the image name right, does the repository and tag exist, are the credentials valid and not expired, and does the pulling identity have read permission on that registry? Note that many registries report a missing image as "unauthorized" or "denied". For slow pulls, ask four questions. How big is the image? Is the registry in the same region? Do the nodes already have the base layers? Is something throttling the traffic, such as the registry, a NAT gateway or a proxy?

Authorization errors, such as 401 Unauthorized, 403 Forbidden or denied: requested access to the resource is denied:

  1. Typo or missing image. Check the registry name, repository and tag letter by letter. For security reasons, many registries answer a request for a repository that does not exist the same way as one you may not see, so a typo looks exactly like a permissions problem.
  2. Expired credentials. Registry tokens are often short-lived. An Azure Container Registry token from az acr login, for example, lasts about three hours. A pull secret copied once into a cluster may simply have expired.
  3. Missing permission. The identity pulling the image, such as the cluster's managed identity, needs a read role, such as AcrPull on Azure.
  4. The wrong account or tenant. Credentials for one registry do not work for another, even in the same company.
  5. Network access to a private registry. If the registry is only reachable over a private endpoint, the node's DNS must resolve its name to the private address (question 538).
  6. Rate limits. 429 Too Many Requests or toomanyrequests is a rate limit, not a permissions problem (question 477).

Test from the same place the pull happens:

bash
docker pull myacr.azurecr.io/shop/checkout-api:3f9c2ab                  # (1)
curl -s -o /dev/null -w '%{http_code}\n' https://myacr.azurecr.io/v2/   # (2)
kubectl describe pod checkout-api-7d9f | grep -A5 Events                # (3)
  1. Try the pull by hand, ideally from the same node or network.
  2. Every OCI registry answers /v2/. A 401 here is normal and good: it means the registry is reachable and asks for login. A timeout means a network problem.
  3. In Kubernetes, the pod's events show the exact pull error (question 406).

Slow pulls:

  1. Image size. A 3 GB image takes time on every new node (question 158).
  2. Distance. A registry in another region means slow, and sometimes expensive, transfers (question 135).
  3. Cold nodes. New nodes have no layers cached. Shared base layers help a lot here.
  4. Throttling. The registry's own limits, a NAT gateway's connection limits, or a corporate proxy.

161. How would you investigate a container that cannot resolve DNS or connect to a downstream service? ​

The short answer

Split the problem into its steps and test each one from inside the container: can it resolve the name, can it reach the resolved address, can it open the port, and does the conversation succeed, including TLS? The first step that fails tells you where to look: DNS settings, routing and firewalls, the service's own allow-list, or certificates and proxies.

Test each step, from inside the container or from a debug container sharing its network (question 43):

bash
getent hosts payments.example.com                         # (1)
nc -vz -w 3 203.0.113.10 443                              # (2)
curl -v --max-time 5 https://payments.example.com/health  # (3)
  1. Name resolution, using the same resolver path the app uses. No answer means DNS. Question 117 covers DNS causes.
  2. Reachability of the address and port. A timeout means something drops the traffic: a firewall, a missing route, or a security group. "Connection refused" means the traffic arrived but nothing listens, or the service actively rejected it.
  3. The full request, including TLS. -v shows each stage, so a certificate error or a proxy problem shows up clearly.

Causes by step:

Fails atUsual causes
Name resolutionWrong DNS servers, name only in a private zone, subnet clash with a VPN
ConnectionEgress firewall, downstream allow-list does not include your outgoing IP, no route
TLSExpired or untrusted certificate, missing CA certificates in a minimal image, clock wrong
RequestProxy required, wrong host name sent, the service rejects the client

Two causes worth naming because they are easy to miss:

  1. Your outgoing IP changed. Many partner APIs only accept calls from a list of known addresses. Moving to a new host, cluster or NAT gateway changes your address, and calls start failing with timeouts or 403s.
  2. No CA certificates in the image. A minimal image without CA certificates fails every HTTPS call with "unable to get local issuer certificate" (question 72).

162. What would you check if a container can connect to a service by IP address but not by DNS name? ​

The short answer

Then the network works and the problem is name resolution. Check that the container's DNS server is reachable and answering. Check that the name is spelled right, and exists in the DNS zone the container can see. Check that the container is on the network where that name is defined. Also check whether the name resolves to a different address than the one you tested, for example a public address instead of a private one, or an IPv6 address the container cannot reach.

Work through these, in order:

  1. What does the container's resolver return?
bash
docker exec api getent hosts orders-db                  # (1)
docker exec api nslookup orders-db 127.0.0.11           # (2)
docker exec api cat /etc/resolv.conf /etc/hosts         # (3)
  1. Resolves the name the same way the app's system library does, including /etc/hosts.

  2. Asks Docker's embedded DNS server directly (question 116).

  3. Which DNS servers and search domains are set, and whether /etc/hosts overrides the name.

  4. Is the name defined where this container looks? A container name only resolves for containers on the same user-defined network (question 116). A company name such as orders-db.corp.local only resolves through company DNS servers.

  5. Does the name point somewhere else? Many companies use split-horizon DNS: the same name gives a private address inside the network and a public one outside. If the container uses public DNS servers, it may get the public address, which it cannot reach, while your test used the private one.

  6. IPv6. The name may return both an IPv6 and an IPv4 address. If the app tries IPv6 first and the container has no IPv6 route, it can fail or wait for a timeout.

  7. Old answers cached. Some runtimes keep DNS answers for a long time. Java, for example, can keep them indefinitely under some security settings. If the service moved to a new address, the app keeps using the old one until it restarts.

  8. Search domains. A short name such as orders-db may be expanded with search domains. If the wrong search domain is tried first, you get the wrong answer, or a slow one. Kubernetes makes this more complex (question 375).

163. How do you capture useful diagnostic information without modifying a production container unnecessarily? ​

The short answer

Collect from the outside first: logs, docker inspect, docker stats, docker top and docker events change nothing. For network and process detail, use the host's own tools inside the container's namespaces with nsenter, or start a separate debug container that joins the target's namespaces. Copy files out with docker cp. Use the runtime's own signals or tools to take heap or thread dumps. Avoid installing tools or editing files inside the running container.

Read-only from the host:

bash
docker logs --since 30m api > api.log
docker inspect api > api-inspect.json
docker stats --no-stream api
docker top api
docker events --since 1h --filter container=api

None of these touches the container. Save the output first, because a restart can destroy the evidence.

Look inside without changing it:

bash
pid=$(docker inspect -f '{{.State.Pid}}' api)
sudo nsenter -t "$pid" -n ss -tanp                        # (1)
sudo nsenter -t "$pid" -n tcpdump -i eth0 -c 200 -w api.pcap   # (2)
docker run --rm -it --network container:api --pid container:api nicolaka/netshoot   # (3)
docker cp api:/app/logs ./api-logs                        # (4)
  1. Runs the host's ss in the container's network namespace, to list its connections. No tool is installed in the container.
  2. Captures 200 packets from the container's network interface into a file, with the host's tcpdump.
  3. Starts a separate debug container full of network tools, netshoot, that shares the target's network and process namespaces. When you exit, it is deleted, and the target is untouched.
  4. Copies files out of the container, even a stopped one.

Runtime dumps. Many runtimes can produce diagnostics without stopping:

  • Java: jcmd <pid> Thread.print for a thread dump, and jcmd <pid> GC.heap_dump /tmp/heap.hprof for a heap dump.
  • Node.js: start with --heapsnapshot-signal=SIGUSR2, then docker kill -s USR2 api writes a heap snapshot.

Preserve evidence if you must replace it. docker commit api api-evidence:incident-42 saves the filesystem as it is (question 466), and docker inspect output saves the configuration, before the container is replaced.

164. How do you decide whether to debug inside a running container, inspect it from the host, or reproduce the problem in a new container? ​

The short answer

Choose by risk and by what you need to see. Inspect from the host first, because it is safe and changes nothing. Go inside only when you need the live state that exists nowhere else, such as open connections or memory, and do it without changing anything. Reproduce in a new container when the problem can be triggered again, because there you can change anything, add tools and repeat the experiment as often as you like, with no risk to customers.

Inspect from the hostDebug inside the live containerReproduce in a new container
Risk to productionNoneSomeNone
Sees live statePartlyYesNo
Can change things freelyNoShould notYes
Can repeat the experimentNoNoYes
Tools availableHost's toolsOnly what is in the image, or a debug containerAnything you add

Inspect from the host when: you are just starting, or the problem is happening right now and you want facts before acting. Logs, inspect, stats, events and nsenter cover most cases (question 163).

Go inside when: the evidence only exists in that process right now: a stuck thread, a connection pool that is full, a leaked file handle, a memory state that a restart would wipe. Look, take dumps, and change nothing. Prefer a debug container that joins the namespaces over docker exec with installs.

Reproduce when: the problem can be triggered, for example "it fails with this request" or "it fails with this configuration". Run the same image digest with the same configuration, somewhere safe. There you can turn on debug logging, attach a debugger, add tools and run the failing case again and again.

Production comes first. If customers are affected, restoring service, for example by rolling back, comes before debugging. Capture the evidence quickly, restore service, then investigate on the evidence and on a reproduction (question 456).

165. How would you design a secure and maintainable base image used by dozens of application teams? ​

The short answer

Have a platform team own a small set of "golden" base images, one per language and runtime, built by their own pipeline from pinned upstream images. Make them minimal, non-root, and complete in the things apps quietly need, such as CA certificates and time zones. Rebuild them on a schedule and immediately for critical vulnerabilities. Publish them with version tags, digests, signatures and SBOMs, and let automation open update pull requests in every team's repository.

upstreampinned by digestbase image pipelinebuild: minimal, non-rootscan, then sign, then SBOMweekly, and on critical CVEsshop/base-node:20-2026.10.3team A repo: update PRteam B repo: update PRteam C repo: update PR
One pipeline feeds every team. The platform team builds and proves the base once. Every team receives the update as an ordinary pull request that runs through its own checks.

What goes into each base image:

  1. A minimal foundation: distroless or a slim distribution, chosen per runtime (question 70).
  2. A non-root user with a fixed number, already set as the default.
  3. The quiet essentials: CA certificates, time zone data, and a sensible locale.
  4. Standard labels: source repository, version and build date (question 220).
  5. Nothing team-specific. Teams add their own dependencies in their own Dockerfiles.

How it is built and published:

  1. Its own pipeline, starting from upstream images pinned by digest.
  2. Scanned, signed, with an SBOM and provenance, the same as any production image (question 146).
  3. Versioned tags such as base-node:20-2026.10.3, plus the digest. Teams pin the digest.
  4. Multi-platform, amd64 and arm64 (question 82).
  5. Rebuilt on a schedule, such as weekly, to pick up upstream fixes, and at once when a critical vulnerability lands.

How teams stay current:

  1. Automated pull requests, from Renovate or Dependabot, bump the base image digest in every repository, and each team's own pipeline proves the update works (question 166).
  2. Clear support rules: which versions are supported, and when old ones stop being allowed.
  3. A policy in the cluster that only allows images built on approved bases, using the signatures and provenance.

Make it easy to do the right thing: good documentation, a template Dockerfile per language, and a quick way to ask for help. Teams adopt a shared base when it saves them work.

166. How would you enforce base-image updates and vulnerability remediation across many repositories? ​

The short answer

Make updating automatic, make the state visible, and make falling behind costly. Bots open update pull requests in every repository, and safe patch updates merge automatically when checks pass. A dashboard shows which services run which base and which open vulnerabilities, with an owner for each. Fix deadlines are set by severity. Finally, the pipeline or the cluster refuses images whose base is too old or has critical findings past their deadline, with recorded exceptions.

1. Know where everything stands. You cannot fix what you cannot see. Build an inventory from SBOMs and registry data: for every running image, which base image and version it uses, and which vulnerabilities it has. Map every image to an owning team.

2. Automate the update itself.

  • Renovate or Dependabot in every repository, opening a pull request whenever a new base image digest or dependency version is published.
  • Auto-merge for low-risk updates, such as a base image patch, when every check passes. Most updates then happen with no human effort.

3. Set deadlines by severity.

SeverityFix within
Critical, or known to be exploited7 days
High30 days
Medium90 days

4. Enforce.

  • In the pipeline: fail builds with critical, fixable findings (question 137).
  • In the cluster: an admission policy that refuses images older than a set age, or with findings past their deadline (question 500).
  • Exceptions are allowed, but each has an owner, a reason and an expiry date (question 279).

5. Report. A weekly view per team of overdue findings, shared with team leads. People fix what is visible.

The order matters. Start with visibility and automation, not with blocking. Blocking first, with hundreds of old findings, stops every release and makes teams fight the process instead of fixing things.

167. How would you support both amd64 and arm64 workloads without maintaining unrelated Dockerfiles? ​

The short answer

Write one Dockerfile and build it for both platforms with Buildx. Use base images that are published for both. For the few steps that differ, such as downloading a processor-specific binary or cross-compiling, use the automatic TARGETARCH and BUILDPLATFORM variables. Then push both builds under one tag, as an image index. Run checks on both platforms in CI, ideally on native machines.

dockerfile
# syntax=docker/dockerfile:1
FROM --platform=$BUILDPLATFORM golang:1.23 AS build
ARG TARGETOS TARGETARCH
WORKDIR /src
COPY . .
# (1)
RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build -o /out/app ./cmd/app

FROM debian:12-slim
ARG TARGETARCH
# (2)
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl \
 && case "$TARGETARCH" in \
      amd64) TOOL_ARCH=x86_64 ;; \
      arm64) TOOL_ARCH=aarch64 ;; \
      *) echo "unsupported: $TARGETARCH" && exit 1 ;; \
    esac \
 && curl -fsSL -o /usr/local/bin/tool "https://example.com/tool-1.4-linux-${TOOL_ARCH}" \
 && chmod +x /usr/local/bin/tool \
 && rm -rf /var/lib/apt/lists/*
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]
  1. Cross-compiles on the build machine's own processor for each target, at full speed (question 83).
  2. The one step that really differs: a third-party tool published under different file names per processor. A case maps Docker's names to the tool's names, and fails loudly for anything unexpected. In real use, also check the download's hash.
bash
docker buildx build --platform linux/amd64,linux/arm64 -t myacr.azurecr.io/shop/app:1.4 --push .

What keeps it maintainable:

  1. One file. Differences live in a few clearly marked steps, not in copies.
  2. Multi-platform base images. Official images already publish both.
  3. Checks on both. An image that builds for ARM but crashes on it is worse than no ARM image. Run at least start-up checks on both, preferably on native ARM runners.
  4. docker buildx bake when you build many images, so the platform list lives in one definition file.

168. How would you measure and improve Docker build duration, image-pull time, image size, and runtime resource use? ​

The short answer

Measure each one continuously, with a trend, not a one-off. Build time per step and cache hit rate come from BuildKit's output. Pull time comes from the container runtime's events, such as Kubernetes' "pulled image in" messages. Image size is a pipeline output. Runtime use comes from monitoring, compared with what each container requests. Then improve each with its own toolbox, and alert when any of them regresses.

MetricHow to measureHow to improve
Build durationPer-step times from BuildKit, total pipeline timeLayer order, cache mounts, registry cache, parallel stages
Cache hit rateShare of steps marked CACHEDFix early cache breaks (question 64)
Image sizeCompressed size after pushMulti-stage, slim bases, .dockerignore
Pull timeRuntime events per nodeSmaller images, shared base layers, registry in the same region
Start-up timeTime from container start to readySmaller start-up work, lazy loading
CPU and memoryActual use against requests and limitsRight-size requests, fix leaks and hot spots

Getting the numbers:

bash
docker buildx build --progress=plain . 2>&1 | grep -E 'DONE|CACHED'    # (1)
kubectl get events -A --field-selector reason=Pulled                    # (2)
docker buildx imagetools inspect --raw myacr.azurecr.io/shop/api:1.4    # (3)
  1. Every build step's time and cache status.
  2. In Kubernetes, messages such as Successfully pulled image ... in 14.2s, per node and image.
  3. The raw manifest, whose layer sizes add up to the compressed size that every node downloads.

Improvements beyond the basics:

  • Pre-pulling. A small DaemonSet that pulls key images onto every node ahead of time, so scale-ups do not wait.
  • Lazy pulling, or image streaming. Some registries and clusters can start a container before the whole image has downloaded, fetching files as they are first read. Azure calls this artifact streaming and Google Kubernetes Engine calls it image streaming. It helps large images start quickly.
  • Right-sizing. Compare each container's real CPU and memory use, over weeks, with its requests. Requests set too high waste money, and requests set too low risk throttling and evictions (question 389).

Make regressions visible. Record these numbers for every build and release, and alert when, for example, image size grows by 20% or build time doubles. Most slowdowns creep in one small change at a time.

169. What failure modes would you consider before adopting containers for a stateful or security-sensitive workload? ​

The short answer

For stateful workloads, think about data. What happens to it when a container or a whole machine dies? How does storage perform? How do backups and point-in-time restores work? How does failover avoid two copies both thinking they are in charge? And how are upgrades done? For security-sensitive workloads, think about the shared kernel, other tenants on the same machine, how secrets reach the container, compliance scope, and proof of where images came from. Often the answer is a managed service, or dedicated machines with stronger isolation.

Stateful workloads, such as databases, queues and search engines:

  1. Data location. If a volume lives on a node's local disk and the node dies, the data dies too. Network storage survives, but is slower.
  2. Storage performance. Databases need predictable disk speed. Network disks and shared storage add delay and have limits on operations per second.
  3. Backups and restores. Backups must be consistent, and restores must be tested, including restoring to a point in time (question 95).
  4. Failover and split brain. When the primary copy fails, exactly one replica must take over. If two both believe they are primary, both accept writes and the data diverges. This is called split brain. Orchestrators move containers quickly, which can make this easier to trigger, not harder.
  5. Upgrades. Major version upgrades often need data migration, which a simple image change cannot do.
  6. Operational maturity. Running a database well is a specialist job. Kubernetes operators (question 331) help, but someone still needs to understand failure recovery.

Security-sensitive workloads, such as payment or health data:

  1. Shared kernel. One kernel flaw affects every container on the machine (question 102).
  2. Neighbours. Other teams' or customers' containers on the same node are a risk.
  3. Secret handling. How secrets arrive, who can read them, and where they could leak (question 145).
  4. Compliance scope. Standards such as PCI DSS for card data can pull every system that shares infrastructure with the sensitive workload into scope for audits.
  5. Supply chain. Every image must be traceable to reviewed source (question 147).
  6. Runtime monitoring. You need to detect unusual behaviour inside containers, such as an unexpected shell starting.

Common answers:

  • Use the cloud's managed database instead of running one yourself, for most teams.
  • Run sensitive workloads on dedicated node pools, separate from everything else.
  • Use sandboxed runtimes, such as gVisor or Kata Containers, for stronger isolation (question 20).
  • Write down the failure scenarios and test them: kill the primary, fill the disk, restore last night's backup.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Docker, CI/CD, Kubernetes & Cloud
Your project
Docker
CI/CD
Kubernetes
Cloud
Observability
Scenarios
Other topics
Nothing picked yet