Skip to content
Tutorials Center
My learning

Topics

Lesson 110 of 111 ยท Practice

Docker Interview Questions

Forty Docker interview questions with clear, verified answers on images, containers, Dockerfiles, networking, volumes, Compose and security, plus tips for answering.

Docker interviews follow a pattern. They start with definitions (what is a container?), move to everyday commands and Dockerfile choices, and then probe whether you understand what is underneath: layers, namespaces, signals, networking, and what goes wrong in production. Good candidates answer in three steps: a one-sentence definition, a short explanation of how it works, and an example or a pitfall from experience.

This lesson has 40 questions grouped by topic, with answers short enough to say out loud. Each answer links to the lesson that teaches the topic in depth. Commands and outputs shown here were run on Docker Engine 29 with Compose 5. Read the answers, then close the page and try to explain each one in your own words; that is what the interviewer will ask you to do.

When you do not know an answer, say how you would find out ("I would check docker inspect for the restart count and the exit code"). Showing a debugging method often counts for more than remembering a flag.

The basics

1. What is Docker?

Docker is a platform for building, shipping and running applications in containers. A container packages an application with its dependencies and runs it as an isolated process on a shared kernel. The tool set includes the CLI, the daemon (dockerd), the image format and Docker Hub. See What Is Docker?.

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

An image is a read-only template: layers of files plus metadata (default command, environment, exposed ports). A container is a running (or stopped) instance of an image with a thin writable layer on top. The relationship is like a class and an object, or a program file and a process. You can start many containers from one image. See Understanding Images.

3. How is a container different from a virtual machine?

A VM runs a full guest operating system with its own kernel on virtualized hardware. A container is just a process on the host kernel, isolated with namespaces and limited with cgroups. So containers start in a fraction of a second, use far less memory and disk, but share the host kernel, which means weaker isolation and the need for a matching kernel type (Linux containers need a Linux kernel; Docker Desktop provides one in a small VM).

4. What technologies make containers work?

Linux namespaces give each container its own view of processes (PID), network, mounts, hostnames, users and more. cgroups limit and account for CPU, memory and process counts. A union filesystem (overlay2) stacks image layers. Capabilities, seccomp and AppArmor or SELinux restrict what the process may do. Details in How Docker Works.

5. What are the main components of Docker's architecture?

The client (docker CLI) talks over a REST API to the daemon (dockerd), which manages images, networks and volumes. The daemon delegates running containers to containerd, which uses runc (an OCI runtime) to create them. Registries store images. The CLI and daemon can be on different machines.

6. What happens when you run docker run nginx?

The CLI asks the daemon to create and start a container. If the image is missing locally, the daemon pulls it from the registry (Docker Hub by default) as layers. It then creates a writable layer, sets up namespaces, a network interface and any mounts, and starts the image's default command. The container stays alive as long as that process runs. See Your First Container.

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

A registry is a server that stores and distributes images. Docker Hub is the default public one. Others include GitHub Container Registry, cloud providers' registries and self-hosted ones. Images are named registry/namespace/name:tag; with no registry the name means Docker Hub. See Tags and Registries.

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

docker stop sends SIGTERM, waits (10 seconds by default), then sends SIGKILL. docker kill sends SIGKILL right away (or any signal you pick with -s). A program that ignores SIGTERM, such as sleep as PID 1, ends with exit code 137 either way:

CONSOLE
$ docker run -d --name s1 alpine sleep 300
$ docker stop s1
s1
$ docker inspect -f '{{.State.ExitCode}}' s1
137

A program that handles SIGTERM and exits cleanly returns its own code (often 0 or 143). See Signals, PID 1 and --init.

9. How do you see running and stopped containers?

docker ps lists running containers, docker ps -a lists all including exited ones. Useful filters are --filter name=web and --filter status=exited, and --format customizes the columns. See Listing and Inspecting.

10. How do you get a shell in a running container?

docker exec -it <name> sh (or bash if the image has it) starts a new process in the container's namespaces. docker attach instead connects you to the main process's streams, so pressing Ctrl+C might stop the container. Neither works on a stopped container. See Logs and exec.

Images and Dockerfiles

11. What is a Docker layer?

Each filesystem-changing instruction (RUN, COPY, ADD) creates a layer, which is a set of file changes identified by a content hash. Layers are read-only and shared between images, so ten images based on the same base store the base once. docker history shows them:

CONSOLE
$ docker history myimage --format '{{.CreatedBy}}'
CMD ["world"]
ENTRYPOINT ["echo" "hello"]
CMD ["/bin/sh"]
ADD alpine-minirootfs-3.24.3-x86_64.tar.gz /โ€ฆ

Instructions like CMD and ENTRYPOINT only change metadata (they appear in history but add no file data). See Layers and the Union Filesystem.

12. What is the build cache, and how do you use it well?

Docker reuses a layer when the instruction and everything before it are unchanged (for COPY, the content of the copied files counts). Once one layer changes, all later layers rebuild. So order instructions from least to most frequently changing: base image, system packages, dependency manifest, dependency install, then your source. See The Build Cache.

13. What is the difference between CMD and ENTRYPOINT?

ENTRYPOINT defines the executable that always runs; CMD supplies default arguments (or the default command if there is no entrypoint). Arguments after the image name replace CMD, and --entrypoint replaces the entrypoint. With this Dockerfile:

DOCKERFILE
FROM alpine
ENTRYPOINT ["echo", "hello"]
CMD ["world"]
CONSOLE
$ docker run --rm demo
hello world
$ docker run --rm demo there
hello there
$ docker run --rm --entrypoint echo demo bye
bye

See CMD and ENTRYPOINT.

14. What is the difference between shell form and exec form?

Exec form is a JSON array (CMD ["node", "server.js"]): the program is started directly and becomes PID 1, so it receives signals. Shell form (CMD node server.js) runs /bin/sh -c "...", so the shell is PID 1 and may not forward SIGTERM, which causes slow, forced shutdowns. Prefer exec form for CMD and ENTRYPOINT.

15. What is the difference between COPY and ADD?

Both copy files from the build context into the image. ADD also extracts local tar archives and can fetch URLs, which makes its behavior less predictable. Prefer COPY for plain copying, and use ADD only when you want the archive extraction. See COPY and ADD.

16. What is the difference between ENV and ARG?

ARG exists only at build time (set with --build-arg). ENV is stored in the image and is visible to the running container. Neither is a safe place for secrets, because both can be read from the image metadata or docker history; use BuildKit secret mounts at build time and runtime secrets at run time. See ENV and ARG.

17. What is a multi-stage build and why use it?

A Dockerfile with several FROM stages. You compile or install tools in a heavy builder stage, then copy only the results into a small final stage with COPY --from=builder. The final image has no compilers or source code, so it is smaller and has less attack surface. See Multi-Stage Builds.

18. What is the build context and what does .dockerignore do?

The context is the set of files the client sends to the builder (the directory argument of docker build). COPY can only read from it. A .dockerignore file excludes paths (.git, node_modules, .env) so builds are faster, caches are not invalidated by irrelevant changes, and secrets are not sent. See Build Context and .dockerignore.

19. How do you reduce an image's size?

Use a small base (-slim, Alpine or distroless), multi-stage builds, combine related RUN steps and remove package caches in the same step, add a .dockerignore, and install only what you need (--no-install-recommends). Remember that deleting a file in a later layer does not shrink the image, because the earlier layer still contains it. See Choosing a Base Image.

20. What is the difference between latest and a version tag?

latest is just a default tag name with no special meaning: it is whatever was last pushed under that name, and it moves. Pin a specific version in production (postgres:17.5) for reproducibility, and for strict immutability pin by digest (image@sha256:...). See Image Tagging Strategy.

Containers and runtime

21. What are the states of a container?

created, running, paused, restarting, exited and dead (plus removing briefly). docker create makes a container without starting it, start/stop toggle running and exited, pause freezes processes using the cgroup freezer, and rm deletes. See The Container Lifecycle.

22. Why does my container exit immediately?

A container lives as long as its main process. If that process finishes, forks into the background, or is a shell with no terminal, the container exits. Check the code and logs: docker ps -a, docker logs, docker inspect -f '{{.State.ExitCode}}'. Run servers in the foreground. See Common Docker Errors.

23. What do exit codes 125, 126, 127 and 137 mean?

125: Docker itself failed (for example a port conflict or name clash). 126: command found but not executable. 127: command not found. 137: killed by SIGKILL (128 + 9), usually the out-of-memory killer or a forced stop. Anything above 128 is 128 plus a signal number.

24. How do you limit a container's resources?

With --memory and --cpus (and --pids-limit), which translate to cgroup settings. If the process exceeds its memory limit, the kernel kills it, and docker inspect shows OOMKilled=true:

CONSOLE
$ docker run --name oom --memory 20m alpine sh -c 'a=x; while true; do a=$a$a; done'
$ docker inspect -f '{{.State.OOMKilled}} {{.State.ExitCode}}' oom
true 137

See Resource Limits.

25. What are restart policies?

no (default), on-failure[:max], always and unless-stopped. They tell the daemon what to do when a container exits or the daemon restarts. on-failure:3 restarts at most three times, so a program that always fails ends after four runs and shows RestartCount 3. Prefer unless-stopped for services, and add health checks so a hung process is noticed. See Running Containers.

26. What does a HEALTHCHECK do?

It periodically runs a command inside the container and marks it healthy or unhealthy based on the exit code (0 healthy, 1 unhealthy). The status shows in docker ps. Plain Docker does not restart unhealthy containers; orchestrators and Compose depends_on: condition: service_healthy use the status. See HEALTHCHECK.

27. What is PID 1 in a container and why does it matter?

The first process of a container's PID namespace. The kernel gives PID 1 special treatment: it ignores signals it has no handler for (so a naive program won't die on SIGTERM), and it must reap orphaned child processes or zombies accumulate. Use exec form, handle SIGTERM, or add --init (a tiny init such as tini).

28. How do you run a container as a non-root user?

Set USER appuser in the Dockerfile (after creating the user and fixing file ownership), or pass -u 1000:1000 at run time. Root inside a container is still root with respect to mounted files and a larger kernel attack surface. A write that the user is not permitted fails normally:

CONSOLE
$ docker run --rm -u 1000 alpine sh -c 'echo x > /etc/f'
sh: can't create /etc/f: Permission denied

See Users and Permissions.

29. Does EXPOSE publish a port?

No. EXPOSE is documentation (metadata). Only -p host:container or -P (publish all exposed ports to random host ports) makes a port reachable from the host:

CONSOLE
$ docker run -d --name e1 myimage
$ docker port e1
$ docker run -d --name e2 -P myimage
$ docker port e2
80/tcp -> 0.0.0.0:49153

The first docker port prints nothing, the second shows the random host port Docker chose (the number varies). See Port Publishing.

30. How do you debug a container that will not start?

Read docker logs, check docker inspect for exit code, OOMKilled and the effective command, and use docker events to see the sequence. Override the entrypoint to get a shell (docker run --rm -it --entrypoint sh image) and run the command by hand. See Debugging Containers.

Data and networking

31. How does Docker persist data?

Container filesystems vanish when the container is removed. For persistence use volumes (managed by Docker, best for databases), bind mounts (a host path, best for development) or tmpfs (memory, for temporary or sensitive data). See Container Storage.

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

A volume lives in Docker's storage area, has a name, is portable, can use drivers, and is initialized from image content on first use. A bind mount maps an exact host path, depends on the host layout, and exposes host permissions. Use volumes for data you care about and bind mounts to share source code with a container during development. See Volumes and Bind Mounts.

33. How do you back up a volume?

Mount the volume read-only in a helper container together with a host folder, and archive it: docker run --rm -v data:/src:ro -v "$PWD":/backup alpine tar czf /backup/data.tgz -C /src .. For databases, prefer the database's own dump tool. See Backup and Restore.

34. Which network drivers exist?

bridge (the default, a private network on one host), host (shares the host's network stack), none (no networking), overlay (multi-host, used by Swarm) and macvlan (container gets its own MAC address on the physical network). See Network Drivers.

35. How do containers find each other?

On a user-defined bridge network Docker provides DNS: a container can reach another by its name or service alias. The default bridge has no name resolution (only legacy --link, which prints a deprecation warning). So create a network and attach both containers. Inside a container, localhost always means that container. See User-Defined Bridges.

Docker Compose

36. What is Docker Compose?

A tool (now docker compose, a CLI plugin) that describes a multi-container application in one compose.yaml file: services, networks, volumes, environment, health checks and dependencies. docker compose up -d creates it all, down removes it. Compose creates a default network and gives each service a DNS name. See Introduction to Compose.

37. How do you control startup order in Compose?

depends_on orders start-up, but by default waits only for the other container to start, not to be ready. Combine it with a health check and condition: service_healthy so the dependent service waits until the database accepts connections. See depends_on and Health.

38. How do you manage configuration per environment in Compose?

Use .env files and ${VAR} interpolation, env_file, and override files merged with -f compose.yaml -f compose.prod.yaml (or a profile). A missing variable only warns and becomes an empty string unless you write ${VAR:?message}. Validate the result with docker compose config. See Multiple Compose Files.

Security and production

39. How would you secure a container image and its runtime?

Use a minimal, trusted, pinned base image; scan images for known vulnerabilities; run as a non-root user with a read-only root filesystem; drop capabilities you do not need and keep the default seccomp profile; never put secrets in images or ENV; do not expose the Docker socket; and keep Docker and base images updated. See Docker Security Checklist and Secrets Management.

40. When would you use Compose, Swarm or Kubernetes?

Compose on a single host for small projects and development; Swarm for a simple multi-host cluster by a small team that knows Compose; Kubernetes for large, multi-team setups that need its ecosystem. Managed container services and serverless containers can remove the orchestration work altogether. See Choosing Your Deployment Path.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In an interview you are asked whether EXPOSE 8080 in a Dockerfile makes the app reachable from the host. What is the correct answer?

    EXPOSE records metadata. -p host:container or -P is what publishes ports to the host.
  2. 2. Which option best describes the difference between a container and a VM?

    Containers use namespaces and cgroups on the host kernel, so they are light and start quickly; a VM adds a guest kernel and virtual hardware.
  3. 3. With ENTRYPOINT ["echo", "hello"] and CMD ["world"], what does docker run image there print?

    Arguments after the image name replace CMD but are appended to the ENTRYPOINT, so the command is echo hello there.
  4. 4. A container ends with exit code 137 and OOMKilled is true. What happened?

    137 is 128 + 9 (SIGKILL), and OOMKilled=true confirms the memory limit as the reason.
  5. 5. Why is deleting a large file in a later RUN step not enough to shrink an image?

    A later layer only hides the file. The data stays in the layer that added it, so clean up within the same instruction or copy only the results into a fresh stage.

Summary

  • Answer in three steps: define the concept, explain how it works, then give an example or a pitfall.
  • Know the model: images are layered read-only templates, containers are isolated processes with a writable layer, and namespaces and cgroups do the isolating.
  • Be exact about Dockerfile behavior: cache order, CMD versus ENTRYPOINT, exec versus shell form, COPY versus ADD, ENV versus ARG, and that EXPOSE does not publish.
  • Remember the exit codes (125, 126, 127, 137) and what each says about the cause.
  • Choose storage deliberately: volumes for data, bind mounts for development, tmpfs for temporary memory-backed files.
  • Containers find each other by name only on user-defined networks, and localhost is always the container itself.
  • Describe security as layers: minimal pinned images, non-root, fewer capabilities, no secrets in images, no exposed socket.
  • Be ready to compare Compose, Swarm, Kubernetes and managed options by operating effort rather than by features.

That completes the Docker track. For a quick reference to keep open while you work, use the Docker Cheat Sheet, and revisit Common Docker Errors whenever something fails.