Level: IntermediateInterview

Docker Interview Questions: 110 Most Asked, with Full Answers

Updated 58 min read
Docker Interview Questions featured image: topics from images to production

Docker interview questions come up in almost every backend, DevOps and cloud interview today, because nearly every team ships its apps in containers. This post gives you 110 of the most asked questions, grouped from basic to advanced, and every one of them now has a full answer in simple English, with commands and examples you can try.

If you build Go services, first read our Go Docker deployment guide, which builds a tiny image step by step. For Go-specific build and CI questions, see the Go deployment interview questions. All answers here match current Docker Engine releases.

What Do Docker Interview Questions Cover?

Docker is a tool that packs your app and everything it needs into one unit called an image. When you run an image, you get a container: a small, isolated process that behaves the same on every machine.

Think of a shipping container at a port. The crane does not care if it holds rice or laptops, because every container has the same size and hooks. Docker gives software the same idea, so “it works on my machine” stops being a problem.

Most Docker interview questions test five areas: images, containers, networking, storage and security. Senior rounds add Docker Compose, production debugging and real scenarios.

How to Use These Docker Interview Questions

Do not try to learn 110 answers by heart. Instead, use the list in three passes.

  1. First, read each question and try to answer it in two or three sentences before you read the answer.
  2. Next, practise the marked ones out loud, with a small example from your own work.
  3. Finally, run the commands from the hands-on section on your laptop, because interviewers love “have you done this?” follow-ups.

The table below shows how interview rounds usually use these questions.

RoundFocusQuestion range
Phone screenBasics and termsQ1 to Q25
Technical roundDockerfile, networks, volumes, ComposeQ26 to Q85
Senior or DevOps roundSecurity, production, scenariosQ86 to Q110
Hands-on testWrite a Dockerfile or Compose fileHands-on section

How Docker Works

Every Docker flow follows the same path. You write a Dockerfile, build it into an image, push the image to a registry, and run it as a container anywhere.

Docker interview questions diagram showing Dockerfile, build, image, registry and running container
A Dockerfile builds an image, the registry stores it, and docker run starts it as a container on any host.

Behind the scenes, the Docker CLI sends your commands to the Docker daemon (dockerd). The daemon uses containerd and runc to start the container, and the Linux kernel isolates it with namespaces and cgroups.

Basic Docker Interview Questions with Answers

These Docker interview questions check that you know the core words and ideas. Freshers should be able to answer all of them, so read each answer and try the commands on your laptop.

Q1. What is Docker, and what problem does it solve?

Docker is a platform to build, ship and run apps inside containers. A container packs your app with its libraries, runtime and settings into one unit. So the app runs the same way on your laptop, a test server and the cloud.

The problem Docker solves is the famous “it works on my machine”. Before containers, an app could break on a server because of a different library version, OS package or config. With Docker, you ship the whole environment with the app, so those differences disappear. It also makes setup fast, because a new developer can start the full stack with one command.

Q2. What is a container?

A container is a running app that is isolated from other apps on the same machine. It has its own files, network, process list and host name, but it shares the host’s Linux kernel. Under the hood, a container is just a normal Linux process with extra walls around it.

Think of flats in one building. Each family has its own rooms and front door, but they all share the same foundation, water and electricity lines. Containers share the kernel the same way, which is why they are light and start in seconds.

Q3. What is the difference between a container and a virtual machine?

A virtual machine (VM) runs a full guest operating system on top of a hypervisor, with its own kernel. A container shares the host kernel and isolates only the app process. So containers are much smaller and faster to start, while VMs give stronger isolation.

FeatureContainerVirtual machine
IsolationProcess level, shares host kernelFull guest OS on a hypervisor
Start timeSeconds or lessUsually minutes
SizeMegabytesGigabytes
DensityMany per hostFewer per host
Security boundaryWeaker, kernel is sharedStronger
Best forMicroservices, CI, fast scalingMixed OS, strong isolation
Docker interview questions comparison of containers and virtual machines
Containers share the host kernel and start in seconds, while virtual machines each carry a full guest operating system.

So use containers for most modern apps, and use VMs when you need a different kernel or a hard security boundary. Many clouds run containers inside VMs to get both.

Q4. What is a Docker image?

A Docker image is a read-only template that holds everything needed to run an app: a base file system, your code or binary, libraries, environment variables and the start command. You build an image from a Dockerfile, and you can store it in a registry and share it.

An image is made of layers stacked on top of each other. Each layer stores only the changes from the one below, so images that share a base layer save disk space and download time.

Q5. What is the difference between an image and a container?

An image is the template, and a container is a running copy of it. A simple way to remember it: an image is a recipe, and a container is the dish you cook from it. You can cook many dishes from one recipe, and you can start many containers from one image.

Technically, a container adds a thin writable layer on top of the image’s read-only layers. Anything the container writes goes into that writable layer, so the image itself never changes.

Q6. What is a Dockerfile?

A Dockerfile is a plain text file with step-by-step instructions to build an image. Each line starts with an instruction, such as FROM, COPY, RUN or CMD. Then docker build reads the file and creates the image.

FROM golang:1.27 AS build
WORKDIR /src
COPY . .
RUN go build -o /app .

FROM debian:bookworm-slim
COPY --from=build /app /app
CMD ["/app"]

Because the Dockerfile is code, you keep it in Git next to your app. So every build is repeatable, and anyone can see exactly how the image was made.

Q7. What is Docker Hub, and what is a registry?

A registry is a server that stores and shares Docker images, like GitHub but for images. You docker push an image to it and docker pull it on another machine. Docker Hub is Docker’s public registry and the default one, so docker pull nginx downloads from Docker Hub.

Companies also use private registries, such as Amazon ECR, Google Artifact Registry, Azure Container Registry, GitHub Container Registry or a self-hosted Harbor. Docker Hub has pull rate limits for anonymous and free users, so teams usually log in or use a mirror in CI.

Q8. What is the Docker daemon, and what does the Docker CLI do?

The Docker daemon, dockerd, is a background service that does the real work. It builds images, starts and stops containers, and manages networks and volumes. The Docker CLI, the docker command you type, is only a client.

When you run docker ps, the CLI sends a request to the daemon through a REST API, usually over the Unix socket /var/run/docker.sock. The daemon answers, and the CLI prints the result. So the CLI can also talk to a daemon on another machine.

Q9. What are containerd and runc, and how do they relate to Docker?

Docker is built from several layers of tools. containerd is a container runtime that manages the full life of containers: pulling images, storing them, and starting and stopping containers. runc is a small low-level tool that actually creates the container using Linux namespaces and cgroups.

So the chain looks like this: docker CLI talks to dockerd, dockerd talks to containerd, and containerd uses runc to start each container. Kubernetes can use containerd directly, without Docker, which is why Docker images still run on Kubernetes.

Q10. What is the OCI (Open Container Initiative), and why does it matter?

The OCI is an open group, under the Linux Foundation, that sets standards for containers. It has three main specs: the image format, the runtime (how to run a container) and the distribution (how registries share images).

It matters because it stops lock-in. An image built with Docker follows the OCI image format, so it runs on containerd, CRI-O, Podman or any other OCI tool. So you can build with one tool and run with another.

Q11. What happens step by step when you run docker run nginx?

This is a classic question, so learn the steps in order.

  1. First, the CLI sends the request to the Docker daemon.
  2. Next, the daemon checks if the nginx:latest image is on the machine. If not, it pulls it from Docker Hub.
  3. Then it creates a new container from the image and adds a writable layer on top.
  4. It connects the container to the default bridge network and gives it an IP address.
  5. After that, containerd and runc start the process with its own namespaces and cgroups.
  6. Finally, nginx starts as the main process (PID 1) inside the container, and its output goes to the container logs.

Since no -d flag was given, the terminal stays attached to the container’s output until you stop it.

Q12. What is an image tag, and why is latest a risky tag?

A tag is a readable label for an image version, written after a colon, such as nginx:1.27 or shop-api:2.3.1. If you do not give a tag, Docker uses latest.

latest is risky because it is just a name, not “the newest version”. It can point to a different image tomorrow. So two servers pulling latest on different days can run different code, and rollbacks become hard. In production, always use a fixed version tag, or better, a digest.

Q13. What is an image digest, and when would you pin one?

A digest is a unique fingerprint of an image’s content, a SHA-256 hash such as nginx@sha256:4c0f.... Unlike a tag, a digest can never point to different content. If one byte changes, the digest changes.

You pin a digest when you need exact, repeatable builds and deploys, for example for base images in production Dockerfiles or for security-approved images. Tools like Renovate or Dependabot can update pinned digests for you when new versions come out.

Q14. How do you list running containers and all containers?

docker ps lists only running containers. docker ps -a lists all containers, including stopped ones. You can also filter and format the output.

docker ps                                  # running containers
docker ps -a                               # all containers, running and stopped
docker ps -q                               # only the container IDs
docker ps --filter "status=exited"         # only stopped containers
docker ps --format "{{.Names}}\t{{.Status}}"

Q15. How do you stop, start, restart and remove a container?

Each action has a simple command. You can use the container name or ID.

docker stop api        # stop gracefully (SIGTERM, then SIGKILL)
docker start api       # start a stopped container again
docker restart api     # stop, then start
docker rm api          # remove a stopped container
docker rm -f api       # stop and remove in one step
docker container prune # remove all stopped containers

Removing a container deletes its writable layer, so any data not in a volume is lost.

Q16. What is the difference between docker stop and docker kill?

docker stop sends SIGTERM to the main process, which asks it to shut down cleanly. If the process is still running after a grace period, 10 seconds by default, Docker sends SIGKILL. docker kill sends SIGKILL straight away, so the process has no chance to clean up.

So use docker stop normally, because it lets your app finish requests, close database connections and save state. Use docker kill only when a container is stuck. You can change the grace time with docker stop -t 30 api.

Q17. How do you see the logs of a container?

Use docker logs. It shows everything the main process wrote to standard output and standard error. That is why containerised apps should log to stdout and stderr, not to files.

docker logs api                 # all logs so far
docker logs -f api              # follow new lines live
docker logs --tail 100 api      # only the last 100 lines
docker logs --since 10m api     # logs from the last 10 minutes
docker logs -t api              # add timestamps

Q18. How do you open a shell inside a running container?

Use docker exec -it with a shell program. The -i keeps input open, and -t gives you a terminal.

docker exec -it api sh          # most small images have sh
docker exec -it api bash        # if bash is installed
docker exec api ls /app         # run one command without a shell

If the image has no shell, such as distroless or scratch, exec fails. Then you use a debug container instead, which is covered in the scenario questions.

Q19. What is Docker Desktop, and how is it different from Docker Engine?

Docker Engine is the core open-source part: the daemon, the CLI and the runtime. It runs natively on Linux. Docker Desktop is an app for macOS, Windows and Linux that bundles Docker Engine inside a small Linux VM, plus a GUI, Docker Compose, Kubernetes, BuildKit and extra tools.

On Mac and Windows you need Desktop (or another tool like Rancher Desktop, Colima or Podman), because containers need a Linux kernel. Also, Docker Desktop is free for personal use, education and small businesses, but larger companies need a paid subscription. Docker Engine on Linux servers is free.

Q20. Which Linux kernel features make containers possible?

Containers are built on three main Linux features.

  • Namespaces: give each container its own view of processes, network, mounts, host name and users.
  • Cgroups (control groups): limit and measure how much CPU, memory and I/O a container can use.
  • Union file systems, such as OverlayFS: stack image layers and add a writable layer on top, without copying everything.

Security features add more walls, such as capabilities, seccomp and AppArmor or SELinux. Together, they make a normal process look like its own small machine.

Q21. What are namespaces, and which ones does Docker use?

A namespace limits what a process can see. Inside a namespace, the process sees only its own resources, as if it were alone on the machine. Docker creates a set of namespaces for every container.

NamespaceWhat it isolates
PIDProcess IDs, so the app sees itself as PID 1
NETNetwork interfaces, IP addresses and ports
MNTMount points and the file system view
UTSHost name and domain name
IPCShared memory and message queues
USERUser and group IDs (used in rootless and userns modes)

So two containers can both listen on port 80 and both have a process with PID 1, because each has its own namespaces.

Q22. What are cgroups, and what do they limit?

Cgroups (control groups) are a Linux feature that limits and tracks how much of the machine a group of processes can use. Docker puts each container in its own cgroup. So one busy container cannot use all the CPU or memory and starve the others.

Cgroups can limit memory, CPU time, the number of processes (PIDs) and disk I/O. If a container goes over its memory limit, the kernel’s OOM killer stops it. Most current Linux systems use cgroups v2, which Docker supports fully.

Q23. Can you run Windows containers on Linux, or Linux containers on Windows?

A container uses the host’s kernel, so a Windows container needs a Windows kernel and a Linux container needs a Linux kernel. So you cannot run Windows containers on a Linux host.

On Windows, Docker Desktop runs Linux containers inside a lightweight Linux VM (using WSL 2), so Linux containers do work there. It can also switch to Windows container mode to run native Windows containers. On macOS, Docker Desktop also uses a Linux VM.

Q24. What is the difference between docker run and docker start?

docker run creates a new container from an image and starts it, all in one step. docker start starts an existing container that was stopped. So run is like buying a new phone and turning it on, and start is like turning your old phone back on.

Each docker run gives you a fresh container with a clean writable layer. A restarted container keeps the files it wrote before it stopped, as long as you did not remove it.

Q25. What do the -d, -it and –rm flags do in docker run?

These are the most used docker run flags.

FlagMeaningExample use
-dDetached: run in the background and print the container IDServers and databases
-iKeep standard input openInteractive tools
-tGive the container a terminalShells, with -i as -it
--rmRemove the container when it stopsOne-off tasks and tests
docker run -d --name web -p 8080:80 nginx:1.27   # background server
docker run -it --rm alpine:3.22 sh               # throwaway shell, removed on exit

Dockerfile and Image Docker Interview Questions with Answers

Most technical rounds spend the longest time on images. So these Docker interview questions focus on the Dockerfile, the build cache and image size.

Q26. What are image layers, and how does the build cache use them?

Each instruction in a Dockerfile that changes files, such as RUN, COPY or ADD, creates a new layer. A layer stores only the changes from the layer below. The final image is all the layers stacked together, like transparent sheets placed one on top of another.

When you build again, Docker checks each instruction from the top. If the instruction and its inputs are the same as last time, it reuses the cached layer instead of running it again. However, once one layer changes, every layer after it must be rebuilt. So the order of your instructions decides how fast your builds are.

Q27. Why should you copy dependency files before the rest of your code?

Dependencies change rarely, but your code changes all the time. If you copy all the code first and then download dependencies, every small code change breaks the cache, and the slow download runs again.

So copy only the dependency files first, download dependencies, and copy the rest of the code after that. Then a code change only rebuilds the last few layers.

FROM golang:1.27
WORKDIR /src

COPY go.mod go.sum ./     # changes rarely
RUN go mod download       # cached until go.mod or go.sum changes

COPY . .                  # changes often
RUN go build -o /app ./cmd/api

The same idea works for other languages, such as package.json for Node.js or requirements.txt for Python.

Q28. What is the difference between RUN, CMD and ENTRYPOINT?

These three look similar, but they run at different times.

InstructionWhen it runsPurpose
RUNAt build timeInstall packages, compile code, creates a layer
CMDWhen the container startsDefault command or default arguments, easy to override
ENTRYPOINTWhen the container startsThe main program that always runs

So RUN apt-get install curl happens once while building the image. CMD and ENTRYPOINT describe what happens each time a container starts. If a Dockerfile has several CMD lines, only the last one counts.

Q29. What is the difference between shell form and exec form in CMD?

Exec form is written as a JSON list, such as CMD ["/app", "--port", "8080"]. Docker runs the program directly, so it becomes PID 1 and receives signals like SIGTERM. Shell form is written as plain text, such as CMD /app --port 8080. Docker wraps it in /bin/sh -c, so the shell becomes PID 1.

The shell form causes a common problem. The shell may not pass SIGTERM to your app, so docker stop waits the full timeout and then kills it. So always prefer exec form for CMD and ENTRYPOINT, and use shell form only when you need shell features like variable expansion.

Q30. How do CMD and ENTRYPOINT work together?

When both are set, CMD becomes the default arguments to ENTRYPOINT. Anything you type after the image name in docker run replaces CMD, but ENTRYPOINT stays.

ENTRYPOINT ["/app"]
CMD ["--port", "8080"]
docker run shop-api                 # runs: /app --port 8080
docker run shop-api --port 9090     # runs: /app --port 9090
docker run --entrypoint sh -it shop-api   # replace the entrypoint for debugging

So use ENTRYPOINT for the program and CMD for its default flags. This makes the image act like a command-line tool.

Q31. What is the difference between COPY and ADD?

COPY copies files and folders from the build context into the image, and nothing more. ADD does the same, but it can also download a file from a URL and unpack a local tar archive automatically.

Those extra features can surprise you, for example an archive being unpacked when you just wanted to copy it. So the Docker docs recommend COPY for normal use. Use ADD only when you really want the auto-unpack, or to add a remote file with a checksum check.

Q32. What does WORKDIR do?

WORKDIR sets the working folder for the instructions that follow, such as RUN, COPY, CMD and ENTRYPOINT. It also creates the folder if it does not exist.

WORKDIR /app
COPY . .          # copies into /app
RUN go build .    # runs inside /app

Use WORKDIR instead of RUN cd /app && ..., because a cd inside RUN only lasts for that one line.

Q33. What is the difference between ARG and ENV?

ARG defines a variable that exists only during the build. You set it with docker build --build-arg VERSION=1.2. ENV sets an environment variable that is saved in the image, so it exists during the build and also inside every running container.

FeatureARGENV
Available at build timeYesYes
Available in running containersNoYes
Set from outside--build-arg-e on docker run
Typical useVersions, build optionsApp settings, PATH, TZ

Neither one is safe for secrets, because both can show up in the image history. Use build secrets instead.

Q34. What does EXPOSE do, and does it publish a port?

EXPOSE 8080 only documents which port the app inside the container listens on. It does not open or publish the port to the host. It is a note for people and tools reading the image.

To actually reach the port from outside, you publish it with -p 8080:8080 on docker run, or a ports entry in Compose. The -P flag publishes all exposed ports to random host ports.

Q35. What is a multi-stage build, and why does it shrink images?

A multi-stage build uses more than one FROM line in one Dockerfile. The first stage has all the build tools, such as a compiler, and builds your app. After that, the final stage starts from a small base image and copies only the finished files from the first stage with COPY --from.

# Stage 1: build
FROM golang:1.27 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /app ./cmd/api

# Stage 2: run
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /app /app
ENTRYPOINT ["/app"]

The compiler, source code and caches never reach the final image. So a Go image can drop from over 800 MB to around 10 to 20 MB. A smaller image downloads faster and has fewer packages for attackers to use.

Q36. How do you choose a base image: full, slim, Alpine, distroless or scratch?

The base image is the starting point of your image, and it decides the size and what tools are inside. The table below compares the common choices.

Base imageRough sizeHas a shell and package managerGood for
Full (debian, ubuntu)75 to 120 MB+YesBuilds, apps needing many tools
Slim (debian:bookworm-slim)About 30 MBYesMost apps that need glibc
AlpineAbout 5 to 8 MBYes, uses musl and apkSmall images, if musl is fine
DistrolessAbout 2 to 20 MBNo shellProduction apps, smaller attack surface
scratch0 MBNothing at allStatic binaries such as Go

So for a Go service built with CGO_ENABLED=0, distroless static or scratch is a great choice. For apps with native libraries, start with slim.

Q37. What problems can Alpine cause because it uses musl instead of glibc?

Alpine uses the musl C library instead of glibc, which most Linux distributions use. Most of the time this is fine, but it can cause a few surprises.

  • Programs built for glibc may not run, or need extra packages, so prebuilt binaries can fail.
  • Python and Node.js packages with native code often need to be compiled from source, which makes builds slower and images bigger.
  • DNS and memory allocation behave a little differently, which has caused performance and lookup issues in some apps.

For Go, a static binary built with CGO_ENABLED=0 does not use any C library, so Alpine, distroless and scratch all work well.

Q38. What is a .dockerignore file, and why is it important?

A .dockerignore file lists files and folders that should not be sent to the Docker builder. It works like .gitignore. Without it, Docker sends your whole project folder as the build context, including .git, node_modules, logs and secret files.

.git
node_modules
*.log
.env
bin/
tmp/

It makes builds faster, because less data is sent. It also stops secrets like .env from ending up in the image by accident with COPY . ., and avoids breaking the cache when unrelated files change.

Q39. How do you reduce the size of a Docker image?

Use several techniques together.

  1. First, use a multi-stage build, so build tools stay out of the final image.
  2. Next, pick a small base image, such as slim, Alpine, distroless or scratch.
  3. Then add a .dockerignore file, so only needed files are copied.
  4. Also, install only runtime packages, with options like apt-get install --no-install-recommends.
  5. Clean package caches in the same RUN line that installs them.
  6. Finally, check the result with docker images and see which layers are big with docker history.

Each RUN creates a layer, and a later layer cannot shrink an earlier one. If you install packages in one RUN and delete the cache in the next RUN, the cache files still live in the first layer, so the image does not get smaller.

# Good: install and clean up in the same layer
RUN apt-get update \
    && apt-get install -y --no-install-recommends ca-certificates curl \
    && rm -rf /var/lib/apt/lists/*

Joining apt-get update and install also avoids a stale cache. If they were separate, Docker could reuse an old update layer and install outdated packages.

Q41. What is BuildKit, and what does it improve?

BuildKit is Docker’s modern build engine, and it has been the default builder since Docker Engine 23.0. It replaced the older builder and brought many improvements.

  • Parallel stages: independent build stages run at the same time.
  • Smarter caching: it skips stages that the final image does not need, and supports cache import and export for CI.
  • Build secrets and SSH: you can use secrets during a build without saving them in a layer.
  • Cache mounts: keep package download caches between builds.
  • Multi-platform builds: build for amd64 and arm64 with docker buildx.

Q42. How do you pass secrets to a build without saving them in a layer?

Use a BuildKit secret mount. The secret is mounted as a file only while that one RUN step runs, and it is never written into any layer or the image history.

# Dockerfile
RUN --mount=type=secret,id=npm_token \
    NPM_TOKEN=$(cat /run/secrets/npm_token) npm ci
docker build --secret id=npm_token,src=$HOME/.npm_token -t web:1.0 .

For private Git repositories, you can use --mount=type=ssh with docker build --ssh default, so your SSH key is never copied. Never use ARG or ENV for secrets, because they can be seen with docker history.

Q43. What is a cache mount in BuildKit?

A cache mount keeps a folder between builds, outside the image layers. It is great for package caches, such as the Go module and build cache, npm or pip. So even when a layer must rebuild, the downloads are already there, and the build is much faster.

RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    go build -o /app ./cmd/api

The cached files are not part of the final image, so the image stays small.

Q44. How do you build images for more than one CPU type, such as amd64 and arm64?

Use docker buildx build with the --platform flag. It builds one image for each platform and pushes them together under one tag, as a multi-platform image (an image index). When someone pulls the tag, Docker picks the right version for their CPU automatically.

docker buildx build \
  --platform linux/amd64,linux/arm64 \
  -t registry.example.com/shop-api:1.4.0 \
  --push .

This matters because many developers use Apple Silicon (arm64) laptops, and many clouds offer cheaper arm64 servers. For Go, cross-compiling is very fast, because you can set GOOS and GOARCH in the build stage instead of emulating the other CPU.

Q45. What does docker buildx do?

docker buildx is the CLI plugin for BuildKit, and it gives you advanced build features. In current Docker versions, docker build itself uses buildx and BuildKit behind the scenes.

With buildx you can build for many platforms, create separate builder instances (including remote ones or ones running in Kubernetes), export and import build cache to a registry for fast CI builds, and use docker buildx bake to build many images from one config file.

Q46. What is the HEALTHCHECK instruction?

HEALTHCHECK tells Docker how to check that the app inside a container is working, not just that the process is running. Docker runs the check command on a schedule and marks the container as starting, healthy or unhealthy.

HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD ["/app", "healthcheck"]

Docker Compose can wait for a healthy status before starting other services. However, Kubernetes ignores the Dockerfile HEALTHCHECK and uses its own liveness and readiness probes. Also, distroless images have no curl, so a small health command built into your own binary works well.

Q47. What does the USER instruction do, and why use it?

USER sets which user runs the following RUN steps and the main process of the container. By default, containers run as root, which is risky. If an attacker breaks into your app, root inside the container makes it easier to damage the container or escape to the host.

FROM debian:bookworm-slim
RUN useradd --system --uid 10001 appuser
COPY --chown=appuser:appuser app /app
USER 10001
ENTRYPOINT ["/app"]

Using a numeric user ID is a good habit, because tools like Kubernetes can then check that the container does not run as root. Distroless images offer a nonroot variant with a ready-made user.

Q48. How do you tag and push an image to a private registry?

The image name must include the registry address. So you tag the image with that full name, log in, then push.

docker build -t shop-api:1.4.0 .
docker tag shop-api:1.4.0 123456789012.dkr.ecr.ap-south-1.amazonaws.com/shop-api:1.4.0
aws ecr get-login-password --region ap-south-1 | \
  docker login --username AWS --password-stdin 123456789012.dkr.ecr.ap-south-1.amazonaws.com
docker push 123456789012.dkr.ecr.ap-south-1.amazonaws.com/shop-api:1.4.0

For other registries, the steps are the same: docker login registry.example.com, then tag and push. In CI, use short-lived tokens instead of saved passwords.

Q49. How do you inspect the layers and history of an image?

Docker gives you a few commands to look inside an image.

docker history shop-api:1.4.0          # each layer, its size and the instruction
docker image inspect shop-api:1.4.0    # full JSON: env, entrypoint, layers, labels
docker image ls                        # sizes of local images

docker history is the quickest way to find which instruction made the image big. Free tools like dive go further and show which files each layer added, so you can spot leftovers like caches.

Q50. What is a dangling image, and how do you clean up unused images?

A dangling image is an image layer with no tag, shown as <none>:<none>. It usually appears when you rebuild an image with the same tag, so the old image loses its name. Dangling images just waste disk space.

docker image prune          # remove dangling images
docker image prune -a       # remove all images not used by any container
docker system df            # see how much space images, containers and volumes use
docker system prune         # remove stopped containers, unused networks, dangling images, build cache

Be careful with -a and --volumes, because they remove more than you might expect. On CI machines, run a prune step regularly so the disk does not fill up.

Container Lifecycle and Networking Docker Interview Questions with Answers

Once a container runs, you must stop it cleanly and connect it to other services. These Docker interview questions cover both, and they are where many candidates get stuck.

Q51. What are the states a container can be in?

A container moves through a few simple states during its life. You can see the state with docker ps -a or docker inspect.

StateMeaning
createdMade with docker create, but not started yet
runningThe main process is running
pausedProcesses are frozen with docker pause
restartingDocker is restarting it because of a restart policy
exitedThe main process stopped, with an exit code
removingDocker is deleting it
deadRemoval failed part way, which is rare

A container lives exactly as long as its main process. When that process ends, the container moves to exited.

Q52. What do restart policies do: no, on-failure, always and unless-stopped?

A restart policy tells Docker what to do when a container stops. You set it with --restart on docker run, or restart: in Compose.

PolicyWhat it does
noNever restart. This is the default
on-failure[:max]Restart only if the exit code is not 0, optionally up to a maximum number of tries
alwaysAlways restart, and also start it again when the Docker daemon starts
unless-stoppedLike always, but not if you stopped it by hand before the daemon restarted

So unless-stopped is a good default for long-running services on a single server. In Kubernetes, the platform handles restarts instead.

Q53. Why should a container run only one main process?

Docker watches only the main process (PID 1). If you run several apps in one container, such as a web server and a database, Docker cannot tell if one of them crashed, logs get mixed up, and you cannot scale or update them separately.

So the usual rule is one concern per container. Run the API and the database as two containers and connect them with a network. A container can still have helper child processes, such as worker processes started by nginx, as long as there is one clear main job.

Q54. What is PID 1 inside a container, and why does signal handling matter?

The main process in a container gets process ID 1. In Linux, PID 1 is special. It does not get the default signal behaviour, so if it does not set up its own handler for SIGTERM, the signal is ignored. PID 1 is also expected to clean up finished child processes (zombie processes).

So when docker stop sends SIGTERM, an app that does not handle it just keeps running, and Docker kills it after the timeout. Your app should catch SIGTERM and shut down cleanly. In Go, signal.NotifyContext makes this easy.

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()

<-ctx.Done() // wait for docker stop
log.Println("shutting down")
srv.Shutdown(context.Background()) // finish in-flight requests

Q55. How does docker stop send signals, and what is the default timeout?

docker stop sends the stop signal, which is SIGTERM by default, to PID 1. Then it waits for the grace period, 10 seconds by default. If the container has not exited by then, Docker sends SIGKILL, which cannot be ignored.

You can change the timeout with docker stop -t 30, or stop_grace_period in Compose. You can change the signal with the STOPSIGNAL instruction in the Dockerfile, for example STOPSIGNAL SIGQUIT for nginx graceful shutdown.

Q56. What is the –init flag used for?

docker run --init adds a tiny init program (tini) as PID 1. It starts your app as its child, passes signals like SIGTERM to it, and cleans up zombie processes.

It is useful when your app was not written to be PID 1, for example a shell script or a program that starts child processes. You can also add tini inside the image with ENTRYPOINT ["tini", "--", "/app"]. A Go app that handles SIGTERM and starts no child processes does not need it.

Q57. What network drivers does Docker have: bridge, host, none, overlay and macvlan?

Docker networking uses drivers, and each one connects containers in a different way.

DriverWhat it doesTypical use
bridgePrivate network on one host, with NAT to the outsideDefault for single-host containers
hostContainer uses the host’s network directly, no isolationVery high network performance
noneNo network at allBatch jobs that need no network
overlayNetwork that spans many Docker hostsDocker Swarm services
macvlanContainer gets its own MAC address on the physical networkApps that must look like real devices
ipvlanLike macvlan, but shares the host MAC addressNetworks that limit MAC addresses

Most of the time you use user-defined bridge networks on one host, and Kubernetes networking in clusters.

Q58. What is the default bridge network, and how is a user-defined bridge better?

When you start a container with no network option, Docker attaches it to the default network called bridge (the docker0 interface). A user-defined bridge is one you create with docker network create.

FeatureDefault bridgeUser-defined bridge
Find containers by name (DNS)No, only by IPYes
IsolationAll default containers share itOnly containers you attach
Connect or disconnect a running containerMust recreateYes, at any time
RecommendedFor quick tests onlyFor real apps

So always create your own network for apps that talk to each other. Docker Compose does this for you automatically.

Q59. How do containers on the same network find each other by name?

On a user-defined network, Docker runs an embedded DNS server. Each container is registered under its name and any network aliases. So a container can call another one by name, and Docker turns the name into the right IP address.

docker network create shop-net
docker run -d --name db --network shop-net postgres:17
docker run -d --name api --network shop-net -e DB_HOST=db shop-api:1.4.0
# inside api, the host name "db" resolves to the database container

This is much better than using IP addresses, because container IPs change every time a container is recreated.

Q60. What is the difference between EXPOSE and publishing a port with -p?

EXPOSE in a Dockerfile only documents the port the app uses. Nothing outside the container can reach it because of EXPOSE alone. Publishing with -p actually opens a port on the host and forwards traffic to the container.

Containers on the same Docker network can always reach each other on any port the app listens on, with no EXPOSE or -p needed. So you only publish ports that people or programs outside Docker must use, such as the API port, and keep the database unpublished.

Q61. What does -p 8080:80 mean?

It means “forward port 8080 on the host to port 80 inside the container”. The format is host:container. So if nginx listens on port 80 inside the container, you open http://localhost:8080 in your browser.

docker run -d -p 8080:80 nginx:1.27           # all host IPs, port 8080
docker run -d -p 127.0.0.1:8080:80 nginx:1.27 # only reachable from this machine
docker run -d -p 80 nginx:1.27                # random host port

By default, a published port listens on all host interfaces, so it can be reachable from the outside network. Bind to 127.0.0.1 for services that should stay local, such as a database on your laptop.

Q62. When would you use host networking?

With --network host, the container shares the host’s network stack. There is no separate IP and no port mapping, so the app listens directly on the host’s ports.

Use it when you need the best network performance, when an app must see the host’s real network interfaces (such as some monitoring agents), or when it uses many dynamic ports. The downsides are no network isolation and possible port conflicts. Also, host networking works fully only on Linux. On Docker Desktop it has limits, because containers run inside a VM.

Q63. How do you connect a container to two networks?

Start it on one network, then attach the second with docker network connect. The container then gets one network interface and IP address for each network.

docker network create frontend
docker network create backend
docker run -d --name api --network frontend shop-api:1.4.0
docker network connect backend api

This is a common way to split traffic. For example, the proxy and API share frontend, while only the API and database share backend. So the proxy can never talk to the database directly. In Compose, you list several networks under the service.

Q64. How does DNS work inside a Docker network?

On a user-defined network, each container’s /etc/resolv.conf points to Docker’s embedded DNS server at 127.0.0.11. When the app looks up a name, the embedded server first checks container names, service names and aliases on the same network. If the name is not a container, it forwards the query to the host’s normal DNS servers.

In Compose, every service name is a DNS name, and if a service has several replicas, the name returns all their IPs. You can set custom DNS servers with --dns if needed.

Q65. How do you check which ports a container has published?

Use docker port for a quick answer, or docker ps and docker inspect for more detail.

docker port api                     # e.g. 8080/tcp -> 0.0.0.0:8080
docker ps --format "{{.Names}}: {{.Ports}}"
docker inspect --format '{{json .NetworkSettings.Ports}}' api

On the host, you can also use ss -tlnp to see which ports are listening.

Storage and Volume Docker Interview Questions with Answers

Containers lose their files when you delete them, so interviewers always ask how you keep data safe. These Docker interview questions cover volumes, bind mounts and running databases in containers.

Q66. Why is data inside a container lost when you remove it?

A container’s files live in a thin writable layer on top of the read-only image layers. That writable layer belongs to the container. When you remove the container with docker rm, Docker deletes the layer, and every file written inside the container goes with it.

Stopping and restarting a container keeps the layer, so data survives a restart. However, containers are meant to be thrown away and replaced, for example on every deploy. So any data you need to keep must go into a volume or an outside service, such as a managed database or object storage.

Q67. What is the difference between a volume and a bind mount?

Both put data outside the container’s writable layer, so it survives when the container is removed. The difference is who manages the folder.

FeatureVolumeBind mount
Managed byDocker, in its own storage areaYou, any host path
Created with-v dbdata:/data or --mount type=volume-v /home/me/app:/app or --mount type=bind
Works the same on every hostYesDepends on the host path
Backup and moveEasy with Docker commandsNormal file tools
Best forDatabase data, app data in productionLocal development, config files

So use volumes for data that must be kept safe, and bind mounts for sharing your source code with a container while you develop. The --mount syntax is longer but clearer, so many teams prefer it in scripts.

Q68. What is a tmpfs mount?

A tmpfs mount stores files in the host’s memory, not on disk. The data disappears when the container stops. It is fast and never written to disk.

docker run -d --tmpfs /tmp:size=64m shop-api:1.4.0

Use it for temporary files, caches and sensitive data that should never touch the disk, such as short-lived tokens. It also pairs well with a read-only root file system, because the app still needs somewhere to write temp files.

Q69. When should you use a named volume instead of a bind mount?

Use a named volume when the data belongs to the app and must stay safe, such as database files, uploaded files or queue data. Docker manages the folder, sets the right permissions and keeps it the same on every machine, so your Compose file works anywhere.

Use a bind mount when you want the container to see files from a specific place on your host. The main examples are your source code during development, so changes show up at once, and a config file you edit on the host.

Q70. How do you back up and restore a Docker volume?

A simple and common way is to run a temporary container that mounts the volume and a host folder, then use tar to copy the data.

# Backup: pack the volume into a tar file in the current folder
docker run --rm -v dbdata:/data -v "$PWD":/backup alpine:3.22 \
  tar czf /backup/dbdata-backup.tgz -C /data .

# Restore: unpack the tar file into a (new) volume
docker run --rm -v dbdata:/data -v "$PWD":/backup alpine:3.22 \
  tar xzf /backup/dbdata-backup.tgz -C /data

For databases, stop writes first or use the database’s own tool, such as pg_dump for PostgreSQL. Copying the raw files of a running database can give you a broken backup.

Q71. How do you share a volume between two containers?

Mount the same named volume into both containers. Both see the same files, so one can write and the other can read.

docker volume create shared-logs
docker run -d --name app -v shared-logs:/var/log/app shop-api:1.4.0
docker run -d --name shipper -v shared-logs:/logs:ro log-shipper:2.0

Here the log shipper mounts the volume read-only, so it cannot change the app’s files. Be careful when two containers write to the same files at once, because Docker does not lock files for you.

Q72. What is the writable container layer, and why should you avoid writing a lot to it?

The writable layer is the top layer that each container gets on top of its image. Any file the app creates or changes goes there. It uses a copy-on-write storage driver, usually overlay2, so the first time a file from the image is changed, the whole file is copied up into the writable layer.

So writing a lot there is slow, especially for big files, and it fills the host disk under Docker’s folder. The data is also lost when the container is removed. So write logs to stdout, and put heavy or important data in volumes or tmpfs.

Q73. How do you run a database like PostgreSQL in Docker without losing data?

Store the database files in a named volume mounted at the database’s data folder. Then you can stop, remove and recreate the container, and the data stays.

docker volume create pgdata
docker run -d --name db \
  -e POSTGRES_PASSWORD=change-me \
  -v pgdata:/var/lib/postgresql/data \
  -p 127.0.0.1:5432:5432 \
  postgres:17

Also, pin a major version tag such as postgres:17, because a newer major version cannot read old data files without an upgrade. Take regular backups with pg_dump. For production, many teams use a managed database instead, so backups and failover are handled for them.

Q74. How do you list and remove unused volumes?

Use the docker volume commands. Volumes are never removed automatically, because Docker does not want to delete your data by accident.

docker volume ls                       # list volumes
docker volume ls -f dangling=true      # volumes not used by any container
docker volume inspect pgdata           # where it lives and its labels
docker volume rm pgdata                # remove one volume
docker volume prune                    # remove unused anonymous volumes
docker volume prune -a                 # remove all unused volumes, named ones too

Always check before pruning on a server, because a removed volume cannot be recovered.

Q75. What does read-only mode (:ro) do for a mount?

Adding :ro (or readonly with --mount) makes the mount read-only inside the container. The app can read the files but not change or delete them.

docker run -d -v "$PWD/config.yaml":/etc/app/config.yaml:ro shop-api:1.4.0

It is a good safety habit for config files, certificates and shared data the container only needs to read. Even if the app has a bug or is attacked, it cannot change those files.

Docker Compose Interview Questions with Answers

Most teams run their local stack with Compose, so expect a few Docker interview questions about it, even for junior roles. A full example Compose file is in the hands-on section below.

Q76. What is Docker Compose, and when do you use it?

Docker Compose is a tool to define and run many containers together from one YAML file, usually compose.yaml. The file lists your services, their images or build folders, ports, environment variables, networks and volumes. Then one command starts the whole stack.

docker compose up -d      # start everything in the background
docker compose ps         # see the services
docker compose logs -f api
docker compose down       # stop and remove containers and the network

You use it for local development, automated tests in CI, demos and small single-server deployments. For example, one file can start your Go API, PostgreSQL, Redis and a mail testing tool, so a new developer is ready in minutes.

Q77. What is the difference between docker compose and the old docker-compose command?

docker-compose (with a hyphen) was Compose V1, a separate tool written in Python. docker compose (with a space) is Compose V2, written in Go and built into the Docker CLI as a plugin. Compose V1 stopped getting updates in 2023, so always use docker compose.

V2 is faster, supports newer features like profiles, watch and better build support, and follows the open Compose Specification. Also, the top-level version: key in the file is now obsolete, so you can leave it out.

Q78. What are services, networks and volumes in a compose.yaml file?

These are the three main top-level sections of a Compose file.

  • services: each service is one container (or several replicas), such as api, db or cache. You set its image or build, ports, environment and dependencies.
  • networks: the networks services join. If you do not define any, Compose creates one default network for the project, and every service can reach the others by service name.
  • volumes: named volumes for data that must survive, such as database files. Services mount them by name.
services:
  api:
    build: .
    networks: [backend]
  db:
    image: postgres:17
    volumes:
      - pgdata:/var/lib/postgresql/data
    networks: [backend]
networks:
  backend:
volumes:
  pgdata:

Q79. What does depends_on do, and why does it not wait for an app to be ready?

depends_on controls start and stop order. If api depends on db, Compose starts db first and stops it last. However, by default it only waits until the db container has started, not until PostgreSQL inside it is ready for connections, which can take several seconds.

So your API might start, try to connect and fail. There are two fixes. Add a healthcheck to the database and use condition: service_healthy, as the next answer shows. Also, write your app to retry its connections with a short backoff, because in production a dependency can restart at any time.

Q80. How do you make one service wait until another is healthy?

Give the dependency a healthcheck, then use the long form of depends_on with condition: service_healthy. Compose then waits until the healthcheck passes before it starts the dependent service.

services:
  api:
    build: .
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: change-me
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 10

Another condition, service_completed_successfully, is useful for one-time jobs such as running database migrations before the API starts.

Q81. How do you pass environment variables and .env files to Compose?

There are three common ways, and they do slightly different jobs.

MethodWhat it does
environment: in a serviceSets variables inside that container
env_file: in a serviceLoads variables for that container from a file
.env file next to compose.yamlFills ${VAR} placeholders inside the Compose file itself
services:
  api:
    image: shop-api:${API_VERSION:-latest}   # from .env, with a default
    environment:
      LOG_LEVEL: info
    env_file:
      - api.env

Keep real secrets out of Git, so add .env and api.env to .gitignore. Compose also supports secrets:, which mounts secret values as files under /run/secrets.

Q82. How do you scale a service in Compose?

Use the --scale flag, or set deploy.replicas in the file. Compose starts several containers of the same service, and the service name in DNS returns all of their IPs.

docker compose up -d --scale worker=4

You cannot scale a service that publishes a fixed host port, such as "8080:8080", because only one container can use that host port. So scale background workers freely, and for web services put a load balancer like nginx or Traefik in front.

Q83. What are Compose profiles?

Profiles let you mark some services as optional. A service with a profile only starts when you turn that profile on. Services without a profile always start.

services:
  api:
    build: .
  db:
    image: postgres:17
  adminer:
    image: adminer
    profiles: ["debug"]   # only with --profile debug
docker compose up -d                   # api and db
docker compose --profile debug up -d   # api, db and adminer

So one file can hold your normal stack plus extra tools for debugging, testing or monitoring.

Q84. How do you rebuild and restart only one service?

Name the service at the end of the command. Compose then rebuilds and recreates only that one, and leaves the others running.

docker compose up -d --build api     # rebuild the image and recreate api
docker compose restart api           # restart without rebuilding
docker compose up -d --no-deps api   # do not touch its dependencies

For fast local development, docker compose watch can also sync file changes into a running container or rebuild it automatically when you save a file.

Q85. Is Docker Compose a good choice for production?

It depends on the size of the system. Compose works well in production for small apps on one server, such as an internal tool, a small website or a side project. It is simple, and with restart policies and healthchecks it is quite reliable.

However, Compose runs on one host. It has no built-in failover across machines, no rolling updates across a cluster, no autoscaling and limited secret management. So for systems that need high availability or many servers, teams use an orchestrator such as Kubernetes or a managed service like AWS ECS. A common pattern is Compose for development and Kubernetes for production.

Security Docker Interview Questions with Answers

Security is where senior candidates stand out. So prepare these Docker interview questions with real examples, and always mention “least privilege”: give a container only what it needs.

Q86. Why should containers not run as root?

By default, the process in a container runs as root (user ID 0). Root inside a container is limited, but it is still the same user ID as root on the host. If an attacker breaks into your app and then finds a kernel bug or a bad setting, such as a mounted host folder, root makes it much easier to damage the host.

So run as a normal user. Add a USER line in the Dockerfile, use a nonroot base image, or pass --user 10001:10001 on docker run. In Kubernetes, set runAsNonRoot: true in the security context.

Q87. What is rootless Docker mode?

In rootless mode, the Docker daemon itself and all containers run as a normal, non-root user on the host. It uses user namespaces, so “root” inside a container maps to an unprivileged user outside.

So even if an attacker escapes a container, they only get the rights of a normal user, not root on the host. There are some limits, such as publishing ports below 1024 needs extra setup, and some storage and network features work differently. Podman also runs rootless by default.

Q88. What are Linux capabilities, and how do you drop them?

Linux splits root’s powers into small pieces called capabilities, such as NET_BIND_SERVICE (use ports below 1024), NET_ADMIN (change network settings) and SYS_ADMIN (many admin actions). Docker gives containers a reduced default set, but you can remove even more.

The safest pattern is to drop all capabilities, then add back only what the app needs.

docker run -d --cap-drop ALL --cap-add NET_BIND_SERVICE -p 80:80 web:1.0

Most Go web services need no capabilities at all, especially when they listen on a port above 1024 such as 8080.

Q89. What does –privileged do, and why is it dangerous?

--privileged gives a container almost all the powers of the host. It gets every capability, access to all host devices, and most security filters such as seccomp and AppArmor are turned off. In practice, a privileged container can easily take over the host.

So never use it for normal apps. It is only for special cases such as running Docker inside Docker or low-level system tools. Even then, prefer giving only the exact capability or device needed with --cap-add or --device.

Q90. Why is mounting the Docker socket into a container risky?

Mounting /var/run/docker.sock lets the container talk to the Docker daemon. With that, it can start a new privileged container that mounts the host’s root folder, which means full control of the host. So the socket is as powerful as root access.

Tools like CI runners, monitoring agents and reverse proxies sometimes ask for it. Avoid it where you can. Use a rootless or remote builder for CI, use a socket proxy that allows only read-only API calls, and never mount the socket into internet-facing apps.

Q91. How do you scan an image for known vulnerabilities?

An image scanner reads the packages inside an image and checks them against databases of known security issues (CVEs). Popular tools are Docker Scout, Trivy and Grype, and most cloud registries can scan images on push.

docker scout cves shop-api:1.4.0
trivy image shop-api:1.4.0

Run scans in CI and fail the build for critical issues that have a fix. Then fix them by updating the base image and dependencies. Small base images like distroless have far fewer packages, so they show far fewer issues to begin with. For Go code, also run govulncheck, which only reports issues in code your program really calls.

Q92. How do you keep secrets out of images and environment variables?

Never put secrets in the Dockerfile with ENV, ARG or COPY, because they stay in the image layers and history, and anyone who pulls the image can read them. Also, add .env and key files to .dockerignore.

  • At build time: use BuildKit secret mounts (RUN --mount=type=secret) or SSH mounts.
  • At run time: mount secrets as files from a secret store, such as Docker or Compose secrets, Kubernetes Secrets, AWS Secrets Manager or Vault.

Environment variables are better than baking secrets in, but they can leak through docker inspect, crash reports and child processes. So mounted files with tight permissions are safer for passwords and keys.

Q93. What is a read-only root file system, and how do you enable it?

With a read-only root file system, the container cannot change any file in its image. If an attacker gets in, they cannot drop new tools or change your binary. Use --read-only, and add a tmpfs for folders the app must write to.

docker run -d --read-only --tmpfs /tmp shop-api:1.4.0

In Kubernetes, the same setting is readOnlyRootFilesystem: true. It works very well with Go apps, which usually write nothing to disk except temp files.

Q94. What are image signing and provenance, and why do they matter?

Image signing adds a cryptographic signature to an image, so you can check it really came from your team and was not changed. Sigstore Cosign is the most common tool today. Provenance is a signed record of how the image was built: which source commit, which builder and which steps. An SBOM (software bill of materials) lists every package inside the image.

They matter because of supply chain attacks, where an attacker swaps or changes an image in a registry. BuildKit can add provenance and SBOM attestations with docker buildx build --provenance=true --sbom=true, and Kubernetes admission controllers can refuse images that are not signed.

Q95. How do seccomp and AppArmor profiles protect containers?

Seccomp filters which system calls (requests to the kernel) a container can make. Docker’s default seccomp profile blocks dozens of risky calls, such as loading kernel modules or changing the system clock. AppArmor (on Ubuntu and Debian) and SELinux (on Red Hat systems) control which files and resources a process can access.

Docker turns on the default seccomp profile and, where available, a default AppArmor profile automatically. You can apply stricter custom profiles for sensitive apps. So never disable them with --security-opt seccomp=unconfined unless you have a clear reason.

Advanced and Scenario Docker Interview Questions with Answers

Senior rounds turn these ideas into real problems. For each scenario, explain what you would check first, and why, because interviewers care about your steps as much as the answer.

Q96. A container exits right after it starts. How do you find out why?

Follow these steps in order.

  1. First, read the logs with docker logs <name>. Most crashes print an error, such as a missing config value or a failed database connection.
  2. Next, check the exit code and details with docker inspect --format '{{.State.ExitCode}} {{.State.Error}}' <name>.
  3. Then check what command actually ran with docker inspect --format '{{.Config.Entrypoint}} {{.Config.Cmd}}' <name>.
  4. If needed, start the image with a shell instead of the app: docker run -it --entrypoint sh <image>, and run the command by hand.

Common causes are a wrong CMD or ENTRYPOINT, a missing environment variable, a binary built for the wrong CPU (exec format error), a missing file or library, or a process that runs in the background and leaves PID 1 with nothing to do.

Q97. Your image is 1.2 GB. How do you bring it under 50 MB?

First, look at where the size comes from with docker history or the dive tool. Usually the base image, build tools and caches take most of the space. Then apply these steps.

  1. Use a multi-stage build, so the compiler and source code stay in the build stage.
  2. Copy only the final binary or build output into the last stage.
  3. Use a small runtime base, such as distroless, Alpine or scratch.
  4. Add a .dockerignore file so .git, node_modules and test data are not copied.
  5. Remove package caches in the same RUN line, and skip recommended packages.

For a Go service, a static binary in distroless/static or scratch usually ends up between 10 and 30 MB. For Node.js or Python, a slim base plus production-only dependencies often gets close to the target.

Q98. A build is slow because the cache breaks every time. What do you check?

The cache breaks from the first instruction whose input changed, so find that line. Run the build with --progress=plain and look for the first step that is not CACHED.

Then check these common causes.

  • COPY . . comes before the dependency download, so any code change re-downloads everything.
  • There is no .dockerignore, so changing files like .git or logs changes the build context.
  • A build argument with a changing value, such as a timestamp or commit ID, is used early.
  • RUN apt-get update uses a base image tag that moves, such as latest.
  • In CI, every job starts on a fresh machine with no cache. Use --cache-from and --cache-to with a registry or the CI cache.

Also, use BuildKit cache mounts for package managers, so even rebuilt layers reuse downloads.

Q99. Two containers cannot talk to each other. How do you debug it?

Go from the network to the app, one step at a time.

  1. First, check they are on the same user-defined network: docker network inspect <network>. Containers on the default bridge cannot use names.
  2. Next, check the name resolves. From one container, run nslookup db or getent hosts db, or use a debug container such as nicolaka/netshoot.
  3. Then check the port is open: nc -zv db 5432.
  4. Check the app listens on 0.0.0.0, not 127.0.0.1. An app bound to localhost inside its container cannot be reached from other containers.
  5. Finally, check you use the container port, not the published host port, and look for firewall rules or a wrong host name in the config.

The 127.0.0.1 mistake is the most common one in interviews and in real life.

Q100. A container uses too much memory and gets killed. How do you set and check limits?

First, confirm it was killed for memory. docker inspect --format '{{.State.OOMKilled}}' <name> shows true, and the exit code is usually 137. Then watch live usage with docker stats.

Set a limit with --memory, so one container cannot take memory from the others.

docker run -d --memory 512m --memory-swap 512m shop-api:1.4.0

Then find the real cause. The app might have a leak, a cache with no size limit, or a runtime that does not know about the container limit. For Go, set GOMEMLIMIT a little below the container limit, such as GOMEMLIMIT=450MiB, so the garbage collector works harder before the kernel kills the process. Use pprof to find the leak.

Q101. What does exit code 137 mean, and what does exit code 143 mean?

When a process is ended by a signal, the exit code is 128 plus the signal number. So the code tells you which signal stopped it.

Exit codeSignalUsual meaning
0NoneFinished normally
1NoneApp error, check the logs
137SIGKILL (9)Killed: out of memory, or docker kill, or stop timeout
139SIGSEGV (11)Crash from bad memory access
143SIGTERM (15)Asked to stop, normal for docker stop

So 143 is usually fine, while 137 needs checking. Look at OOMKilled first, then at how long the app takes to shut down.

Q102. How do you set CPU and memory limits on a container?

Use flags on docker run, or the deploy.resources section in Compose.

# 512 MB memory, 1.5 CPU cores, at most 200 processes
docker run -d --memory 512m --cpus 1.5 --pids-limit 200 shop-api:1.4.0
services:
  api:
    image: shop-api:1.4.0
    deploy:
      resources:
        limits:
          cpus: "1.5"
          memory: 512M

A memory limit is hard: going over it gets the process killed. A CPU limit only slows the container down (throttling). Since Go 1.25, the Go runtime reads the container CPU limit and sets GOMAXPROCS to match, which avoids heavy throttling.

Q103. How do you collect logs from many containers in production?

First, make every app log to stdout and stderr, ideally as JSON with fields like level, request ID and service name. Docker captures this through a logging driver. The default json-file driver writes to files on the host, so turn on log rotation, or the disk will fill up.

{
  "log-driver": "json-file",
  "log-opts": { "max-size": "10m", "max-file": "3" }
}

Then ship the logs to a central system. You can use a logging driver such as fluentd, gelf or awslogs, or run an agent such as Fluent Bit, Vector or Grafana Alloy that reads the log files. Store and search them in Loki, Elasticsearch or a cloud service like CloudWatch.

Q104. How would you update a running service with zero downtime?

On a single host with plain Docker, you start the new version next to the old one, check it is healthy, switch traffic, then stop the old one.

  1. Build and push a new image with a new version tag.
  2. Start a new container from it on the same network, without stopping the old one.
  3. Wait until its healthcheck passes.
  4. Point the reverse proxy (nginx, Traefik or Caddy) at the new container and reload it.
  5. Stop the old container gracefully with docker stop, so it finishes in-flight requests.

The app must handle SIGTERM and finish requests before exiting. In real production, an orchestrator such as Kubernetes or ECS does these rolling updates for you, using readiness probes.

Q105. How do you copy files in and out of a running container?

Use docker cp. It works in both directions and also works with stopped containers.

docker cp api:/app/logs/error.log ./error.log    # container to host
docker cp ./config.yaml api:/etc/app/config.yaml  # host to container

It is handy for debugging, such as pulling out a crash dump or a profile. However, do not use it to deploy or change apps. Files copied into a container are lost when it is recreated, so build them into the image or mount them instead.

Q106. Your app works locally but fails inside Docker with a time zone or TLS error. Why?

Small base images, such as scratch and some distroless or Alpine images, may not include two things your laptop has: time zone data and CA certificates.

  • Time zone error: the app cannot load a zone like Asia/Kolkata, because /usr/share/zoneinfo is missing. In Go, add import _ "time/tzdata" or build with -tags timetzdata to embed the data in the binary, or install the tzdata package.
  • TLS error: HTTPS calls fail with “certificate signed by unknown authority”, because /etc/ssl/certs is missing. Copy the CA certificates from the build stage, or use a base image such as distroless/static that already includes them.
FROM scratch
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=build /app /app
ENTRYPOINT ["/app"]

Q107. How do you debug a container image that has no shell, such as distroless?

You cannot docker exec into it, because there is no shell. Instead, start a separate debug container that shares the target’s namespaces, so you can see its processes and network with your own tools.

# Share the network and process namespaces of the "api" container
docker run -it --rm \
  --network container:api \
  --pid container:api \
  nicolaka/netshoot

Docker Desktop also has a docker debug command that attaches a toolbox shell to any container. In Kubernetes, use kubectl debug with an ephemeral container. Another option is a :debug image variant, as distroless offers, for testing only.

Q108. How do Docker and Kubernetes work together today?

Docker and Kubernetes do different jobs. Docker is mainly used to build images and run containers on one machine, especially for development and CI. Kubernetes runs containers across a cluster of machines, with scaling, self-healing, rolling updates and service discovery.

The common flow is: developers build an image with Docker, CI pushes it to a registry, and Kubernetes pulls and runs it on its nodes using containerd or CRI-O. Because the image follows the OCI standard, it runs the same everywhere. Our Kubernetes interview questions cover the cluster side in detail.

Q109. Why did Kubernetes remove dockershim, and can you still use Docker images in Kubernetes?

Kubernetes talks to container runtimes through a standard interface called CRI (Container Runtime Interface). Docker Engine was created before CRI and never supported it, so Kubernetes kept an adapter called dockershim. Keeping that extra layer was costly, so it was removed in Kubernetes 1.24.

Yes, you can still use Docker images. They are standard OCI images, so containerd and CRI-O run them without any change. Only clusters that used Docker Engine as the node runtime had to switch, and teams that still need it can use the separate cri-dockerd adapter.

Q110. Docker Swarm or Kubernetes: which would you pick for a new project, and why?

Docker Swarm is Docker’s built-in orchestrator. It is much simpler to learn and set up, uses the same Compose-style files and is fine for small clusters. Kubernetes is more complex, but it has a far larger ecosystem, more features and support from every major cloud as a managed service (EKS, GKE, AKS).

FeatureDocker SwarmKubernetes
Learning curveLowHigh
SetupOne command per nodeMore work, or use a managed service
Ecosystem and toolsSmallVery large
AutoscalingNot built inBuilt in (HPA, cluster autoscaler)
Cloud managed optionsFewEvery major cloud

For most new projects, I would pick a managed Kubernetes service, because of its ecosystem and the skills available in the job market. For a small team running a few services on one or two servers, Docker Compose or Swarm can be enough and much simpler.

Hands-On Docker Interview Questions Practice

Interviewers often ask you to write a Dockerfile on the spot. Here is a clean multi-stage Dockerfile for a small Go web service. It answers questions 26, 27, 35, 38 and 47 in one go.

# Stage 1: build the Go binary with all build tools
FROM golang:1.27 AS build
WORKDIR /src

# Copy dependency files first so this layer stays cached
COPY go.mod go.sum ./
RUN go mod download

# Now copy the rest of the code and build a static binary
COPY . .
RUN CGO_ENABLED=0 go build -o /app ./cmd/api

# Stage 2: tiny runtime image with no shell and a non-root user
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /app /app
EXPOSE 8080
USER nonroot:nonroot
ENTRYPOINT ["/app"]

The first stage downloads modules before copying the code, so code changes do not break the module cache. The second stage keeps only the binary, so the final image is usually under 20 MB. CGO_ENABLED=0 makes a static binary that needs no C libraries.

Next, here is a small Compose file with an API and a PostgreSQL database. It answers questions 78 to 81.

# compose.yaml: run the API and its database together
services:
  api:
    build: .
    ports:
      - "8080:8080"          # host port 8080 -> container port 8080
    environment:
      DATABASE_URL: postgres://app:secret@db:5432/shop?sslmode=disable
    depends_on:
      db:
        condition: service_healthy   # wait until the database is ready
  db:
    image: postgres:17
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: shop
    volumes:
      - dbdata:/var/lib/postgresql/data   # named volume keeps data safe
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d shop"]
      interval: 5s
      retries: 5
volumes:
  dbdata:

The API reaches the database by its service name, db, because Compose puts both services on one network. The healthcheck plus condition: service_healthy fixes the classic depends_on problem from question 79. In real projects, load the password from a secret instead of writing it in the file.

Finally, these are the commands you should be able to type without looking them up.

docker build -t shop-api:1.0 .          # build an image from the Dockerfile
docker images                           # list local images
docker run -d --name api -p 8080:8080 shop-api:1.0   # run in the background
docker ps -a                            # list all containers
docker logs -f api                      # follow the logs
docker exec -it api sh                  # open a shell (if the image has one)
docker inspect api                      # full details, exit code, IPs
docker stats                            # live CPU and memory use
docker compose up -d --build            # start the whole stack
docker system prune                     # remove stopped containers and unused data

Common Mistakes in Docker Interview Questions

  • Mixing up image and container: always say “an image is the template, a container is the running copy”.
  • Saying EXPOSE publishes a port: it does not; only -p or a Compose ports entry does.
  • Forgetting about PID 1: if your app ignores SIGTERM, every stop takes the full timeout.
  • Using latest in production: pin a version tag or a digest so deploys are repeatable.
  • Putting secrets in ENV or ARG: they end up in the image history for anyone to read.

Best Practices for Answering Docker Interview Questions

  • Start with a one-line definition, then add one real example from a project.
  • Draw the flow of Dockerfile, image, registry and container if you have a whiteboard.
  • Mention trade-offs, such as Alpine being small but using musl.
  • Talk about security by default: non-root users, small images and image scanning.
  • Link Docker to Kubernetes, because most teams use both together.

Practice Task

To practise these Docker interview questions, take any small app you have and write a multi-stage Dockerfile for it. Then measure the image size with docker images, add a .dockerignore file and a non-root user, and measure again. Hint: try both a slim base image and distroless, and compare the sizes.

Official Resources

Quick Recap

  • Docker interview questions focus on images, containers, networks, volumes and security.
  • An image is a read-only template, and a container is a running copy of it.
  • Multi-stage builds, small base images and .dockerignore keep images small.
  • Use user-defined networks for name-based DNS, and volumes for data that must survive.
  • Run as non-root, keep secrets out of images, and pin image versions.
  • Every one of the 110 questions now has a full answer, with commands you can try.
  • Practise the hands-on Dockerfile and Compose file, because live tasks are common.

What’s Next?

Containers are only half the story in most interviews. Next, read Kubernetes interview questions, with pods, deployments, services, scaling and real cluster scenarios. For more question lists, browse the Go interview questions hub.