Skip to content
System Design

Docker interview questions and answers

55 questions, 55 with code. About 3 h 40 min to read them all.

By TestLab · Updated

Plan for an interview
55 questions

Track what you know and what to revise.

Sign in to track progress

You can open a few full answers without signing in. Sign in to read all

1

What is Docker, and how is it different from virtual machines?

Docker is a platform for building, sharing and running applications in containers. A container packages an application with its libraries and runtime, and runs as an isolated process on the host’s kernel. Isolation comes from Linux namespaces (process, network, mount, user and others), resource limits from cgroups, and the file system from a layered image. A virtual machine emulates a whole computer: a hypervisor runs separate guest operating systems, each with its own kernel. As a result, containers are much lighter: they start in milliseconds to seconds, use megabytes rather than gigabytes, and many can share one host. VMs give stronger isolation and can run different operating systems and kernels. In practice the two are combined: containers usually run inside VMs in the cloud.

Read full answer

Applies toDocker Engine 27+ on Linux; Docker Desktop on macOS and Windows

Architecture

Containers                              Virtual machines
+---------+---------+---------+         +-----------+-----------+
| App A   | App B   | App C   |         | App A     | App B     |
| libs    | libs    | libs    |         | libs      | libs      |
+---------+---------+---------+         | guest OS  | guest OS  |
| container runtime (Docker)  |         | (kernel)  | (kernel)  |
+-----------------------------+         +-----------+-----------+
| host OS kernel (shared)     |         | hypervisor            |
+-----------------------------+         +-----------------------+
| hardware                    |         | hardware              |
+-----------------------------+         +-----------------------+

Comparison

Aspect Docker containers Virtual machines
Isolation Process level: namespaces, cgroups, seccomp, capabilities Hardware level: separate kernels
Kernel Shared with the host Each VM has its own
Start-up time Milliseconds to seconds Tens of seconds to minutes
Size Megabytes (image layers shared) Gigabytes (a full OS per VM)
Density Dozens to hundreds per host Fewer per host
Operating systems Same kernel family as the host (Linux containers on Linux) Any guest OS
Security boundary Weaker; a kernel exploit can affect the host Stronger
Portability Image runs anywhere with a compatible runtime and CPU architecture VM images are larger and more hypervisor-specific
Typical use Microservices, CI, reproducible development environments Full OS isolation, different OSes, legacy apps, multi-tenant hosting

Docker’s Main Components

Component Role
Docker CLI docker build, docker run, docker compose
Docker Engine (dockerd) API server that manages images, containers, networks and volumes
containerd and runc Lower-level runtime that actually creates containers (OCI runtime spec)
BuildKit The image builder: caching, multi-stage builds, multi-platform builds
Registries Store and distribute images (Docker Hub, GHCR, ECR, Artifact Registry, Harbor)

Quick Example

docker run --rm -d --name web -p 8080:80 nginx:1.27
docker ps                                  # the container is just a process with its own view
docker exec web cat /etc/os-release        # the image's userland (Debian)...
docker exec web uname -r                   # ...but the host's kernel version
docker stop web

Docker on macOS and Windows

Linux containers need a Linux kernel, so Docker Desktop runs a lightweight Linux VM (or WSL 2 on Windows) and the containers run inside it. Windows also has native Windows containers.

Stronger Isolation Options

When containers need VM-like isolation, for example for untrusted multi-tenant code, there are gVisor (a user-space kernel), Kata Containers and Firecracker microVMs. They combine container workflows with a VM-style boundary.

Pitfalls

  • Treating containers as tiny VMs: SSH servers, several processes, manual changes inside.

  • Assuming containers are a strong security boundary by default; harden them (non-root, dropped capabilities, seccomp).

  • Expecting a Linux image to run on any CPU: build multi-platform images for amd64 and arm64.

Interview Tips

  • Say “containers share the host kernel; VMs virtualise hardware and run their own kernels”.

  • Mention namespaces and cgroups.

  • Compare start-up, size, density and isolation, and note that containers often run inside VMs.

2

What is a Docker image?

A Docker image is a read-only, layered template for creating containers. It contains: - a filesystem: the base OS userland, the language runtime, libraries and the application; - configuration metadata: the default command (ENTRYPOINT/CMD), environment variables, working directory, user and exposed ports.

Each Dockerfile instruction that changes files adds a layer: a set of filesystem differences, identified by a content hash. Layers are shared between images and cached during builds. An image is referred to by a name and tag (nginx:1.27) or, immutably, by a digest (nginx@sha256:...). Images follow the OCI image specification, so any compliant runtime and registry can use them. A container is a running instance of an image with a thin writable layer on top.

Read full answer

Applies toDocker Engine 27+, BuildKit, OCI image spec 1.1

What an Image Is Made Of

Part Content
Layers Compressed tar archives of filesystem changes, each with a digest
Image config JSON: default command, entrypoint, environment, user, working directory, labels, layer list
Manifest Links the config and layers for one platform (for example linux/amd64)
Image index (manifest list) For multi-platform images: points to one manifest per OS and architecture

Building and Inspecting an Image

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
USER 10001
CMD ["python", "-m", "app"]
docker build -t ghcr.io/example/api:1.4.0 .
docker image ls ghcr.io/example/api
docker history ghcr.io/example/api:1.4.0      # one line per layer and its size
docker image inspect ghcr.io/example/api:1.4.0 --format '{{json .Config.Cmd}}'
docker push ghcr.io/example/api:1.4.0

Tags Versus Digests

Reference Example Property
Tag python:3.12-slim Mutable: can be moved to a newer build
Digest python@sha256:... Immutable: always exactly the same content

Use tags for humans and digests for deployments that must be reproducible.

Image Versus Container

Image Container
Read-only template Running (or stopped) instance
Stored in registries and the local image store Exists on a host
Layers shared by many containers Adds its own writable layer, lost when the container is removed
Built with docker build Created with docker run or docker create

Good Images

  • Small base images (slim, Alpine, distroless) and multi-stage builds.

  • One concern per image; configuration from the environment at run time.

  • No secrets in any layer: a file deleted in a later layer is still in the earlier one.

  • Labels for source, version and licence (org.opencontainers.image.*).

  • Multi-platform builds (docker buildx build --platform linux/amd64,linux/arm64).

Pitfalls

  • Relying on latest, which changes unpredictably.

  • Large images full of build tools and caches.

  • Secrets baked into layers.

Interview Tips

  • Define an image as layers plus configuration, read-only, identified by digest.

  • Explain tags versus digests and image versus container.

  • Mention the OCI standard and multi-platform images.

3

How does a Docker container differ from a Docker image?

An image is a static, read-only package: layered files plus configuration, stored in a registry or on a host. A container is a running (or stopped) instance of an image. Docker adds a thin writable layer on top of the image’s read-only layers, plus runtime state: isolated processes in namespaces, cgroup resource limits, a network interface and IP address, mounted volumes, and environment overrides. The usual analogy is a class and its objects, or a program file and a running process. One image can start many containers, which share its layers. Changes a container makes to its filesystem stay in its own writable layer and disappear when the container is removed, unless they go to a volume.

Read full answer

Applies toDocker Engine 27+ (overlay2 storage driver)

Comparison

Aspect Image Container
Nature Template, an artifact Instance with processes and state
Mutability Read-only, identified by digest Writable layer on top (copy-on-write)
Lifecycle Built, tagged, pushed, pulled, deleted Created, started, paused, stopped, restarted, removed
Storage Shared read-only layers Per-container writable layer
Runtime resources None CPU and memory limits, network, mounts, PID namespace
Commands docker build, pull, push, image ls, rmi docker run, ps, exec, logs, stop, rm
Count One image Many containers from the same image

Seeing the Difference

docker pull nginx:1.27                       # one image
docker run -d --name a nginx:1.27            # two containers from it
docker run -d --name b nginx:1.27
docker exec a sh -c 'echo changed > /usr/share/nginx/html/index.html'
docker exec b cat /usr/share/nginx/html/index.html   # still the original page
docker diff a                                # shows the changed file in a's writable layer
docker rm -f a b                             # the change is gone; the image is unchanged

Copy-on-Write

The storage driver (overlay2 on Linux) presents the image layers and the container layer as one merged filesystem. When a container modifies a file from the image, the file is copied up into the writable layer first, so other containers using the same image are unaffected. That is why starting a container is fast and cheap: nothing is copied until it is written.

Container Lifecycle States

created --start--> running --stop--> exited --start--> running
   |                  |  \--pause--> paused --unpause--/
   +------ rm --------+--------- rm (after stop, or -f) ---> removed

Persisting Data

Need Use
Data that outlives the container Named volumes (-v pgdata:/var/lib/postgresql/data)
Sharing host files during development Bind mounts (-v "$PWD":/app)
Temporary, in-memory data tmpfs mounts
A new image from a changed container docker commit (rarely; prefer a Dockerfile)

Pitfalls

  • Storing important data in the container’s writable layer, lost on docker rm or redeploy.

  • Fixing problems inside running containers instead of rebuilding the image, so the fix is lost.

  • Confusing stopped containers with removed ones: stopped containers still use disk space (docker container prune).

Interview Tips

  • Use the class versus object analogy.

  • Explain the writable layer, copy-on-write and shared image layers.

  • Mention volumes for persistent data and the container lifecycle.

4

What is the Docker Hub, and what is it used for?

Docker Hub is Docker’s public container registry, and the default registry the Docker CLI uses: docker pull nginx means docker.io/library/nginx:latest. It is used to: - find and pull base images, especially Docker Official Images (nginx, postgres, python, node) and Verified Publisher images from vendors; - publish and share images, publicly or in private repositories; - automate image workflows with webhooks, vulnerability insights from Docker Scout, and automated builds on paid plans.

Organisations often combine Docker Hub with other registries: GitHub Container Registry, Amazon ECR, Google Artifact Registry, Azure Container Registry, or a self-hosted Harbor. They also often use pull-through caches to avoid Docker Hub’s pull rate limits.

Read full answer

Applies toDocker Hub (docker.io) and the Docker CLI

Image Naming

docker.io / library / nginx : 1.27
registry    namespace  repo   tag

nginx:1.27                   -> docker.io/library/nginx:1.27   (official image)
bitnami/redis:7.4            -> docker.io/bitnami/redis:7.4    (publisher namespace)
ghcr.io/example/api:1.4.0    -> another registry (GitHub Container Registry)

Common Commands

docker login                                   # use an access token, not your password
docker search postgres
docker pull postgres:17
docker tag myapp:dev example/myapp:1.0.0
docker push example/myapp:1.0.0
docker logout

Content Types on Docker Hub

Type Description Trust level
Docker Official Images Curated base images maintained with upstream projects High; regularly rebuilt and scanned
Verified Publisher Images from verified commercial vendors High
Docker-Sponsored Open Source Images from sponsored open-source projects Medium to high
Community images Anyone can publish Check them carefully before use

Using Docker Hub Well

Practice Why
Prefer official or verified images as bases Maintained, patched, documented
Pin versions, or digests in production latest changes unexpectedly
Authenticate pulls in CI Higher rate limits than anonymous pulls
Mirror or cache images A pull-through cache (Harbor, ECR pull-through, Artifact Registry remote repos) keeps builds working if Docker Hub is slow or limited
Use access tokens with limited scope Safer than passwords; revocable
Scan images Docker Scout, Trivy or Grype before use

Docker Hub Versus Private Registries

Need Choice
Open-source distribution Docker Hub public repositories (or GHCR)
Images close to cloud workloads, with IAM integration ECR, Artifact Registry, ACR
Images next to source code GitHub Container Registry, GitLab registry
Self-hosted, air-gapped or with replication Harbor

Pitfalls

  • Pulling unverified community images that may contain malware or crypto-miners.

  • Hitting rate limits in CI because of anonymous pulls.

  • Pushing secrets inside images to public repositories.

  • Depending on one external registry for production deployments, without a mirror.

Interview Tips

  • Define Docker Hub as the default public registry for pulling and pushing images.

  • Mention Official Images, Verified Publishers, private repositories and rate limits.

  • Name alternatives and pull-through caching.

5

Explain the Dockerfile and its significance in Docker.

A Dockerfile is a text file of instructions that tells Docker, via the BuildKit builder, how to build an image step by step: - which base image to start from (FROM); - which files to copy in (COPY); - which commands to run at build time (RUN); - how to configure the container (ENV, WORKDIR, USER, EXPOSE); - what to execute when it starts (ENTRYPOINT, CMD).

Its significance is that it makes images reproducible, versioned and reviewable. The build environment is code stored in Git next to the application, so any developer or CI system can rebuild the same image. Each instruction that changes files creates a cached layer, so the order of instructions decides how fast rebuilds are.

Read full answer

Applies toDockerfile syntax 1.x with BuildKit (Docker Engine 23+)

Example: Node.js Service

# syntax=docker/dockerfile:1
FROM node:22-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev

FROM node:22-slim
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --chown=node:node . .
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s CMD node healthcheck.js
CMD ["node", "server.js"]
docker build -t example/web:2.1.0 .
docker run --rm -p 3000:3000 example/web:2.1.0

Main Instructions

Instruction Purpose
FROM Base image; several FROMs make a multi-stage build
WORKDIR Working directory for later instructions and the container
COPY / ADD Add files from the build context (prefer COPY)
RUN Run a command at build time and save the result as a layer
ENV / ARG Environment variables at run time / build-time variables
USER User for later instructions and the running container
EXPOSE Documents the listening port (does not publish it)
ENTRYPOINT / CMD The executable / default arguments or command
HEALTHCHECK Command Docker uses to check container health
LABEL Metadata (org.opencontainers.image.source, version)
VOLUME Declares a mount point for persistent data

Why Order Matters: Layer Caching

Docker reuses a cached layer if the instruction and its inputs have not changed. Once one layer changes, every later layer is rebuilt. So copy the dependency manifest and install dependencies before copying the source. A source change then skips the slow npm ci.

ENTRYPOINT Versus CMD

Form Behaviour
CMD ["node", "server.js"] Default command; docker run image other-cmd replaces it
ENTRYPOINT ["python", "-m", "tool"] + CMD ["--help"] Fixed executable; CMD supplies default arguments that docker run arguments replace
Exec form (JSON array) The process runs as PID 1 and receives signals such as SIGTERM
Shell form (CMD node server.js) Runs under /bin/sh -c; signals may not reach the app

Best Practices

  • Pin base images (node:22-slim, or a digest) and rebuild regularly.

  • Multi-stage builds keep compilers out of the final image.

  • Combine related commands in one RUN, and clean package caches in the same step.

  • Use .dockerignore to keep .git, node_modules and secrets out of the build context.

  • Run as non-root.

  • Pass secrets with RUN --mount=type=secret, never ARG or ENV.

  • Lint with Hadolint.

Pitfalls

  • Copying the whole source before installing dependencies, so every change reinstalls everything.

  • Shell-form CMD that breaks graceful shutdown.

  • apt-get update in a separate layer from apt-get install, which leaves stale package lists cached.

Interview Tips

  • Describe the Dockerfile as infrastructure as code for images.

  • Explain the main instructions, layer caching and multi-stage builds.

  • Mention ENTRYPOINT versus CMD and exec form.

6

How does Docker use layers to build images?

A Docker image is a stack of read-only layers. Each Dockerfile instruction that changes the filesystem (RUN, COPY, ADD) produces one new layer: a tar archive of the files added, changed or deleted compared with the layer below. Deleted files are recorded as whiteout markers. Instructions such as ENV, CMD, EXPOSE and LABEL only change the image configuration. Each layer is content-addressed by a SHA-256 digest, so identical layers are stored and downloaded once and shared between images. During builds, BuildKit caches layers: if an instruction and its inputs are unchanged, the cached layer is reused, and everything after the first changed instruction is rebuilt. At run time, a union filesystem (overlay2) stacks the layers into one view and adds a writable container layer on top, using copy-on-write.

Read full answer

Applies toDocker Engine 27+ with BuildKit and the overlay2 storage driver

Layers From a Dockerfile

FROM python:3.12-slim                  # base image layers (shared with every image using it)
WORKDIR /app                           # small layer (creates the directory)
COPY requirements.txt .                # layer: one file
RUN pip install --no-cache-dir -r requirements.txt   # layer: installed packages (large)
COPY . .                               # layer: application source
CMD ["python", "-m", "app"]            # configuration only, no layer
docker history example/app:1.0         # lists layers with the instruction and size
docker image inspect example/app:1.0 --format '{{json .RootFS.Layers}}'

How the Build Cache Decides

Instruction Cache key includes
RUN The command string and the parent layer (not the network content it fetches)
COPY / ADD Checksums of the copied files and the parent layer
FROM The resolved base image digest

With the order above, editing application code invalidates only the final COPY . . layer, so dependencies are not reinstalled. Copying all the source before pip install would make every code change reinstall everything.

Because RUN caching ignores what the command downloads, RUN apt-get update can stay cached and stale. Combine it with apt-get install in the same RUN, or rebuild with --no-cache or --pull on a schedule.

Layers at Run Time

container writable layer   (copy-on-write: changed files are copied up here)
---------------------------
layer 5: COPY . .
layer 4: pip install ...
layer 3: COPY requirements.txt
layer 2: WORKDIR /app
layer 1..n: python:3.12-slim base layers

overlay2 merges these directories into one root filesystem. Many containers can share the same lower layers, and each has its own thin writable layer.

Why Deleting Files Does Not Shrink Images

RUN curl -fsSLo /tmp/big.tar.gz https://example.com/big.tar.gz
RUN tar -xzf /tmp/big.tar.gz -C /opt && rm /tmp/big.tar.gz     # the archive stays in the previous layer

The archive is still stored in the first RUN layer; the second only adds a whiteout marker. Download, extract and delete in one RUN, or use a multi-stage build and copy only the result.

Benefits

Benefit Explanation
Faster builds Unchanged steps are reused
Smaller transfers Pulls and pushes skip layers the other side already has
Disk efficiency Shared base layers stored once
Fast container start No copying; just a new writable layer

Advanced Cache Features

  • Cache mounts (RUN --mount=type=cache,target=/root/.cache/pip) keep package caches between builds without putting them in layers.

  • Remote cache for CI (--cache-to and --cache-from with a registry or GitHub Actions cache).

  • COPY --link makes copied layers independent of earlier layers, so they can be reused when the base changes.

Pitfalls

  • Poor instruction order, which breaks caching.

  • Secrets copied in, then deleted: they remain in an earlier layer.

  • Too many tiny layers or one huge layer; group related changes sensibly.

Interview Tips

  • Explain one layer per filesystem-changing instruction, content-addressing and sharing.

  • Describe cache invalidation: everything after the first change is rebuilt.

  • Mention overlay2, copy-on-write and why deleting in a later layer does not shrink the image.

7

What’s the difference between the COPY and ADD commands in a Dockerfile?

Both instructions add files to an image, but COPY does only one thing: it copies files and directories from the build context, or from another build stage with --from, into the image. ADD does that and more: - It automatically extracts local tar archives (gzip, bzip2 and xz compressed) into the destination. - It can download from remote URLs. Downloaded files are not extracted. - It can clone Git repositories with recent Dockerfile syntax.

Because ADD‘s extra behaviour is implicit and easy to trigger by accident, the official best practice is to use COPY by default. Use ADD only when you deliberately want local archive extraction, or a remote or Git source, ideally with --checksum to verify downloads.

Read full answer

Applies toDockerfile syntax 1.x with BuildKit

Comparison

Feature COPY ADD
Files from the build context Yes Yes
From another stage (--from=build) Yes No
Auto-extracts local .tar, .tar.gz, .tar.bz2, .tar.xz No (copies the archive as is) Yes
Remote URL source No Yes (downloaded, not extracted)
Git repository source No Yes (recent syntax)
Checksum verification Not needed --checksum=sha256:... for HTTP and Git sources
--chown, --chmod, --link, --exclude Yes Yes
Predictability High Lower (behaviour depends on the source type)

Examples

# syntax=docker/dockerfile:1
FROM alpine:3.20

# Copy files: the normal case
COPY app/ /opt/app/
COPY --chown=10001:10001 config.yaml /etc/app/config.yaml

# Copy a build result from another stage (COPY only)
# COPY --from=build /out/server /usr/local/bin/server

# Extract a local archive (ADD's useful special case)
ADD vendor-sdk.tar.gz /opt/sdk/

# Download with integrity verification
ADD --checksum=sha256:24454f830cdb571e2c4ad15481119c43b3cafd48dd869a9b2945d1036d1dc68d \
    https://example.com/tool-1.2.0.tar.gz /tmp/tool.tar.gz

The checksum in the last example is a placeholder; use the real SHA-256 of the file you download.

Why COPY Is Preferred

  • Explicit: a file named .tar.gz that should stay compressed will not be unpacked unexpectedly.

  • Easier to review and cache: inputs are local files with known checksums.

  • Safer: remote downloads without verification can introduce tampered content.

For remote files, many teams use RUN curl ... && verify && extract && clean up in a single layer, or ADD --checksum, so downloads are verified and temporary files do not remain in a layer.

Pitfalls

  • Using ADD for ordinary files and being surprised when an archive is extracted.

  • ADD <url> without --checksum, which makes builds non-reproducible and less secure.

  • Expecting ADD to extract downloaded archives: only local archives are extracted.

  • Copying the whole context (COPY . .) without a .dockerignore, bringing in secrets and .git.

Interview Tips

  • Summarise: COPY copies; ADD also extracts local tar files and fetches URLs or Git.

  • State the best practice: prefer COPY.

  • Mention COPY --from for multi-stage builds and ADD --checksum for verified downloads.

8

What’s the purpose of the .dockerignore file?

When you run docker build, the builder receives a build context: the files in the directory you pass (usually .). The .dockerignore file lists patterns of files and directories to exclude from that context. Docker never sends them to the builder, so COPY . . cannot include them. This: - speeds up builds, because less data is transferred and hashed; - prevents cache invalidation from irrelevant changes, such as .git or editor files; - keeps images smaller; - keeps secrets out of images: .env files, credentials, private keys.

It uses glob-style patterns similar to .gitignore, with ** for any depth and ! for exceptions.

Read full answer

Applies toDocker Engine 27+ with BuildKit

Example

# Version control and tooling
.git
.gitignore
.github
.vscode
.idea

# Dependencies and build output (rebuilt inside the image)
node_modules
dist
coverage
**/__pycache__
**/*.pyc

# Secrets and local configuration
.env
.env.*
!.env.example
*.pem
*.key
secrets/

# Docker files themselves (optional)
Dockerfile*
docker-compose*.yml

# Logs and OS files
*.log
.DS_Store

!.env.example re-includes the example file after .env.* excluded it. Later lines override earlier ones.

Pattern Rules

Pattern Matches
node_modules node_modules at the root of the context
**/node_modules node_modules at any depth
*.log .log files at the root
*/.log .log files anywhere
!keep.log Re-include a file excluded by an earlier rule
docs/*.md Markdown files directly in docs

Patterns are relative to the root of the context. Unlike .gitignore, a bare name such as node_modules matches only at the root; use **/ for nested directories.

Why It Matters

Without .dockerignore With it
Hundreds of MB of node_modules or .git sent on every build Small context; faster builds
Every Git commit changes .git, invalidating COPY . . Cache stays valid when only ignored files change
.env with database passwords copied into a layer and pushed Secrets never reach the builder
Host-built node_modules for macOS copied into a Linux image Dependencies installed cleanly inside the image

Related Features

  • Per-Dockerfile ignore files: with BuildKit, Dockerfile.dockerignore or api.Dockerfile.dockerignore next to the Dockerfile overrides the root .dockerignore, which helps monorepos.

  • COPY --exclude (recent Dockerfile syntax) excludes paths for one instruction.

  • Build secrets (RUN --mount=type=secret) are the right way to use credentials during a build.

Checking What Is Sent

The build output shows the size of the context transferred (transferring context: 2.1MB). A large number points to a missing ignore rule.

Pitfalls

  • Forgetting **/ for nested directories.

  • Excluding files the build needs (for example the lock file), which causes confusing COPY errors.

  • Relying on .dockerignore alone for secrets: also avoid keeping secrets in the repository.

Interview Tips

  • Explain build context first, then what .dockerignore removes from it.

  • Give the benefits: speed, cache stability, smaller images and security.

  • Mention ! exceptions and ** patterns.

9

How would you go about creating a Docker image from an existing container?

Use docker commit. It takes a container’s writable layer, meaning every change made inside it since it started, and saves it as a new image layer on top of the original image. Options let you add a message, an author, and configuration changes such as CMD, ENV or EXPOSE (--change). The result can be tagged and pushed like any other image. Commit is useful for debugging, preserving the state of a broken container for analysis, or quick experiments. For anything you will maintain, write a Dockerfile instead: committed images are not reproducible, hide how they were built, and tend to collect junk. A related pair, docker export and docker import, produces a flattened image with no history and no metadata.

Read full answer

Applies toDocker Engine 27+

Step by Step

# 1. Start a container from a base image and change it
docker run -it --name work ubuntu:24.04 bash
#   (inside) apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
#   (inside) exit

# 2. See what changed in the container's writable layer
docker diff work            # A = added, C = changed, D = deleted paths

# 3. Commit it as a new image, setting the default command
docker commit \
  --author "Platform Team" \
  --message "ubuntu with curl" \
  --change 'CMD ["curl", "--version"]' \
  work example/ubuntu-curl:0.1

# 4. Use it, and inspect how it was made
docker run --rm example/ubuntu-curl:0.1
docker history example/ubuntu-curl:0.1
docker push example/ubuntu-curl:0.1      # after tagging for your registry and logging in

By default docker commit pauses the container while committing, for consistency (--pause=false disables this).

What Is and Is Not Included

Included Not included
Files changed in the container’s filesystem Data in volumes and bind mounts
Configuration changes passed with --change Running processes and memory state
The original image’s layers (shared) Network settings, port mappings, resource limits from docker run

Commit Versus Export/Import Versus Dockerfile

Method Result Use
docker commit New layer on top of the image, metadata kept Debugging, snapshots, experiments
docker export + docker import Single flattened layer; history and metadata such as CMD, ENV lost Moving a filesystem, flattening
docker save + docker load Saves images (all layers and tags) as a tar Moving images without a registry
Dockerfile Reproducible, reviewable build Everything you maintain

Turning the Experiment Into a Dockerfile

FROM ubuntu:24.04
RUN apt-get update \
 && apt-get install -y --no-install-recommends curl ca-certificates \
 && rm -rf /var/lib/apt/lists/*
CMD ["curl", "--version"]

This produces the same result, but anyone can rebuild it, CI can rebuild it when the base image is patched, and the change is visible in code review.

Pitfalls

  • Committing secrets: shell history, credentials or tokens in the container end up in the image.

  • Bloated images full of caches and temporary files.

  • “Snowflake” images that nobody can rebuild when a security patch is needed.

  • Expecting volume data to be in the committed image.

Interview Tips

  • Name docker commit with --change and docker diff.

  • Explain why a Dockerfile is preferred for real images.

  • Contrast commit, export/import and save/load.

10

In practice, how do you reduce the size of Docker images?

Smaller images pull faster, start faster, cost less to store and have fewer vulnerabilities. The biggest wins, roughly in order: 1. Use multi-stage builds. Compile in a full builder image, then copy only the artifacts into a minimal runtime image. 2. Choose a small base image: -slim, Alpine, distroless or scratch for static binaries. 3. Install only what runs: no build tools, docs or dev dependencies (--no-install-recommends, npm ci --omit=dev). 4. Clean up in the same layer that created the files: package lists and caches. Files deleted in a later layer still take space. 5. Keep the build context small with .dockerignore, and copy only the needed files. 6. Measure with docker history, docker image ls or dive, to see which layers are large.

Read full answer

Applies toDocker Engine 27+ with BuildKit

Example: From 1.1 GB to About 20 MB (Go Service)

# Before: one stage, full toolchain in the final image (roughly 1 GB+)
# FROM golang:1.23
# COPY . .
# RUN go build -o /app/server ./cmd/server
# CMD ["/app/server"]

# After: multi-stage, static binary on a distroless base
# syntax=docker/dockerfile:1
FROM golang:1.23 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
RUN --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/server /server
ENTRYPOINT ["/server"]

The final image holds the binary plus a few megabytes of base files. The exact size depends on the program.

Techniques by Language

Ecosystem Techniques
Go, Rust Static binaries; scratch or distroless static; strip symbols
Python python:3.12-slim; pip install --no-cache-dir; build wheels in a builder stage; copy only the virtual environment
Node.js node:22-slim or Alpine; npm ci --omit=dev; copy built dist and production node_modules only
Java Run on a JRE, not a JDK (for example eclipse-temurin:21-jre); jlink custom runtimes; layered jars
Debian or Ubuntu packages apt-get install --no-install-recommends ... && rm -rf /var/lib/apt/lists/* in one RUN
Alpine packages apk add --no-cache

Layer Hygiene

# Bad: the archive stays in layer 1 even though layer 2 deletes it
RUN curl -fsSLo /tmp/tool.tgz https://example.com/tool.tgz
RUN tar -xzf /tmp/tool.tgz -C /usr/local && rm /tmp/tool.tgz

# Good: download, extract and delete in one layer
RUN curl -fsSL https://example.com/tool.tgz | tar -xz -C /usr/local

Use cache mounts (RUN --mount=type=cache,...) for package manager caches. They speed up builds without ending up in the image.

Measuring

docker image ls example/api                 # total size
docker history example/api:1.4.0            # size per layer
dive example/api:1.4.0                      # interactive layer explorer, shows wasted space

Trade-Offs

Choice Watch out for
Alpine (musl libc) Some binaries and Python wheels expect glibc; DNS and performance differences
Distroless or scratch No shell for debugging; use kubectl debug or docker debug with ephemeral containers
Aggressive stripping Harder to debug crashes; keep symbols separately if needed

Pitfalls

  • Squashing layers to hide bloat instead of removing its cause; it also breaks layer sharing.

  • Copying the whole repository into the runtime stage.

  • Leaving dev dependencies and test files in production images.

Interview Tips

  • Lead with multi-stage builds and minimal base images.

  • Explain same-layer cleanup and .dockerignore.

  • Mention measuring with dive and the Alpine and distroless trade-offs.

11

What command is used to run a Docker container from an image?

The command is docker run. It creates and starts a new container from an image in one step: it pulls the image if it is not present locally, creates the container’s writable layer, sets up networking and mounts, then starts the image’s default command, or the command you pass after the image name. Common options: - -d runs it in the background; - -it gives an interactive terminal; - --name names the container; - -p host:container publishes ports; - -e sets environment variables; - -v or --mount attaches volumes; - --rm removes the container when it exits; - --restart sets a restart policy; - --memory and --cpus set resource limits.

docker run is equivalent to docker create followed by docker start.

Read full answer

Applies toDocker Engine 27+ CLI

Syntax and Examples

docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]

# One-off command; container removed afterwards
docker run --rm alpine:3.20 echo "hello"

# Interactive shell
docker run --rm -it ubuntu:24.04 bash

# Background web server on host port 8080
docker run -d --name web -p 8080:80 nginx:1.27

# Database with configuration, a named volume and a restart policy
docker run -d --name db \
  -e POSTGRES_PASSWORD_FILE=/run/secrets/pg \
  -v pgdata:/var/lib/postgresql/data \
  -v "$PWD/pg-password.txt":/run/secrets/pg:ro \
  --restart unless-stopped \
  --memory 1g --cpus 1.5 \
  postgres:17

Frequently Used Options

Option Meaning
-d, --detach Run in the background and print the container ID
-i, -t (-it) Keep STDIN open, allocate a terminal
--rm Delete the container when it stops
--name Fixed name instead of a random one
-p 8080:80 Publish container port 80 on host port 8080 (-P publishes all exposed ports to random ports)
-e KEY=value, --env-file Environment variables
-v name:/path, --mount type=volume,... Volumes and bind mounts
--network Attach to a specific network
--restart no, on-failure, always, unless-stopped Restart policy
--memory, --cpus Resource limits
-u, --user Run as a specific user
--entrypoint Override the image’s ENTRYPOINT
--read-only, --cap-drop ALL Hardening options

Related Commands

Command Purpose
docker create then docker start Two-step version of run
docker ps / docker ps -a List running / all containers
docker logs -f web Follow the container’s output
docker exec -it web sh Run a command in a running container
docker stop web / docker rm web Stop (SIGTERM, then SIGKILL after a timeout) / remove
docker compose up Run several containers defined in compose.yaml

Pitfalls

  • Forgetting -d, so the terminal is attached to the container, or forgetting -it for shells.

  • Using docker run repeatedly without --rm, leaving many stopped containers.

  • Arguments in the wrong place: options must come before the image name; anything after it is the container command.

  • Secrets passed with -e, which are visible in docker inspect; prefer files or secret stores.

Interview Tips

  • Answer docker run, and explain that it is create plus start.

  • Mention the key flags: -d, -it, -p, -e, -v, --name, --rm, --restart.

  • Show the syntax order: options, image, then command.

12

What is a Docker namespace and what are its benefits?

Namespaces are a Linux kernel feature that Docker uses to give each container its own isolated view of system resources. Processes in a container see only their own process tree (PID namespace), network stack (NET), filesystem mounts (MNT), hostname (UTS), inter-process communication objects (IPC), cgroup hierarchy (CGROUP) and, optionally, user and group IDs (USER). To the container it looks like a separate machine, while it is really an ordinary process on the shared host kernel. The benefits are isolation (containers cannot see or signal each other’s processes, and each can bind port 80), security (a smaller view of the host, especially with user namespaces mapping container root to an unprivileged host user), portability and efficiency: no separate kernel or VM is needed. Namespaces isolate what a process can see; cgroups limit how much it can use.

Read full answer

Applies toLinux namespaces as used by Docker Engine 27+ (runc)

Namespace Types

Namespace Isolates Effect in a container
PID Process IDs The app is PID 1; host processes are invisible
NET Interfaces, IP addresses, routes, ports, firewall rules Own eth0, IP and port space
MNT Mount points Own root filesystem from the image layers
UTS Hostname and domain name Own hostname (the container ID by default)
IPC Shared memory, semaphores, message queues No shared memory with other containers
USER User and group IDs Container root can map to an unprivileged host UID (when enabled)
CGROUP View of the cgroup hierarchy Sees only its own cgroup tree

Seeing Namespaces in Action

docker run -d --name demo nginx:1.27
docker exec demo sh -c 'echo $$; hostname'      # small PID, container hostname
docker top demo                                  # the same processes, with host PIDs
pid=$(docker inspect -f '{{.State.Pid}}' demo)
sudo ls -l /proc/$pid/ns                         # the namespace handles for that process (Linux host)
docker rm -f demo

Sharing Namespaces on Purpose

Option Effect Use
--network host Uses the host network namespace Maximum network performance; no port isolation
--network container:<name> Shares another container’s network namespace Sidecars (like containers in a Kubernetes pod)
--pid host / --pid container:<name> Shares a PID namespace Debugging and monitoring tools
--ipc host Shares host IPC Some high-performance apps
--userns host Disables user namespace remapping for one container Compatibility

Each of these reduces isolation, so use them deliberately.

User Namespaces for Security

Without user namespaces, root in the container is UID 0 on the host, limited only by dropped capabilities, seccomp and AppArmor or SELinux. Enabling userns-remap in the daemon, or running rootless Docker, maps container UIDs to a high, unprivileged range on the host. A container breakout then has far less power.

Namespaces Versus cgroups

Namespaces cgroups
Limit what a process can see Limit what a process can use (CPU, memory, I/O, PIDs)
Isolation of views Resource accounting and limits
Together with seccomp, capabilities and LSMs (AppArmor, SELinux) They form the container sandbox

Pitfalls

  • Assuming namespaces equal VM isolation: all containers share one kernel, so kernel vulnerabilities matter.

  • Running with --privileged or host namespaces without need.

  • Confusing Docker namespaces with Kubernetes namespaces: Kubernetes namespaces are logical groupings of API objects, not kernel isolation.

Interview Tips

  • List the seven namespace types and what each isolates.

  • Contrast namespaces (visibility) with cgroups (resources).

  • Mention user namespaces and rootless mode for security.

13

What is a Docker volume, and when would you use it?

A Docker volume is persistent storage managed by Docker, stored outside the container’s writable layer (by default under /var/lib/docker/volumes/ on Linux) and mounted into containers at a path. Data in a volume survives container removal and recreation, can be shared between containers, and avoids the copy-on-write overhead of the container layer. Use volumes for anything that must outlive a container: database files, uploaded content, queues, or caches you want to keep. Docker also offers bind mounts, which map a specific host directory and suit development (live code reloading) and host configuration, and tmpfs mounts, which are in memory and suit temporary or sensitive data. Volume drivers let volumes live on NFS, cloud disks or other storage.

Read full answer

Applies toDocker Engine 27+ and Docker Compose v2

Mount Types

Type Data lives Managed by Best for
Named volume Docker’s storage area (or a driver’s backend) Docker Databases, persistent application data
Anonymous volume Same, with a random name Docker Throwaway data declared by VOLUME in images
Bind mount Any host path You Source code in development, host config files, sockets
tmpfs Host memory only Docker Temporary files, secrets that must not touch disk

Commands

docker volume create pgdata
docker run -d --name db \
  -e POSTGRES_PASSWORD=devonly \
  --mount type=volume,source=pgdata,target=/var/lib/postgresql/data \
  postgres:17

docker rm -f db                  # container gone...
docker run -d --name db2 -e POSTGRES_PASSWORD=devonly \
  -v pgdata:/var/lib/postgresql/data postgres:17   # ...data still there

docker volume ls
docker volume inspect pgdata
docker volume prune              # removes unused anonymous volumes (add -a for unused named ones)

-v name:/path and --mount type=volume,source=...,target=... are equivalent. --mount is more explicit and preferred in scripts.

In Compose

services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: devonly
    volumes:
      - pgdata:/var/lib/postgresql/data
  api:
    build: .
    volumes:
      - ./src:/app/src          # bind mount for live reload in development
    tmpfs:
      - /tmp
volumes:
  pgdata: {}

Backing Up and Restoring a Volume

# Backup: mount the volume read-only in a helper container and archive it
docker run --rm -v pgdata:/data:ro -v "$PWD":/backup alpine:3.20 \
  tar czf /backup/pgdata.tgz -C /data .

# Restore into a new volume
docker volume create pgdata-restored
docker run --rm -v pgdata-restored:/data -v "$PWD":/backup alpine:3.20 \
  tar xzf /backup/pgdata.tgz -C /data

For databases, prefer logical dumps (pg_dump) or stop the database first, so the files are consistent.

When to Use What

Situation Choice
Database in local development or a single host Named volume
Live-editing source code Bind mount
Sharing files between two containers Named volume mounted in both
Scratch space or sensitive temporary data tmpfs
Persistent storage across hosts Volume driver (NFS, cloud) or, in Kubernetes, PersistentVolumes

Pitfalls

  • Keeping data in the container layer, lost on docker rm.

  • docker compose down -v or docker volume prune -a deleting data you needed.

  • Permission mismatches: the container user’s UID must be able to write the mounted path.

  • Bind-mounting the Docker socket, which effectively gives the container root on the host.

Interview Tips

  • Define volumes as Docker-managed persistent storage outside the container lifecycle.

  • Compare volumes, bind mounts and tmpfs.

  • Mention backups, sharing and volume drivers.

14

Explain the use and significance of the docker-compose tool.

Docker Compose defines and runs multi-container applications from one YAML file (compose.yaml). The file lists the services, such as the API, database, cache and worker, with their images or build instructions, ports, environment, volumes, networks, dependencies and health checks. One command, docker compose up, creates the networks and volumes and starts everything in the right order. docker compose down stops and removes it all. Its significance is that the whole development environment becomes code: reproducible, versioned in Git, and shareable, so a new developer can run the full stack in minutes. It is also widely used for integration tests in CI, demos and simple single-host deployments. Today it is a Docker CLI plugin (Compose v2, docker compose), replacing the old Python docker-compose binary.

Read full answer

Applies toDocker Compose v2 (Compose Specification)

Example

services:
  api:
    build: ./api
    ports:
      - "8000:8000"
    environment:
      DATABASE_URL: postgres://app:devonly@db:5432/app
      REDIS_URL: redis://cache:6379/0
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_started
    develop:
      watch:
        - action: sync
          path: ./api/src
          target: /app/src
  worker:
    build: ./api
    command: ["python", "-m", "worker"]
    depends_on: [db, cache]
  db:
    image: postgres:17
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: devonly
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 5s
      retries: 10
  cache:
    image: redis:7.4
  mailpit:
    image: axllent/mailpit:latest
    profiles: ["tools"]
volumes:
  pgdata: {}

The top-level version: key is obsolete in the Compose Specification and can be left out.

Everyday Commands

Command Purpose
docker compose up -d Build if needed, create and start everything in the background
docker compose up -d --build api Rebuild and restart one service
docker compose ps / logs -f api Status / follow logs
docker compose exec db psql -U app Run a command in a running service
docker compose run --rm api pytest One-off container (tests, migrations)
docker compose watch Sync or rebuild on file changes (from the develop.watch section)
docker compose --profile tools up Also start optional services
docker compose down / down -v Remove containers and networks / and volumes

What Compose Gives You

Feature Benefit
A project network Services reach each other by service name (db:5432) through Docker’s DNS
Dependency ordering with health conditions The API starts after the database is actually ready
Named volumes Data survives restarts
Override files (compose.override.yaml, -f for several files) Different settings for development, CI and production
.env file and variable interpolation Configurable without editing YAML
Profiles Optional services on demand

Compose Versus Kubernetes

Compose Kubernetes
Single host Cluster of nodes
Simple YAML, fast to start Many object types; steeper learning curve
Basic restart policies Self-healing, autoscaling, rolling updates
Great for development, CI, small deployments Production at scale

Tools such as Kompose convert Compose files into Kubernetes manifests as a starting point.

Pitfalls

  • depends_on without health conditions: the dependency container is started, but not necessarily ready.

  • Committing real secrets in compose.yaml or .env; use Compose secrets or a secret manager.

  • down -v by habit, deleting database volumes.

  • Treating Compose as a production orchestrator for systems that need high availability.

Interview Tips

  • Describe Compose as “the whole multi-container app in one YAML file”.

  • Mention service-name DNS, volumes, health-based depends_on, profiles and override files.

  • Contrast it with Kubernetes for production.

15

Can containers on the same Docker host communicate by default, and how?

Yes. By default, every container that is not given a network joins the default bridge network (bridge, the docker0 interface on Linux). Containers there can reach each other by IP address, because inter-container communication (icc) is enabled by default. However, the default bridge has no automatic DNS for container names (only the legacy --link option). The recommended way is a user-defined bridge network: containers attached to it can reach each other by container name or alias through Docker’s embedded DNS server (127.0.0.11), and they are isolated from containers on other networks. Docker Compose creates such a network for each project automatically, so services talk to each other by service name. Published ports (-p) are only needed for access from the host or outside, not between containers on the same network.

Read full answer

Applies toDocker Engine 27+ on Linux

Default Bridge: IP Only

docker run -d --name a nginx:1.27
docker run --rm busybox:1.37 sh -c "wget -qO- http://a"      # fails: name not resolved
ip=$(docker inspect -f '{{.NetworkSettings.IPAddress}}' a)
docker run --rm busybox:1.37 wget -qO- "http://$ip" | head -n 4  # works: by IP

User-Defined Bridge: Names Work

docker network create appnet
docker run -d --name api --network appnet nginx:1.27
docker run --rm --network appnet busybox:1.37 wget -qO- http://api | head -n 4   # works by name
docker run --rm busybox:1.37 wget -T 3 -qO- http://api   # fails: different network, isolated

Default Versus User-Defined Bridge

Feature Default bridge User-defined bridge
Name resolution No (only legacy --link) Yes, by container name and network aliases
Isolation All unattached containers share it Only containers you attach
Attach or detach while running No (restart needed) Yes (docker network connect and disconnect)
Per-network settings Shared daemon settings Own subnet, gateway, MTU, options
Recommended No, except quick tests Yes

With Docker Compose

services:
  api:
    image: example/api:1.4.0
    environment:
      DB_HOST: db          # the service name is the hostname
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: devonly

Both services join the project’s default network (<project>_default), so api connects to db:5432 with no port publishing.

Other Ways Containers Can Communicate

Method How
Shared network namespace --network container:api: both share localhost
Host network --network host: both use the host’s interfaces and ports (Linux)
Through published ports on the host Works, but is slower and less isolated than a shared network
Shared volumes or Unix sockets File-based communication through a mounted volume

Restricting Communication

  • Put services on separate networks, and attach a container to several networks only where needed (for example the API on frontend and backend, the database only on backend).

  • Use internal: true networks for back-end-only traffic with no external access.

  • Disable icc on a bridge (com.docker.network.bridge.enable_icc=false) for full isolation between containers on that bridge.

Pitfalls

  • Using localhost to reach another container: inside a container, localhost is the container itself.

  • Relying on container IPs, which change when containers are recreated.

  • Publishing database ports to the host just so other containers can reach them.

Interview Tips

  • Answer yes, through the default bridge, by IP.

  • Recommend user-defined networks for DNS by name and isolation, as Compose does.

  • Mention the localhost pitfall and separating networks for security.

16

Describe the different types of networks in Docker.

Docker networking is pluggable through network drivers. The built-in drivers are: - bridge (the default): a private virtual network on one host, with NAT to the outside. User-defined bridges add DNS by container name. - host: the container uses the host’s network stack directly, with no isolation and no port mapping. - none: no networking except loopback. - overlay: a virtual network spanning several Docker hosts, used by Docker Swarm services, with optional encryption. - macvlan: each container gets its own MAC and IP address on the physical LAN, appearing as a separate device. - ipvlan: like macvlan, but containers share the host’s MAC address, in L2 or L3 mode.

Third-party plugins add more. In Kubernetes, networking is provided by CNI plugins instead.

Read full answer

Applies toDocker Engine 27+ on Linux

Driver Comparison

Driver Scope Isolation Container IP Typical use
bridge Single host Isolated network; NAT for outbound; -p for inbound Private subnet (for example 172.18.0.0/16) Default; local development; Compose
host Single host None for networking The host’s IPs Maximum performance; many ports; network tools
none Single host Complete Loopback only Batch jobs that need no network; security
overlay Multiple hosts (Swarm) Isolated across hosts; VXLAN; optional IPsec encryption Virtual subnet across nodes Swarm services; attachable for standalone containers
macvlan Physical LAN Containers appear as LAN devices LAN IPs with unique MACs Legacy apps expecting LAN presence; network appliances
ipvlan Physical LAN Same MAC as the host; L2 or L3 routing LAN or routed IPs Where switches limit MAC addresses; large deployments

Examples

# User-defined bridge with a custom subnet
docker network create --driver bridge --subnet 10.10.0.0/24 appnet

# Host networking (Linux): nginx listens directly on host port 80
docker run -d --network host nginx:1.27

# No network
docker run --rm --network none alpine:3.20 ip addr

# Overlay (needs swarm mode: docker swarm init)
docker network create --driver overlay --attachable --opt encrypted backend

# Macvlan on the LAN interface eth0
docker network create -d macvlan \
  --subnet 192.168.1.0/24 --gateway 192.168.1.1 \
  -o parent=eth0 lan

docker network ls
docker network inspect appnet

How Bridge Networking Works

container eth0 (172.18.0.2) --veth pair--> br-xxxx bridge on the host (172.18.0.1)
                                             | iptables/nftables NAT (masquerade)
                                             v
                                         host eth0 --> internet
inbound: -p 8080:80 adds a DNAT rule from host:8080 to 172.18.0.2:80

Choosing a Network Type

Need Driver
Containers on one host talking by name User-defined bridge
Lowest network overhead or many dynamic ports host
No network access at all none
Containers on several hosts (Swarm) overlay
Containers must look like physical devices on the LAN macvlan or ipvlan

Special Mode: Sharing Another Container’s Network

--network container:<name> joins an existing container’s network namespace. The containers share IP and localhost, like containers in a Kubernetes pod.

Pitfalls

  • Host networking on Docker Desktop behaves differently, because containers run inside a VM; it was historically Linux-only.

  • Macvlan and the host: by default the host cannot talk to its macvlan containers directly without extra configuration.

  • Subnet clashes between Docker networks and corporate or VPN ranges; configure default-address-pools.

  • Overlay without encryption for sensitive traffic between hosts.

Interview Tips

  • List bridge, host, none, overlay, macvlan and ipvlan, with one use case each.

  • Explain the default bridge versus user-defined bridges (DNS and isolation).

  • Mention NAT and port publishing, and that Kubernetes uses CNI.

17

How do you create a Docker network?

Create a network with docker network create, optionally choosing a driver (bridge by default on a single host, overlay for Swarm across hosts, or macvlan and ipvlan for LAN-attached containers) and settings such as subnet, gateway, IP range, MTU, labels, and whether it is internal (no outside access). Then attach containers with --network on docker run, or with docker network connect for running containers. Containers on the same user-defined network reach each other by name through Docker’s embedded DNS. In Docker Compose, networks are declared under a top-level networks: key, and every project gets a default network automatically.

Read full answer

Applies toDocker Engine 27+ and Docker Compose v2

Basic Usage

# Simplest: a user-defined bridge network
docker network create appnet

# With explicit addressing and options
docker network create \
  --driver bridge \
  --subnet 10.20.0.0/24 \
  --gateway 10.20.0.1 \
  --ip-range 10.20.0.128/25 \
  --opt com.docker.network.driver.mtu=1450 \
  --label team=payments \
  appnet2

# Back-end-only network with no route to the outside
docker network create --internal backend

# Run containers on it and talk by name
docker run -d --name db --network appnet -e POSTGRES_PASSWORD=devonly postgres:17
docker run --rm --network appnet postgres:17 pg_isready -h db

# Inspect, list and clean up
docker network ls
docker network inspect appnet --format '{{json .IPAM.Config}}'
docker network rm appnet2
docker network prune            # removes networks no container uses

Useful Options

Option Purpose
--driver, -d bridge (default), overlay, macvlan, ipvlan, or a plugin
--subnet, --gateway, --ip-range Control addressing and avoid clashes with VPN or office ranges
--internal No external connectivity; only containers on the network can talk
--attachable For overlay networks: allow standalone containers, not only Swarm services
--ipv6 Enable IPv6 (with an IPv6 subnet)
--opt Driver options (MTU, bridge name, inter-container communication)
--label Metadata for filtering and automation

In Docker Compose

services:
  web:
    image: nginx:1.27
    networks: [frontend]
    ports:
      - "8080:80"
  api:
    image: example/api:1.4.0
    networks: [frontend, backend]
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: devonly
    networks: [backend]
networks:
  frontend: {}
  backend:
    internal: true
    ipam:
      config:
        - subnet: 10.30.0.0/24

web can reach api, and api can reach db, but web cannot reach db, and the back-end network has no internet access. Compose prefixes network names with the project name (myapp_backend). Use external: true to reuse a network created outside Compose.

Overlay Networks Across Hosts

docker swarm init                                     # on the manager
docker network create -d overlay --attachable --opt encrypted mesh
docker service create --name api --network mesh example/api:1.4.0

Pitfalls

  • Subnet clashes with corporate networks or VPNs: set explicit subnets, or default-address-pools in the daemon configuration.

  • Forgetting that the default bridge has no DNS: create a user-defined network.

  • docker network rm failing because containers are still attached; disconnect or remove them first.

  • Putting everything on one network, losing the isolation that separate networks give.

Interview Tips

  • Show docker network create with a driver and subnet, then --network to attach.

  • Mention name resolution, --internal and overlay for several hosts.

  • Show the Compose networks: equivalent.

18

How could you connect a container to a specific network?

There are two ways: - At creation time, pass --network <name> to docker run or docker create. Add --network-alias for extra DNS names and --ip for a fixed address on a network with a configured subnet. - For a running container, use docker network connect <network> <container>, which adds another interface without restarting it. docker network disconnect removes it.

A container can belong to several networks at once, one interface on each, which is how you let a service bridge a front-end and a back-end network. In Docker Compose, list the networks under each service’s networks: key. Aliases and static IPs can be set per network there too.

Read full answer

Applies toDocker Engine 27+ and Docker Compose v2

At Creation Time

docker network create appnet --subnet 10.40.0.0/24

docker run -d --name api \
  --network appnet \
  --network-alias api.internal \
  --ip 10.40.0.10 \
  example/api:1.4.0

Docker Engine 25 and later accept --network several times on docker run, attaching the container to all those networks at start-up.

For a Running Container

docker network create backend
docker network connect backend api                            # second interface
docker network connect --alias api-backend backend api        # (alternative, with an alias)
docker inspect -f '{{json .NetworkSettings.Networks}}' api    # shows both networks
docker network disconnect appnet api                          # leave a network

The container keeps running; a new interface such as eth1 appears for each extra network.

In Docker Compose

services:
  api:
    image: example/api:1.4.0
    networks:
      frontend:
        aliases: ["api.internal"]
      backend:
        ipv4_address: 10.50.0.10
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: devonly
    networks: [backend]
networks:
  frontend: {}
  backend:
    ipam:
      config:
        - subnet: 10.50.0.0/24

Special Network Modes

Option Effect
--network host Use the host’s network stack (cannot be combined with other networks)
--network none No networking
--network container:<name> Share another container’s network namespace

Checking Connectivity

docker network inspect backend --format '{{range .Containers}}{{.Name}} {{.IPv4Address}}{{"\n"}}{{end}}'
docker exec api getent hosts db          # DNS resolution from inside, if the image has getent

Pitfalls

  • The default bridge network does not support aliases or DNS by name; use user-defined networks.

  • Static IPs only work on networks created with an explicit subnet, and they can clash on recreation; prefer DNS names.

  • Joining every network “to make it work”, which removes isolation.

  • Expecting docker network connect to work with host or none mode containers: they cannot join other networks.

Interview Tips

  • Give --network at run time and docker network connect for running containers.

  • Mention several networks per container, aliases and Compose networks:.

  • Note the special modes and the default bridge’s limitations.

19

How does Docker’s default bridge network differ from a user-defined bridge network?

Both use the same bridge driver: a virtual Linux bridge on one host, with NAT for outbound traffic. They differ in features and isolation. The default bridge (bridge, the docker0 interface) is used by every container started without --network. It offers no automatic DNS, so containers reach each other only by IP or through the legacy, deprecated --link. All unattached containers share it, so there is no isolation between unrelated apps. Containers cannot be attached or detached while running, and its settings are daemon-wide. A user-defined bridge, created with docker network create, provides: - DNS resolution by container name and alias; - isolation: only the containers you attach; - hot attach and detach; - per-network configuration: subnet, MTU, internal, IPv6.

Docker recommends user-defined bridges for anything beyond quick tests, and Compose uses them automatically.

Read full answer

Applies toDocker Engine 27+ on Linux

Comparison

Feature Default bridge (bridge) User-defined bridge
Created by Docker, automatically You (docker network create) or Compose
Name resolution None (only /etc/hosts entries via --link) Embedded DNS (127.0.0.11) by name and alias
Isolation Every unattached container shares it Only attached containers; separate apps stay apart
Attach or detach while running Not possible docker network connect and disconnect
Configuration Daemon-wide (daemon.json: bip, MTU) Per network: subnet, gateway, MTU, --internal, IPv6, labels
Environment variable sharing --link exposed environment variables (legacy) Not shared; use explicit configuration
Recommended for Quick one-off tests Everything else

Demonstration

# Default bridge: names do not resolve
docker run -d --name a1 nginx:1.27
docker run --rm busybox:1.37 nslookup a1          # fails

# User-defined bridge: names resolve
docker network create mynet
docker run -d --name b1 --network mynet nginx:1.27
docker run --rm --network mynet busybox:1.37 nslookup b1   # resolves through 127.0.0.11

# Isolation: a container on the default bridge cannot reach b1
docker run --rm busybox:1.37 wget -T 3 -qO- http://b1      # fails

Why Isolation Matters

default bridge:   [wordpress] [unrelated-db] [test-container]   all can reach each other by IP

user-defined:     blog-net:  [wordpress] [blog-db]
                  shop-net:  [shop-api]  [shop-db]               blog and shop cannot talk

Other Practical Differences

  • Port publishing (-p) works the same on both. It is only needed for access from outside the network.

  • Inter-container communication on the default bridge is controlled by the daemon-wide icc setting. On user-defined bridges it can be set per network (com.docker.network.bridge.enable_icc).

  • --link is legacy and may be removed in future; user-defined networks replace it.

When the Default Bridge Is Acceptable

  • One-off commands, such as docker run --rm alpine ping example.com, that need internet access but no other containers.

  • Quick experiments where you do not care about names or isolation.

Pitfalls

  • Using --link in new setups.

  • Hard-coding IPs on the default bridge; they change between runs.

  • Assuming Compose services are on the default bridge: Compose creates a user-defined <project>_default network.

Interview Tips

  • Name the key differences: DNS by name, isolation, hot connect and per-network configuration.

  • Mention the embedded DNS server at 127.0.0.11 and that --link is legacy.

  • State the recommendation: always use user-defined networks.

20

How would you enable communication between Docker containers on different hosts?

Containers on different hosts are on separate private bridge networks, so they need a way across the physical network. The options are: 1. Publish ports and use host addresses: container A calls hostB:8080, which maps to a container on host B. It is simple and works anywhere, but needs port management and gives no service discovery. 2. An overlay network: with Docker Swarm, docker network create -d overlay builds a VXLAN virtual network spanning the hosts. Containers and services get IPs on it and resolve each other by name, with optional IPsec encryption (--opt encrypted). 3. macvlan or ipvlan: put containers directly on the physical LAN with their own routable IPs. 4. An orchestrator with a CNI (Kubernetes with Cilium, Calico or a cloud CNI), which gives every pod a routable IP across nodes, with Services for discovery. This is the usual production answer. 5. A service mesh or VPN (Tailscale, WireGuard) to connect hosts across sites.

Read full answer

Applies toDocker Engine 27+ (Swarm mode), Kubernetes 1.30+

Option 1: Published Ports

# host B (10.0.1.20)
docker run -d --name api -p 8080:8080 example/api:1.4.0

# host A
docker run --rm -e API_URL=http://10.0.1.20:8080 example/client:2.0.0

Use a DNS name or a load balancer instead of a raw IP, and restrict the port with host firewalls.

Option 2: Swarm Overlay Network

# host A (manager)
docker swarm init --advertise-addr 10.0.1.10
# host B (worker), using the token printed above
docker swarm join --token <worker-token> 10.0.1.10:2377

# on the manager
docker network create -d overlay --attachable --opt encrypted appmesh
docker service create --name api --network appmesh --replicas 2 example/api:1.4.0
docker service create --name web --network appmesh -p 80:8080 example/web:2.0.0

web reaches http://api:8080 wherever the tasks run. Swarm’s internal DNS and virtual IP load-balance across the api replicas.

Required ports between hosts:

Port Purpose
TCP 2377 Swarm cluster management
TCP and UDP 7946 Node discovery (gossip)
UDP 4789 VXLAN overlay data traffic
IP protocol 50 (ESP) Only when overlay encryption is on

Option 3: macvlan or ipvlan

Containers get LAN addresses (for example 192.168.1.50 on host A, 192.168.1.60 on host B) and talk like ordinary machines. This requires LAN IP planning and switch support for several MAC addresses (macvlan).

Option 4: Kubernetes

pod on node A (10.244.1.7) --CNI routing or encapsulation--> pod on node B (10.244.2.9)
service "api" -> stable virtual IP and DNS name api.default.svc.cluster.local

Choosing

Situation Choice
Two or three hosts, simple setup Published ports + DNS, or Swarm overlay
Production microservices Kubernetes (CNI + Services), possibly with a mesh for mTLS
Containers must appear on the LAN macvlan or ipvlan
Hosts in different sites or clouds VPN (WireGuard, Tailscale), mesh federation, or public endpoints with TLS

Pitfalls

  • Unencrypted traffic between hosts over untrusted networks; enable overlay encryption or mTLS.

  • Firewalls blocking the overlay ports (UDP 4789 especially), giving confusing partial connectivity.

  • MTU problems: VXLAN adds about 50 bytes of overhead, so large packets fail unless the MTU is lowered.

  • Exposing internal ports publicly when using published ports.

Interview Tips

  • Explain that bridges are host-local, then give ports, overlay, macvlan and orchestrator/CNI.

  • Name VXLAN and the Swarm ports.

  • Mention encryption and MTU as practical issues.

21

How can resource constraints be applied to containers in Docker?

Docker applies resource limits through Linux cgroups, set with docker run flags (or Compose deploy.resources), and changeable on running containers with docker update: - Memory: --memory (a hard limit; exceeding it triggers the OOM killer), --memory-reservation (a soft limit), --memory-swap, and --oom-score-adj. - CPU: --cpus (for example 1.5 CPUs of time, enforced by CFS quota), --cpu-shares (relative weight under contention), and --cpuset-cpus (pin to specific cores). - Processes: --pids-limit, to stop fork bombs. - Block I/O: --blkio-weight, --device-read-bps and --device-write-bps, and IOPS limits. - Others: --ulimit (open files) and --shm-size.

By default a container has no limits and can use all host resources, so set at least memory and CPU limits in shared environments.

Read full answer

Applies toDocker Engine 27+ on Linux with cgroups v2

Examples

docker run -d --name api \
  --memory 512m \
  --memory-reservation 256m \
  --memory-swap 512m \
  --cpus 1.5 \
  --pids-limit 200 \
  --ulimit nofile=65536:65536 \
  example/api:1.4.0

# Change limits on a running container
docker update --memory 768m --memory-swap 768m --cpus 2 api

# Watch usage against limits
docker stats api --no-stream

Setting --memory-swap equal to --memory disables swap for the container.

Memory Options

Option Meaning
--memory 512m Hard limit; the kernel OOM-kills a process in the container if it is exceeded
--memory-reservation 256m Soft limit, enforced when the host is short of memory
--memory-swap Total of memory plus swap; equal to --memory means no swap; -1 means unlimited swap
--oom-kill-disable Avoid; only with a memory limit, otherwise the host can run out of memory
--shm-size 256m Size of /dev/shm (databases, browsers)

CPU Options

Option Meaning
--cpus 1.5 At most 1.5 CPUs worth of time per scheduling period (quota)
--cpu-shares 512 Relative weight when CPUs are busy (default 1024); no effect when idle
--cpuset-cpus 0,1 Run only on cores 0 and 1
--cpu-period, --cpu-quota Low-level quota settings behind --cpus

In Docker Compose

services:
  api:
    image: example/api:1.4.0
    deploy:
      resources:
        limits:
          cpus: "1.5"
          memory: 512M
          pids: 200
        reservations:
          memory: 256M
    ulimits:
      nofile:
        soft: 65536
        hard: 65536

Compose v2 applies deploy.resources limits with docker compose up, not only in Swarm.

Making Applications Respect Limits

Runtime Note
Java (JDK 10+) Container-aware: sizes the heap from the memory limit; tune with -XX:MaxRAMPercentage
Node.js Recent versions size the heap from the cgroup limit; set --max-old-space-size explicitly if needed
Go Go 1.19+ GOMEMLIMIT for a soft memory limit; Go 1.25+ sets GOMAXPROCS from the CPU limit
Python No automatic limit; watch worker counts (Gunicorn workers × memory per worker)

Diagnosing Limit Problems

docker inspect -f '{{.State.OOMKilled}} {{.State.ExitCode}}' api   # true 137 means OOM-killed
docker stats                                                        # live CPU, memory, PIDs

Exit code 137 (128 + SIGKILL) together with OOMKilled: true means the memory limit was hit. CPU throttling shows up as high latency while the container is at its --cpus limit.

Pitfalls

  • No limits on shared hosts, so one container starves the others.

  • Limits that are too tight, causing OOM kills or heavy throttling.

  • Apps unaware of limits, which size thread pools or heaps from the host’s resources.

  • Disabling the OOM killer.

Interview Tips

  • Say that limits use cgroups, and name --memory, --cpus, --pids-limit.

  • Distinguish hard limits, soft reservations and relative shares.

  • Mention docker update, docker stats, exit code 137 and runtime awareness of limits.

22

What are Docker security profiles, and how do they work?

Docker security profiles are kernel-level policies that restrict what a containerised process may do, adding defence in depth beyond namespaces and cgroups: - seccomp profiles filter the system calls a container can make. Docker’s default profile blocks dozens of dangerous calls, such as kexec_load, mount, reboot and add_key. - AppArmor profiles (on Ubuntu and Debian) restrict file paths, capabilities and network access per program. Docker loads a default profile, docker-default. - SELinux labels (on RHEL, Fedora and CentOS) enforce mandatory access control between containers and the host when SELinux is enabled. - Linux capabilities split root’s powers into units. Docker grants a reduced default set, which you can shrink further with --cap-drop.

Profiles are applied with --security-opt and --cap-drop/--cap-add. The main risk is turning them off, for example with --privileged or seccomp=unconfined.

Read full answer

Applies toDocker Engine 27+ on Linux

The Layers

Mechanism Restricts Default in Docker How to change
seccomp System calls Default profile on (allow list) --security-opt seccomp=profile.json
AppArmor File, mount, network and capability access docker-default profile --security-opt apparmor=my-profile
SELinux Labels on processes and files Used when SELinux is enabled in the daemon --security-opt label=type:...; :z/:Z on bind mounts
Capabilities Root privileges (NET_ADMIN, SYS_ADMIN and others) Reduced default set (for example no SYS_ADMIN) --cap-drop ALL --cap-add NET_BIND_SERVICE
no-new-privileges Gaining privileges through setuid binaries Off --security-opt no-new-privileges

A Hardened Run

docker run -d --name api \
  --user 10001:10001 \
  --read-only --tmpfs /tmp \
  --cap-drop ALL \
  --security-opt no-new-privileges \
  --security-opt seccomp=./seccomp-api.json \
  --security-opt apparmor=docker-default \
  example/api:1.4.0

docker inspect -f '{{.HostConfig.SecurityOpt}} {{.HostConfig.CapDrop}}' api

A Custom seccomp Profile (Fragment)

{
  "defaultAction": "SCMP_ACT_ERRNO",
  "architectures": ["SCMP_ARCH_X86_64", "SCMP_ARCH_AARCH64"],
  "syscalls": [
    {
      "names": ["read", "write", "openat", "close", "fstat", "mmap", "munmap",
                "brk", "rt_sigaction", "rt_sigprocmask", "futex", "epoll_wait",
                "accept4", "socket", "connect", "bind", "listen", "exit_group"],
      "action": "SCMP_ACT_ALLOW"
    }
  ]
}

Any system call not listed returns an error. A real profile needs more calls; build it by starting from Docker’s default profile and removing calls, or by recording what the app uses (for example with strace or tools such as the Security Profiles Operator in Kubernetes), then testing thoroughly.

A Simple AppArmor Profile (Fragment)

#include <tunables/global>
profile api-profile flags=(attach_disconnected,mediate_deleted) {
  #include <abstractions/base>
  network inet tcp,
  /app/** r,
  /tmp/** rw,
  deny /etc/shadow r,
  deny mount,
}

Load it with sudo apparmor_parser -r -W api-profile, then run with --security-opt apparmor=api-profile.

What Disables Protection

Flag Effect
--privileged All capabilities, all devices, no seccomp or AppArmor confinement: effectively root on the host
--security-opt seccomp=unconfined No system call filtering
--cap-add SYS_ADMIN Very broad powers, including mounting
-v /var/run/docker.sock:... Control of the Docker daemon, which means root on the host

In Kubernetes

The same mechanisms appear in securityContext: seccompProfile: RuntimeDefault, capabilities.drop: ["ALL"], allowPrivilegeEscalation: false, AppArmor profiles, and SELinux options. Pod Security Standards (the “restricted” level) enforce them.

Pitfalls

  • Using --privileged to fix a permission error.

  • Over-strict custom profiles that break the app in rare code paths; test them under realistic load.

  • Assuming AppArmor and SELinux are both active: it depends on the host distribution.

Interview Tips

  • Name seccomp (system calls), AppArmor or SELinux (access control), and capabilities.

  • Explain that defaults are on and how --privileged removes them.

  • Mention no-new-privileges, non-root users and read-only filesystems as complements.

23

Explain how you would scan a Docker image for vulnerabilities.

Use an image scanner, such as Trivy, Grype, Docker Scout or Snyk, or the scanning built into registries (ECR, Artifact Registry, Harbor). The scanner: 1. unpacks the image layers; 2. builds an inventory of OS packages (from dpkg, rpm and apk databases) and language dependencies (lock files and installed packages for npm, pip, Maven, Go modules and others), often as an SBOM; 3. matches each package version against vulnerability databases (NVD, distribution security trackers, GitHub advisories, OSV); 4. reports CVEs with severity, affected and fixed versions.

Many scanners also check for secrets, misconfigurations (running as root, for example) and licences. Run it in CI as a gate, for example failing on fixable critical or high issues, in the registry continuously, because new CVEs are published every day, and at admission in Kubernetes. Then fix by updating the base image or dependencies and rebuilding.

Read full answer

Applies toTrivy 0.5x+, Grype, Docker Scout (Docker Desktop and CLI)

Commands

# Trivy: scan an image, show only fixable high and critical issues, fail the build if any
trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 ghcr.io/example/api:1.4.0

# Trivy: also look for embedded secrets and misconfigurations
trivy image --scanners vuln,secret,misconfig ghcr.io/example/api:1.4.0

# Grype, from an SBOM generated by Syft
syft ghcr.io/example/api:1.4.0 -o cyclonedx-json > sbom.json
grype sbom:./sbom.json --fail-on high

# Docker Scout
docker scout cves ghcr.io/example/api:1.4.0
docker scout recommendations ghcr.io/example/api:1.4.0     # suggests better base images

In CI (GitHub Actions Example)

name: build
on: [push]
jobs:
  image:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: docker build -t ghcr.io/example/api:${{ github.sha }} .
      - uses: aquasecurity/trivy-action@0.28.0
        with:
          image-ref: ghcr.io/example/api:${{ github.sha }}
          severity: CRITICAL,HIGH
          ignore-unfixed: true
          exit-code: "1"

Pin actions to a version or commit SHA. Many teams also upload the results as SARIF, so they appear in the repository’s security tab.

Where to Scan

Stage Purpose
Developer machine and IDE Early feedback
CI after build Gate: do not push images with fixable critical issues
Registry, continuously Catch new CVEs in images already published
Admission in Kubernetes Block unscanned or failing images (Kyverno, Gatekeeper, with signed attestations)
Running workloads Inventory of what is deployed and exposed

Handling Results

Step Practice
Prioritise Severity plus exploitability: CISA KEV list, EPSS scores, whether the package is actually used or reachable
Fix Update the base image (often fixes most findings), upgrade dependencies, remove unused packages
Reduce the surface Minimal or distroless bases mean fewer packages and fewer CVEs
Accept or suppress with care .trivyignore or VEX statements, with a reason and an expiry date
Track SLAs For example: critical fixed within 7 days, high within 30

Limits of Scanning

  • It finds known vulnerabilities in recognised packages only; software copied in without package metadata may be missed.

  • Results depend on database freshness.

  • False positives happen, for example when distributions backport fixes without changing the version.

  • It does not replace runtime hardening, signing or secure coding.

Pitfalls

  • Scanning once at build time and never again.

  • Failing builds on unfixable CVEs, so teams start ignoring the scanner.

  • Ignoring language dependencies and scanning only OS packages.

Interview Tips

  • Explain inventory (SBOM) → match against CVE databases → report.

  • Name Trivy, Grype and Docker Scout, and show a CI gate command.

  • Cover continuous rescanning, prioritisation and fixing by rebuilding.

24

What is the purpose of a Docker Healthcheck?

A HEALTHCHECK tells Docker how to test whether the application inside a container is actually working, not just whether its process is running. Docker runs the check command periodically inside the container. Exit code 0 means healthy, 1 means unhealthy. The container’s status moves from starting to healthy, or to unhealthy after a set number of consecutive failures. The purpose is to detect hung or broken apps (a deadlocked server, a lost database connection) and to let tooling react: - docker ps and monitoring show the health status; - Docker Compose depends_on: condition: service_healthy waits for readiness; - Docker Swarm replaces unhealthy tasks.

Plain Docker does not restart unhealthy containers by itself. Kubernetes ignores Dockerfile HEALTHCHECK and uses its own liveness, readiness and startup probes.

Read full answer

Applies toDocker Engine 27+, Docker Compose v2, Swarm mode

In a Dockerfile

FROM python:3.12-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
HEALTHCHECK --interval=30s --timeout=3s --start-period=20s --retries=3 \
  CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=2).status == 200 else 1)"
CMD ["gunicorn", "-b", "0.0.0.0:8000", "app:app"]

Using Python avoids installing curl just for the check. HEALTHCHECK NONE disables a check inherited from the base image.

Options

Option Default Meaning
--interval 30s Time between checks
--timeout 30s A check taking longer counts as a failure
--start-period 0s Grace period at start-up: failures do not count yet (a success marks it healthy)
--start-interval 5s Check interval during the start period (Docker Engine 25+)
--retries 3 Consecutive failures needed for unhealthy

In Docker Compose

services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: devonly
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 10
  api:
    image: example/api:1.4.0
    depends_on:
      db:
        condition: service_healthy

Checking the Status

docker ps                                            # STATUS shows (healthy) or (unhealthy)
docker inspect -f '{{json .State.Health}}' api       # recent results with output and exit codes

Who Reacts to Health

Platform Behaviour on unhealthy
Plain docker run Status only; restart policies react to exits, not to health
Docker Compose Used by depends_on conditions; no automatic restart (some teams add an autoheal sidecar)
Docker Swarm Replaces the unhealthy task
Kubernetes Ignores Dockerfile HEALTHCHECK; define liveness, readiness and startup probes in the pod spec
Amazon ECS Uses container health checks in the task definition

Designing Good Checks

  • Check the app itself, for example a lightweight /health endpoint, cheaply and quickly.

  • Do not check deep dependencies in liveness-style checks; a database outage should not mark every app container unhealthy and trigger restarts everywhere.

  • Use a start period for slow starters.

  • Keep the tools minimal: avoid adding curl and a shell to distroless images; use a small binary or the app’s own CLI.

Pitfalls

  • Expecting Docker to restart unhealthy containers automatically.

  • Heavy checks that add load every few seconds.

  • Timeouts longer than the interval.

  • Relying on HEALTHCHECK in Kubernetes, where it has no effect.

Interview Tips

  • Define it as “is the app working, not just is the process alive”.

  • Explain statuses, options and exit codes.

  • Mention Compose service_healthy, Swarm replacement and Kubernetes probes instead.

25

Describe how you would handle sensitive data with Docker.

Sensitive data, such as passwords, API keys, TLS private keys, tokens and personal data, must never be baked into images: anyone who can pull the image can read every layer, and deleting a file in a later layer does not remove it from the earlier one. Supply secrets at run time, through Docker or Compose secrets (mounted as files under /run/secrets), orchestrator secrets (Kubernetes Secrets with encryption at rest, Swarm secrets), or ideally an external secret manager (HashiCorp Vault, AWS Secrets Manager, Google Secret Manager, Azure Key Vault). At build time, use BuildKit secret mounts (RUN --mount=type=secret), which never end up in a layer. Prefer files over environment variables, because environment variables leak through docker inspect, crash dumps, child processes and logs. Also keep secrets out of the build context and Git (.dockerignore, secret scanning), encrypt data at rest and in transit, rotate secrets, and limit who can access the Docker daemon.

Read full answer

Applies toDocker Engine 27+ with BuildKit, Docker Compose v2, Swarm and Kubernetes

Build Time: Secret Mounts

# syntax=docker/dockerfile:1
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
# The token is available only during this RUN step and is never stored in a layer
RUN --mount=type=secret,id=pip_token \
    PIP_INDEX_URL="https://__token__:$(cat /run/secrets/pip_token)@pypi.example.com/simple" \
    pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "-m", "app"]
docker build --secret id=pip_token,src=./pip_token.txt -t example/app:1.0 .

Never use ARG or ENV for secrets: their values are stored in the image history and metadata.

Run Time: Compose Secrets as Files

services:
  api:
    image: example/api:1.4.0
    secrets:
      - db_password
    environment:
      DB_PASSWORD_FILE: /run/secrets/db_password
  db:
    image: postgres:17
    secrets:
      - db_password
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets:
  db_password:
    file: ./secrets/db_password.txt      # git-ignored; in Swarm, use external secrets

Many official images support the *_FILE convention. Applications should read the file at start-up, or watch it to support rotation.

Options Compared

Method Where the secret lives Risks
In the image (COPY, ARG, ENV) Every copy of the image Never do this
-e / --env-file Container config, visible in docker inspect and /proc Leaks to logs, child processes, error reporters
Mounted files (Compose or Swarm secrets, tmpfs) Memory-backed file in the container Limited to who can exec into the container
Kubernetes Secrets etcd (enable encryption at rest), mounted as files Base64 is not encryption; restrict RBAC
External secret manager Vault or a cloud service; fetched at start-up or synced (External Secrets Operator, CSI driver) Best: auditing, rotation, short-lived credentials

Other Practices

Area Practice
Source control .gitignore and .dockerignore for .env and key files; secret scanning (Gitleaks, TruffleHog, push protection)
Images Scan for secrets (trivy image --scanners secret)
Logs Never log secrets; redact in the logging pipeline
Docker daemon Access to the Docker socket is root-equivalent: restrict it; never mount it into untrusted containers
Data at rest Encrypted volumes and disks; database encryption; encrypted backups
Data in transit TLS between services; mTLS in a mesh
Rotation Short-lived credentials (Vault dynamic secrets, cloud IAM roles) instead of long-lived keys
Identity Prefer workload identity (IAM roles, Kubernetes service account tokens) over static keys

Pitfalls

  • Secrets in ARG/ENV, visible in docker history and docker inspect.

  • Copying .env into the image with COPY . ..

  • Thinking docker rm or a later RUN rm removes secrets from pushed layers.

  • Committing secrets to Git and only deleting them in a later commit: rotate them instead.

Interview Tips

  • State the rule: no secrets in images; inject them at run time.

  • Mention BuildKit secret mounts, file-based secrets and external secret managers.

  • Explain why environment variables are weaker than files, and cover rotation and access control.

26

What is Docker Swarm, and when would you use it?

Docker Swarm (swarm mode) is the container orchestrator built into Docker Engine. It turns several Docker hosts into one cluster of manager nodes, which hold the cluster state replicated with the Raft consensus protocol and schedule work, and worker nodes, which run tasks. You declare services: an image, a replica count, ports, networks, secrets and update policies. Swarm keeps that many tasks (containers) running, reschedules them when nodes fail, performs rolling updates and rollbacks, provides overlay networking with built-in DNS-based service discovery and load balancing (the routing mesh), and manages secrets and configs. Swarm is a good choice for small and medium deployments that want orchestration with little operational complexity, using familiar Compose files (docker stack deploy). For large-scale, ecosystem-heavy or multi-team platforms, Kubernetes is the industry standard.

Read full answer

Applies toDocker Engine 27+ swarm mode (the original standalone "Docker Swarm" product is retired)

Core Concepts

Concept Meaning
Node A Docker host in the swarm: manager or worker
Manager Keeps cluster state (Raft), schedules tasks, serves the API; use 3 or 5 for fault tolerance
Worker Runs tasks assigned by managers
Service Desired state: image, replicas (or global = one per node), ports, networks
Task One container instance of a service
Stack A group of services deployed from a Compose file
Overlay network Virtual network spanning nodes
Routing mesh Published ports reachable on every node, forwarded to healthy tasks
Secrets and configs Encrypted in the Raft log; mounted into tasks as files

Getting Started

docker swarm init --advertise-addr 10.0.1.10          # first manager
docker swarm join-token worker                        # prints the join command
# on other hosts: docker swarm join --token <token> 10.0.1.10:2377

docker service create --name web --replicas 3 -p 80:80 nginx:1.27
docker service ls
docker service ps web                                 # where the tasks run
docker service scale web=5
docker service update --image nginx:1.27.3 web        # rolling update
docker service rollback web

Manager Fault Tolerance

Managers Can lose Note
1 0 No fault tolerance
3 1 Common choice
5 2 Larger clusters

Raft needs a majority of managers to make changes. With an even number there is no benefit; 4 managers tolerate only 1 failure, like 3.

When to Use Swarm

Good fit Poor fit
Small teams already using Docker and Compose Large, multi-team platforms
A handful of hosts, edge or on-premises sites Need for a rich ecosystem (operators, service meshes, policy engines)
Simple stateless services needing HA and rolling updates Advanced autoscaling (Swarm has no built-in autoscaler)
Low operational overhead is a priority Managed cloud offerings and hiring considerations favour Kubernetes

Pitfalls

  • One manager in production.

  • Running heavy workloads on managers, which can destabilise the cluster (use --availability drain on managers if needed).

  • Stateful services with host-local volumes, which cannot move between nodes.

  • Not backing up the swarm state (/var/lib/docker/swarm on a manager).

Interview Tips

  • Define Swarm as Docker’s built-in orchestrator with managers (Raft) and workers.

  • Explain services, tasks, the routing mesh and rolling updates.

  • Say when to choose it over Kubernetes: simplicity at small scale.

27

What is the difference between Docker Swarm and Kubernetes?

Both are container orchestrators: they schedule containers across a cluster, keep a desired number running, roll out updates and provide service discovery. Docker Swarm is built into Docker Engine and optimised for simplicity. Setup is one command, it uses Compose files, and it has fewer concepts, but it also has a smaller feature set and ecosystem. Kubernetes is a separate, extensible platform with a much richer model: pods, Deployments, StatefulSets, a declarative API with custom resources and operators, autoscaling, fine-grained networking and security policies, pluggable storage and networking, and a vast ecosystem (Helm, Argo CD, service meshes, policy engines). It is offered as a managed service by every major cloud. The trade-off is simplicity (Swarm) versus capability and ecosystem (Kubernetes). Kubernetes is the industry standard for production platforms; Swarm suits small, simple deployments.

Read full answer

Applies toDocker Engine 27+ swarm mode and Kubernetes 1.30+

Comparison

Aspect Docker Swarm Kubernetes
Installation Built in: docker swarm init Separate components (control plane, kubelet, CNI) or a managed service (EKS, GKE, AKS)
Learning curve Low Steep
Configuration Compose files (docker stack deploy) Kubernetes manifests (YAML), Helm charts, Kustomize
Basic unit Service → tasks (containers) Pod (one or more containers) managed by Deployments, StatefulSets, DaemonSets, Jobs
Scaling Manual (docker service scale) Horizontal Pod Autoscaler, cluster autoscaling, KEDA
Load balancing Routing mesh and VIP, built in Services (kube-proxy or eBPF), Ingress, Gateway API
Networking Overlay networks built in Pluggable CNI (Cilium, Calico); NetworkPolicies
Storage Volumes and plugins; limited orchestration PersistentVolumes, StorageClasses, CSI drivers, dynamic provisioning
Stateful apps Basic StatefulSets, operators for databases
Health checks Container HEALTHCHECK Liveness, readiness and startup probes
Updates Rolling updates with rollback Rolling updates; canary and blue-green with Argo Rollouts or Flagger
Security TLS between nodes, secrets, overlay encryption RBAC, Pod Security Standards, NetworkPolicies, admission control, secrets
Extensibility Limited Custom resources, operators, admission webhooks
Ecosystem and community Small Very large; CNCF ecosystem
Managed cloud offerings None from major clouds Every major cloud

Same App in Both

# Swarm: compose.yaml, deployed with: docker stack deploy -c compose.yaml shop
services:
  web:
    image: example/web:2.0.0
    ports:
      - "80:8080"
    deploy:
      replicas: 3
      update_config:
        parallelism: 1
        order: start-first

In Kubernetes the same service needs a Deployment (replicas, image, probes) and a Service (with an Ingress or Gateway for external traffic). There are more objects, but each one gives finer control.

Choosing

Choose Swarm when Choose Kubernetes when
A small team runs a few services on a few hosts Many teams and services share a platform
You want orchestration with minimal operations You need autoscaling, rich policies, operators
On-premises or edge sites need something simple You want managed cloud services and a large hiring pool
Compose files are already the standard You need a large ecosystem (GitOps, meshes, observability integrations)

Lightweight Kubernetes distributions (k3s, MicroK8s) narrow the gap for small and edge deployments.

Pitfalls

  • Choosing Kubernetes for a tiny app and spending more time on the platform than on the product.

  • Choosing Swarm for a growing platform, then migrating later under pressure.

  • Assuming Compose files run unchanged on Kubernetes; tools such as Kompose only help as a starting point.

Interview Tips

  • Summarise as simplicity versus capability and ecosystem.

  • Compare units, scaling, networking, storage and extensibility.

  • Give concrete criteria for choosing each.

28

What is a Docker Stack?

A Docker Stack is a group of related Swarm services, together with their networks, volumes, secrets and configs, defined in one Compose file and deployed and managed as a unit on a Docker Swarm cluster. You deploy it with docker stack deploy -c compose.yaml <name>. Swarm creates every service with the stack name as a prefix (shop_web, shop_api), and running the same command again with a changed file updates the stack: services whose configuration changed get rolling updates. Stack files use the normal Compose format plus the deploy: section (replicas, placement, update and rollback settings, resources, restart policy). Stacks need pre-built images from a registry, because build: is ignored. Stacks are Swarm’s equivalent of what Compose does on one host, or roughly what a Helm release does in Kubernetes.

Read full answer

Applies toDocker Engine 27+ swarm mode

Example Stack File

services:
  web:
    image: ghcr.io/example/web:2.0.0
    ports:
      - "80:8080"
    networks: [frontend]
    deploy:
      replicas: 3
      update_config:
        parallelism: 1
        delay: 10s
        order: start-first
        failure_action: rollback
      restart_policy:
        condition: on-failure
  api:
    image: ghcr.io/example/api:1.4.0
    networks: [frontend, backend]
    secrets: [db_password]
    deploy:
      replicas: 2
      resources:
        limits:
          cpus: "1"
          memory: 512M
  db:
    image: postgres:17
    networks: [backend]
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets: [db_password]
    volumes:
      - pgdata:/var/lib/postgresql/data
    deploy:
      placement:
        constraints:
          - node.labels.db == true
networks:
  frontend:
    driver: overlay
  backend:
    driver: overlay
    internal: true
volumes:
  pgdata: {}
secrets:
  db_password:
    external: true

Managing a Stack

printf 's3cret-value' | docker secret create db_password -   # create the external secret once
docker node update --label-add db=true node-2                  # where the database may run

docker stack deploy -c compose.yaml shop     # create or update
docker stack ls                              # stacks and service counts
docker stack services shop                   # services and replica status
docker stack ps shop                         # tasks and the nodes they run on
docker stack rm shop                         # remove services and networks (volumes stay)

Stack Versus Compose Project

docker compose up docker stack deploy
Target One Docker host A Swarm cluster
build: Supported Ignored; images must be in a registry
deploy: section Partly used (resources) Fully used: replicas, placement, update and rollback
Networks Bridge by default Overlay by default
Self-healing across nodes No Yes
Secrets File-based Swarm secrets, encrypted in the cluster

Pitfalls

  • Expecting build: to work: build and push images first.

  • depends_on ordering is ignored in stacks: services must retry until their dependencies are ready.

  • Stateful services without placement constraints: the database moves to another node, where its local volume does not exist.

  • Using latest tags: nodes may run different images, and updates are not detected.

Interview Tips

  • Define a stack as “a multi-service app from one Compose file on Swarm”.

  • Show docker stack deploy/ls/services/ps/rm.

  • Mention the deploy: section and the differences from Compose (no build, no depends_on).

29

How do you deploy an application stack in Docker Swarm?

The process: 1. Prepare a swarm: docker swarm init on the first manager and docker swarm join on the others. Use 3 managers for fault tolerance. 2. Build and push the images to a registry all nodes can reach, tagged with immutable versions. 3. Create the external secrets and configs the stack needs (docker secret create), and label nodes for placement constraints. 4. Write a Compose file with a deploy: section for each service: replicas, update and rollback policy, resources, placement. 5. Run docker stack deploy -c compose.yaml <stack> (with --with-registry-auth for private registries). 6. Verify with docker stack services and docker stack ps.

Later updates are the same command with a new image tag: Swarm rolls out the changed services according to update_config, and can roll back automatically on failure.

Read full answer

Applies toDocker Engine 27+ swarm mode

1. Cluster

docker swarm init --advertise-addr 10.0.1.10
docker swarm join-token manager      # join two more managers with this
docker swarm join-token worker       # join workers with this
docker node ls
docker node update --label-add tier=db node-3

2. Images and Secrets

docker build -t ghcr.io/example/api:1.4.0 ./api
docker push ghcr.io/example/api:1.4.0
openssl rand -base64 24 | docker secret create db_password -

3. Stack File

services:
  api:
    image: ghcr.io/example/api:1.4.0
    ports:
      - "8080:8080"
    secrets: [db_password]
    environment:
      DB_HOST: db
      DB_PASSWORD_FILE: /run/secrets/db_password
    healthcheck:
      test: ["CMD", "/app/healthcheck"]
      interval: 10s
      retries: 3
    deploy:
      replicas: 3
      update_config:
        parallelism: 1
        delay: 10s
        order: start-first
        failure_action: rollback
        monitor: 30s
      rollback_config:
        parallelism: 1
      restart_policy:
        condition: on-failure
        max_attempts: 5
  db:
    image: postgres:17
    secrets: [db_password]
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    volumes:
      - pgdata:/var/lib/postgresql/data
    deploy:
      replicas: 1
      placement:
        constraints:
          - node.labels.tier == db
volumes:
  pgdata: {}
secrets:
  db_password:
    external: true

4. Deploy and Verify

docker stack deploy -c compose.yaml --with-registry-auth shop
docker stack services shop            # REPLICAS should show 3/3 and 1/1
docker stack ps shop --no-trunc       # task states and errors
docker service logs -f shop_api

5. Update and Roll Back

# Change the image tag to 1.5.0 in compose.yaml, then:
docker stack deploy -c compose.yaml --with-registry-auth shop
docker service ps shop_api            # watch tasks being replaced one at a time
docker service rollback shop_api      # manual rollback if needed

With failure_action: rollback, Swarm rolls back by itself if new tasks fail their health checks within the monitor window. order: start-first starts the new task before stopping an old one, avoiding capacity dips.

Deployment Checklist

Item Why
Immutable image tags, or digests Every node runs exactly the same image
Health checks Swarm only considers tasks healthy after the check passes; enables automatic rollback
--with-registry-auth Worker nodes can pull private images
Placement constraints for stateful services Data volumes are local to a node
Resource limits and reservations Predictable scheduling
Secrets as external objects Not in files committed to Git
CI/CD A pipeline runs docker stack deploy against a manager (over SSH, or with a Docker context)

Pitfalls

  • Images only on the build machine: other nodes cannot pull them.

  • Missing health checks, so broken releases are considered successful.

  • build: and depends_on in the stack file, which Swarm ignores.

  • Running docker stack deploy against a worker: it must target a manager.

Interview Tips

  • Walk through init and join → push images → secrets → stack file → deploy → verify.

  • Explain rolling updates with update_config and automatic rollback.

  • Mention registry auth, placement constraints and health checks.

30

How does Docker manage service replication and load balancing?

In Docker Swarm, a service declares its desired state: - replicated mode with N replicas, spread across nodes by the scheduler; - global mode, with one task on every eligible node.

Managers run a reconciliation loop. If a task or node fails, a new task is scheduled elsewhere to restore the count. Load balancing works at two levels: - Inside the cluster, every service gets a virtual IP (VIP) on its overlay networks, and Docker’s embedded DNS resolves the service name to that VIP. IPVS in the Linux kernel then spreads connections across the healthy tasks. A DNS round-robin mode (endpoint_mode: dnsrr) returns task IPs directly instead. - From outside, the ingress routing mesh makes a published port reachable on every node. A request arriving at any node is forwarded to a healthy task, even one on another node.

Read full answer

Plain Docker without Swarm has no replication: docker compose up --scale starts several containers, and their DNS name returns all their IPs.

Applies to: Docker Engine 27+ swarm mode

Replication

docker service create --name api --replicas 4 --network appnet example/api:1.4.0
docker service scale api=6
docker service create --name node-exporter --mode global prom/node-exporter:v1.8.2
docker service ps api            # task-to-node mapping; failed tasks are replaced
Mode Behaviour Use
Replicated N tasks, spread across nodes Stateless services
Global One task per node (new nodes get one automatically) Agents: monitoring, logging
Replicated-job / global-job Run to completion Batch jobs and migrations

The scheduler respects placement constraints (node.labels.zone == a), placement preferences (spread=node.labels.zone), and resource reservations.

Internal Load Balancing: VIP and DNS

client task --DNS "api"--> 10.0.1.5 (service VIP)
                             |
                         IPVS load balancer on the client's node
                         /           |            \
                   task 1 (node A)  task 2 (node B)  task 3 (node C)
Endpoint mode DNS returns Balancing Notes
vip (default) One stable virtual IP IPVS, per connection Clients need no special logic
dnsrr All task IPs Client or DNS round robin For clients with their own balancing; cannot be combined with ingress-published ports

IPVS balances connections, not requests. Long-lived connections (HTTP/2, gRPC, database pools) stay on one task, so use an L7 proxy or client-side balancing for those.

External Load Balancing: The Routing Mesh

docker service create --name web --replicas 3 -p 80:8080 example/web:2.0.0
# Port 80 now answers on every node, including nodes running no web task
user -> external LB (or DNS) -> any node:80 -> ingress network -> a healthy web task
Publish mode Behaviour
ingress (default) Routing mesh: every node listens and forwards
host (mode: host in the ports section) Only nodes running a task listen; no extra hop; preserves the client’s source IP

An external load balancer, such as a cloud load balancer, HAProxy or nginx, usually sits in front and spreads traffic across the nodes.

Health and Updates

  • Only tasks that pass their HEALTHCHECK receive traffic; unhealthy tasks are replaced.

  • Rolling updates (update_config) replace tasks gradually, so the VIP always has healthy back ends.

Pitfalls

  • Connection-level balancing for gRPC, so one task gets all the traffic.

  • Losing the client IP through the routing mesh; use host mode or proxy protocol if you need it.

  • Ingress ports blocked between nodes by firewalls (UDP 4789, TCP and UDP 7946).

Interview Tips

  • Describe desired-state replication and reconciliation, and replicated versus global modes.

  • Explain VIP + DNS + IPVS inside the cluster and the routing mesh outside.

  • Mention connection versus request balancing and host-mode publishing.

31

What command would you use to list all running containers?

Use docker ps, or its newer equivalent docker container ls. It lists running containers with their ID, image, command, creation time, status, published ports and name. Useful variations: - docker ps -a includes stopped containers too; - docker ps -q prints only IDs, for scripting; - --filter (-f) selects by status, name, label, image, network or health; - --format prints custom columns or JSON; - -s adds sizes; - -l shows the latest container; - -n 5 shows the last five created.

For Compose projects, docker compose ps lists the project’s containers. In Swarm, docker service ps <service> lists a service’s tasks across nodes.

Read full answer

Applies toDocker Engine 27+ CLI

Examples

docker ps                                   # running containers
docker ps -a                                # all containers, including exited
docker ps -q                                # IDs only
docker ps -aq --filter status=exited        # IDs of stopped containers
docker ps --filter name=api                 # name contains "api"
docker ps --filter label=team=payments
docker ps --filter ancestor=nginx:1.27      # created from this image
docker ps --filter health=unhealthy
docker ps -s                                # include container size (writable layer)
docker ps --no-trunc                        # full IDs and commands

Custom Output

docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}'
docker ps --format json | jq -r '.Names'
Placeholder Value
.ID Container ID
.Names Container name
.Image Image
.Status For example Up 3 hours (healthy)
.Ports Published ports
.State running, exited, paused
.Labels / .Label "key" Labels
.Networks Attached networks

Common Filters

Filter Example
status created, restarting, running, paused, exited, dead
name --filter name=web
label --filter label=env=prod
ancestor --filter ancestor=postgres:17
network --filter network=appnet
publish / expose --filter publish=8080
health healthy, unhealthy, starting, none

Related Commands

Command Shows
docker compose ps Containers in the current Compose project
docker stats Live CPU, memory and I/O of running containers
docker service ls / docker service ps web Swarm services / their tasks
docker container prune Removes all stopped containers

Pitfalls

  • Forgetting -a when looking for a container that crashed: it is not “running”.

  • Scripts parsing the default table output; use -q or --format instead.

  • Not using docker ps on remote hosts: set a Docker context (docker context use prod) or DOCKER_HOST.

Interview Tips

  • Answer docker ps (or docker container ls), and -a for all containers.

  • Mention -q, --filter and --format for scripting.

  • Note docker compose ps and docker service ps.

32

How can you stop all containers running on a host using a single command?

Combine docker stop with docker ps -q, which prints the IDs of all running containers: docker stop $(docker ps -q). docker stop sends SIGTERM to each container’s main process, waits for a grace period (10 seconds by default, -t to change it), then sends SIGKILL, so applications can shut down cleanly. A safer form for scripts is docker ps -q | xargs -r docker stop, which does nothing when no containers are running. With GNU xargs, -r skips running the command on empty input; BSD and macOS xargs already behave this way. To stop immediately without a grace period, use docker kill. For Compose projects, docker compose stop (or down) is cleaner. Remember that containers with --restart always start again when the daemon restarts, and Swarm recreates tasks of services you stop by hand: scale the services or remove the stack instead.

Read full answer

Applies toDocker Engine 27+ CLI (bash or zsh; PowerShell shown separately)

Commands

# Graceful stop of every running container
docker stop $(docker ps -q)

# Safe when nothing is running, and handles many containers
docker ps -q | xargs -r docker stop

# Longer grace period for databases
docker ps -q | xargs -r docker stop -t 60

# Immediate stop (SIGKILL)
docker ps -q | xargs -r docker kill

# Stop and remove all containers (running and stopped)
docker ps -aq | xargs -r docker rm -f
# PowerShell
docker ps -q | ForEach-Object { docker stop $_ }

Variations by Scope

Goal Command
Containers with a label docker stop $(docker ps -q --filter label=env=dev)
One Compose project docker compose stop (keep containers) or docker compose down (remove them)
Swarm services docker service scale web=0, or docker stack rm shop
Everything on a development machine, plus cleanup docker stop $(docker ps -q), then docker system prune
Stop the Docker daemon itself (Linux) sudo systemctl stop docker docker.socket

stop Versus kill

docker stop docker kill
Signal SIGTERM (or the image’s STOPSIGNAL), then SIGKILL after the timeout SIGKILL immediately (or --signal)
Cleanup The app can finish requests, flush data and close connections No cleanup
Use Normal shutdowns Hung containers, emergencies

Why Containers Come Back

  • Restart policy always: restarts when the daemon restarts. unless-stopped stays stopped after a manual stop. To change it, run docker update --restart no <id>.

  • Swarm services and Kubernetes pods: the orchestrator replaces stopped containers to restore the desired state.

  • Compose with restart: always: the same as the restart policy above.

Pitfalls

  • docker stop $(docker ps -q) with nothing running prints an error; use xargs -r.

  • Apps that ignore SIGTERM, for example because a shell runs as PID 1, wait the full timeout and are killed; use exec-form CMD or --init.

  • Stopping databases with kill, which risks recovery time or data issues.

  • Running this on a shared or production host without checking what is running.

Interview Tips

  • Give docker stop $(docker ps -q) and the xargs -r variant.

  • Explain SIGTERM, the grace period and SIGKILL, and stop versus kill.

  • Mention restart policies and orchestrators restarting containers.

33

How would you execute a command inside a running container?

Use docker exec. It starts an additional process inside an already running container, in the same namespaces (filesystem, network, PIDs) as the main process. For an interactive shell, run docker exec -it <container> sh (or bash if the image has it): -i keeps STDIN open and -t allocates a terminal. Other useful options are -u to run as a different user, -w to set the working directory, -e to add environment variables, and -d to run in the background. The container must be running; for a stopped container, start it, or run a new container from the same image. Distroless images have no shell, so use docker debug (Docker Desktop) or attach a debug container that shares the target’s namespaces. In Compose, use docker compose exec <service> ...; in Kubernetes, kubectl exec -it pod -- sh.

Read full answer

Applies toDocker Engine 27+ CLI

Examples

docker exec -it api sh                          # interactive shell
docker exec api ls -la /app                     # one-off command, output returned
docker exec -u 0 -it api sh                     # as root (for debugging only)
docker exec -w /app -e DEBUG=1 api python manage.py check
docker exec -d api sh -c 'touch /tmp/ready'     # in the background
docker exec -it db psql -U postgres             # database shell in a Postgres container
docker exec api sh -c 'echo $HOSTNAME && env | sort | head'   # shell features need sh -c
docker compose exec api pytest -q               # in a Compose service

Options

Option Meaning
-i Keep STDIN open (needed to type into the process)
-t Allocate a pseudo-terminal (prompt, line editing, colours)
-u user[:group] Run as a given user or UID
-w /path Working directory
-e KEY=value, --env-file Extra environment variables
-d Detached: start and return immediately
--privileged Extended privileges for this process (avoid)

exec Versus attach Versus run

Command What it does
docker exec Starts a new process in a running container
docker attach Connects your terminal to the container’s main process (PID 1); Ctrl+C may stop the container (detach with Ctrl+P, Ctrl+Q)
docker run Creates a new container from an image

Debugging Minimal Images

# Docker Desktop: debug shell with tools, even for distroless images
docker debug api

# Plain Engine: a tools container sharing the target's network and PID namespaces
docker run --rm -it --network container:api --pid container:api nicolaka/netshoot

The second form lets you run ps, ss, curl and tcpdump against the target container without installing tools in its image.

Exit Codes and Scripting

docker exec returns the exit code of the command, so it works in scripts and health checks:

if docker exec db pg_isready -U postgres; then echo "db ready"; fi

Use -t only for interactive use: in CI, a TTY merges stderr into stdout and can add carriage returns to the output.

Pitfalls

  • Making fixes with exec in production: the changes are lost when the container is recreated. Fix the image instead.

  • Expecting shell syntax (pipes, $VAR, &&) without sh -c '...'.

  • “executable file not found”: the image does not contain bash; try sh, or use a debug container.

  • Exec access as a security risk: anyone who can exec can read secrets in the container; restrict access to the Docker socket and, in Kubernetes, to pods/exec.

Interview Tips

  • Answer docker exec -it <container> sh.

  • Explain -i, -t, -u, -w, -e, and exec versus attach.

  • Mention debugging distroless images and that changes made by exec are not persistent.

34

What command would you use to display the logs of a container?

Use docker logs <container>. It shows what the container’s main process wrote to STDOUT and STDERR, as captured by Docker’s logging driver. Common options: - -f follows new output, like tail -f; - --tail N shows only the last N lines; - --since and --until select a time range (10m, 2026-11-05T10:00:00); - -t adds timestamps; - --details shows extra attributes.

It works for the default json-file and local drivers and for journald. With remote drivers (syslog, fluentd, awslogs, gelf), recent Docker versions keep a local cache (“dual logging”), so docker logs still works. For Compose, use docker compose logs -f [service]. For Swarm, use docker service logs. In production, ship logs to a central logging system rather than relying on docker logs.

Read full answer

Applies toDocker Engine 27+ CLI

Examples

docker logs api                               # everything captured so far
docker logs -f api                            # follow live output
docker logs --tail 100 -f api                 # last 100 lines, then follow
docker logs --since 15m api                   # last 15 minutes
docker logs --since 2026-11-05T10:00:00 --until 2026-11-05T10:30:00 api
docker logs -t api                            # with timestamps
docker logs api 2>&1 | grep -i error          # stderr is sent to stderr; merge before grepping
docker compose logs -f --tail 50 api worker   # several Compose services
docker service logs -f shop_api               # all tasks of a Swarm service

Options

Option Meaning
-f, --follow Stream new log lines
-n, --tail Number of lines from the end (all by default)
--since / --until Relative (30m, 2h) or absolute timestamps
-t, --timestamps Prefix each line with its timestamp
--details Extra attributes from --log-opt labels and environment

Logging Drivers and Rotation

Driver Notes
json-file (default) JSON lines on the host; no rotation unless configured
local Compact, rotated by default; recommended for single hosts
journald Into the systemd journal; journalctl CONTAINER_NAME=api
syslog, fluentd, gelf, awslogs, gcplogs, splunk Ship logs to external systems
{
  "log-driver": "local",
  "log-opts": { "max-size": "20m", "max-file": "5" }
}

This goes in /etc/docker/daemon.json. Without rotation, json-file logs can fill the disk. The setting applies to containers created after the daemon restarts.

Making Logs Useful

  • Log to stdout and stderr, not to files inside the container. Official images often symlink log files to /dev/stdout.

  • Use structured JSON logs so central systems can parse them.

  • Include request or trace IDs to correlate across services.

Pitfalls

  • No output because the app writes to a file instead of stdout, or buffers output (Python: set PYTHONUNBUFFERED=1).

  • Disk full from unrotated json-file logs.

  • Missing logs after docker rm: container logs are deleted with the container.

  • Grepping without 2>&1, missing stderr lines.

Interview Tips

  • Answer docker logs, with -f, --tail, --since and -t.

  • Explain that it shows stdout and stderr through the logging driver.

  • Mention log rotation, Compose and Swarm variants, and central logging in production.

35

Explain how to copy files from a container to the local file system.

Use docker cp: docker cp <container>:<path-in-container> <local-path>. It copies a file or a whole directory out of the container’s filesystem to the host, and the reverse order copies into the container. It works on running and stopped containers, because it reads the container’s filesystem directly. Useful details: - -a (archive mode) keeps ownership (UID and GID); - -L follows symbolic links in the source; - - as the destination writes a tar stream to stdout.

It cannot read mounted volumes’ contents in every case; for volumes, mount the volume into a helper container and copy from there. Alternatives are docker exec ... cat file > local for single files, a bind mount when files should be shared continuously, and, in Kubernetes, kubectl cp.

Read full answer

Applies toDocker Engine 27+ CLI

Examples

# A single file to the current directory
docker cp api:/app/logs/error.log ./error.log

# A whole directory (creates ./reports locally)
docker cp api:/app/reports ./reports

# Copy only the contents of a directory into an existing local folder
docker cp api:/app/reports/. ./local-reports/

# From a stopped container (for example to rescue files after a crash)
docker cp crashed-job:/tmp/output.csv .

# Into a container
docker cp ./config.yaml api:/etc/app/config.yaml

# As a tar stream, then compressed
docker cp api:/var/lib/app - | gzip > app-data.tar.gz

# Keep ownership information
docker cp -a api:/srv/data ./data

Path Rules

Source Destination Result
File Existing directory File copied into the directory
File Non-existent path Copied with that name
Directory dir Existing directory Creates dest/dir
Directory dir/. Existing directory Copies the contents of dir into dest
Directory Non-existent path Creates it with the contents

Copying From a Volume

docker run --rm -v pgdata:/data:ro -v "$PWD":/out alpine:3.20 \
  sh -c 'cp -a /data/. /out/pgdata-copy/'

Using a helper container works even if the original container has been removed, and avoids copying live database files from a running database. For databases, prefer pg_dump or the equivalent.

Other Ways

Method Use
docker exec api cat /app/file > file Quick single text file
Bind mount (-v "$PWD"/out:/app/out) Files appear on the host continuously
docker exec with tar -cf - piped to a local tar -xf - Streaming copies with tar options
docker export The whole container filesystem as a tar
docker create + docker cp Extract build artifacts from an image without running it

The last trick is handy in CI:

id=$(docker create example/builder:1.0)
docker cp "$id":/out/app.tar.gz .
docker rm "$id"

Pitfalls

  • Permission issues: copied files are owned by the user running docker cp (unless -a is used), and copying in may give files the wrong owner for the container’s user.

  • Copying from distroless images works (no shell needed), but docker exec cat would not.

  • Copying large live data (databases) while they are being written gives inconsistent copies.

  • Using docker cp to deploy configuration: the changes are lost when the container is recreated.

Interview Tips

  • Answer docker cp container:/path ./local, and the reverse for copying in.

  • Mention stopped containers, dir/. semantics, -a and tar streams.

  • Explain the helper container for volumes and the docker create trick for artifacts.

36

How can you inspect the details of a specific container via the CLI?

Use docker inspect <container>, or docker container inspect. It prints the container’s full low-level configuration and state as JSON: - State: running, exit code, OOMKilled, health, start time, PID; - Config: image, command, entrypoint, environment, labels, user; - HostConfig: resource limits, restart policy, port bindings, security options, mounts; - NetworkSettings: networks, IPs, MAC addresses; - Mounts.

Use --format (-f) with Go templates to pull out single fields, or pipe the JSON to jq. Other commands give complementary views: docker logs for output, docker stats for live resource use, docker top for processes, docker port for port mappings, docker diff for filesystem changes, and docker events for lifecycle events.

Read full answer

Applies toDocker Engine 27+ CLI

Examples

docker inspect api                                             # full JSON
docker inspect -f '{{.State.Status}} {{.State.ExitCode}} {{.State.OOMKilled}}' api
docker inspect -f '{{.Config.Image}} {{json .Config.Cmd}}' api
docker inspect -f '{{range $k, $v := .NetworkSettings.Networks}}{{$k}} {{$v.IPAddress}}{{"\n"}}{{end}}' api
docker inspect -f '{{json .Mounts}}' api | jq
docker inspect -f '{{.HostConfig.Memory}} {{.HostConfig.NanoCpus}} {{.HostConfig.RestartPolicy.Name}}' api
docker inspect -f '{{json .State.Health}}' api | jq '.Status, .Log[-1].Output'
docker inspect api | jq '.[0].Config.Env'                      # careful: shows secret values

Key Sections

Section Contains
State Status, running, paused, restarting, OOMKilled, exit code, error, start and finish times, health
Config Image, command, entrypoint, environment, labels, working directory, user, exposed ports
HostConfig Memory and CPU limits, restart policy, port bindings, capabilities, security options, log configuration
NetworkSettings Networks, IP addresses, gateways, published ports
Mounts Volumes and bind mounts with source, destination and mode
Image Image ID (digest) the container was created from
LogPath, RestartCount, Platform, Driver Diagnostics

Complementary Commands

Command Shows
docker ps --filter name=api Quick status, ports and name
docker logs --tail 50 api Recent output
docker stats api --no-stream CPU, memory, network and I/O usage
docker top api Processes with host PIDs
docker port api Published port mappings
docker diff api Files added, changed or deleted in the writable layer
docker events --filter container=api Live lifecycle events (start, die, oom, health_status)
docker inspect <image> / docker network inspect / docker volume inspect The same for other object types

A Typical Debugging Flow

docker ps -a --filter name=api                     # exited? restarting?
docker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}} {{.State.Error}}' api
docker logs --tail 100 api                         # what it printed before dying
docker inspect -f '{{json .HostConfig.Memory}}' api   # limit too low?

Exit code 137 with OOMKilled: true means the memory limit was exceeded. 1 usually means an application error. 127 means the command was not found.

Pitfalls

  • Sharing docker inspect output: it includes environment variables, often with secrets.

  • Template errors on missing fields; use {{json .Field}} to see the structure first.

  • Confusing image and container inspect: an image shows its default configuration; a container shows the actual configuration it runs with.

Interview Tips

  • Answer docker inspect, with --format or jq for specific fields.

  • Name the main sections: State, Config, HostConfig, NetworkSettings, Mounts.

  • Mention stats, top, logs, diff and events for a full picture.

37

Describe how to use Docker’s REST API to start a container.

The Docker CLI is a client of the Docker Engine REST API, which the daemon serves on a Unix socket (/var/run/docker.sock) by default, or on TCP protected with TLS. Starting a container through the API takes up to three calls: 1. Pull the image if it is not present: POST /images/create?fromImage=nginx&tag=1.27. 2. Create the container: POST /containers/create?name=web with a JSON body holding the image, command, environment, and HostConfig (port bindings, mounts, restart policy, limits). The response contains the container ID. 3. Start it: POST /containers/{id}/start, which returns 204 No Content on success.

Then use GET /containers/{id}/json to inspect it and GET /containers/{id}/logs for logs. Prefix paths with an API version (for example /v1.47), and check yours with docker version. In code, use an official SDK (Go, or the Python docker package) rather than raw HTTP. Access to the API is root-equivalent, so protect it.

Read full answer

Applies toDocker Engine API v1.45+ (Docker Engine 26+)

With curl Over the Unix Socket

API=http://localhost/v1.45
SOCK=/var/run/docker.sock

# 1. Pull the image (streams progress as JSON lines)
curl -s --unix-socket $SOCK -X POST "$API/images/create?fromImage=nginx&tag=1.27"

# 2. Create the container
curl -s --unix-socket $SOCK -X POST "$API/containers/create?name=web" \
  -H "Content-Type: application/json" \
  -d '{
        "Image": "nginx:1.27",
        "Env": ["NGINX_ENTRYPOINT_QUIET_LOGS=1"],
        "ExposedPorts": {"80/tcp": {}},
        "HostConfig": {
          "PortBindings": {"80/tcp": [{"HostPort": "8080"}]},
          "RestartPolicy": {"Name": "unless-stopped"},
          "Memory": 268435456
        }
      }'
# -> {"Id":"4f2c...","Warnings":[]}

# 3. Start it
curl -s -o /dev/null -w "%{http_code}\n" --unix-socket $SOCK -X POST "$API/containers/web/start"
# -> 204 (304 if it was already running)

# Inspect and read logs
curl -s --unix-socket $SOCK "$API/containers/web/json" | jq '.State.Status'
curl -s --unix-socket $SOCK "$API/containers/web/logs?stdout=1&stderr=1&tail=20" --output -

Endpoints accept the container name or ID. The Memory value is in bytes (256 MiB here). Version v1.45 works on Docker Engine 26 and newer; newer daemons also accept older API versions.

With an SDK

In application code, use an official SDK instead of raw HTTP. In the Python docker package, client.containers.run("nginx:1.27", name="web", detach=True, ports={"80/tcp": 8080}) pulls the image if needed, then creates and starts the container. The Go client (github.com/docker/docker/client) exposes ContainerCreate and ContainerStart in the same way.

Common Status Codes

Call Success Errors
POST /containers/create 201 Created 404 image not found (pull first), 409 name already in use
POST /containers/{id}/start 204 No Content 304 already started, 404 no such container
POST /containers/{id}/stop 204 304 already stopped

Securing the API

  • The socket gives full control of the host: never expose TCP port 2375 without TLS, and never mount the socket into untrusted containers.

  • For remote access, use TLS with client certificates (port 2376) or SSH (DOCKER_HOST=ssh://user@host).

  • Consider rootless Docker or an authorisation plugin to limit what clients can do.

Pitfalls

  • Forgetting to pull before creating: the create call returns 404.

  • Missing Content-Type: application/json.

  • Port bindings need both ExposedPorts and HostConfig.PortBindings for older API versions.

  • Unversioned paths, which can change behaviour when the daemon is upgraded.

Interview Tips

  • Describe pull → create (with HostConfig) → start, with the Unix socket and versioned paths.

  • Mention status codes (201, 204, 404, 409) and the SDKs.

  • Stress that API access is root-equivalent.

38

Explain the importance of minimizing the number of layers in a Dockerfile.

Each RUN, COPY and ADD instruction creates a layer, and every layer adds some metadata, storage and pull overhead. More importantly, files created in one layer and deleted in a later one still take space, because a layer cannot shrink an earlier one. Minimising layers by combining related commands, especially install-and-clean-up in one RUN, keeps images smaller, faster to pull and with less leftover data, such as package caches or temporary secrets. Overlay filesystems also have a maximum layer count (127 for overlay2), and very deep layer stacks can slow file lookups slightly. However, layer count is a secondary goal: since multi-stage builds, the final image’s layers are what count, and good cache use sometimes means more, well-ordered layers. For example, separate dependency installation from source copying so code changes do not reinstall everything. The real aim is small images and fast, cache-friendly builds, not the lowest possible number.

Read full answer

Applies toDockerfile builds with BuildKit (Docker Engine 23+)

The Main Reason: Deleting in a Later Layer Does Not Help

# Three layers; the package lists and build tools remain in the image
RUN apt-get update
RUN apt-get install -y build-essential curl
RUN rm -rf /var/lib/apt/lists/*        # hides the files but does not reclaim the space

# One layer; the cleanup actually reduces the size
RUN apt-get update \
 && apt-get install -y --no-install-recommends curl \
 && rm -rf /var/lib/apt/lists/*

Combining apt-get update with install also avoids a stale cached update layer, which can make installs fail or install old versions.

Which Instructions Create Layers

Instruction Layer?
RUN, COPY, ADD Yes: filesystem changes
FROM Brings in the base image’s layers
ENV, LABEL, CMD, ENTRYPOINT, EXPOSE, USER, WORKDIR (if the directory exists), ARG Metadata only (empty layers in history)

Balancing Fewer Layers With Caching

# Good: few layers AND cache-friendly ordering
FROM node:22-slim
WORKDIR /app
COPY package.json package-lock.json ./          # changes rarely
RUN npm ci --omit=dev && npm cache clean --force   # cached until dependencies change
COPY . .                                         # changes often
CMD ["node", "server.js"]

Merging the two COPY steps would save a layer but break caching: every code edit would reinstall all dependencies.

Better Tools Than Squeezing Layers

Technique Effect
Multi-stage builds Build tools and intermediate files stay in earlier stages; the final stage has only a few layers
Cache mounts (RUN --mount=type=cache) Package caches never enter a layer
Secret mounts Credentials never enter a layer
.dockerignore Fewer, smaller files copied
COPY --link Independent layers that can be reused when the base changes
Squashing (--squash, experimental) One final layer, but layer sharing with the base image is lost; rarely worth it

Effects Summary

Too many layers Too few layers
Leftover files in early layers Poor caching: small changes rebuild everything
Slightly more metadata and pull overhead Less layer sharing between images
Can hit the layer limit in extreme cases Harder-to-read Dockerfiles with very long RUN lines

Pitfalls

  • Cleaning up in a separate RUN, which does not shrink the image.

  • One giant RUN that does everything, so every change invalidates all of it.

  • Chasing layer counts instead of measuring actual image size (docker history, dive).

Interview Tips

  • Explain why later deletions do not shrink images, and the same-layer cleanup rule.

  • Balance it with cache-friendly ordering.

  • Mention multi-stage builds and cache or secret mounts as the modern approach.

39

Discuss the best practices for tagging Docker images.

Tags are human-readable, mutable pointers to image digests. Good tagging makes it obvious what is running, where it came from, and how to roll back. Best practices: - Tag every build with an immutable, unique identifier, such as the Git commit SHA or a build number, and never reuse it. - For releases, also apply semantic version tags (1.4.2, plus convenience tags 1.4 and 1, which move to the newest patch or minor release). - Avoid latest in deployments: it is ambiguous, does not trigger updates reliably, and makes rollbacks unclear. - Deploy by digest (image@sha256:...), or at least by an immutable tag. - Turn on tag immutability in the registry where possible. - Add OCI labels (source repository, revision, version, creation time) inside the image. - Keep tags consistent across services. - Clean up old tags with retention policies.

Read full answer

Applies toOCI images and registries (Docker Hub, GHCR, ECR, Artifact Registry, Harbor)

A Practical Scheme

Tag Example Mutable? Purpose
Git SHA api:3f9c2ab No Exact traceability to source; used by CI and CD
Full version api:1.4.2 No (enforce it) Release identity
Minor and major api:1.4, api:1 Yes Consumers who want automatic patch or minor updates
Environment or channel api:staging, api:stable Yes Optional pointers for humans; never used by deployments
latest api:latest Yes Convenience for local use only
Variant suffix api:1.4.2-alpine, python:3.12-slim Depends Different base images or flavours

Tagging in CI

SHA=$(git rev-parse --short HEAD)
VERSION=1.4.2
IMAGE=ghcr.io/example/api

docker buildx build \
  --platform linux/amd64,linux/arm64 \
  --label org.opencontainers.image.source=https://github.com/example/api \
  --label org.opencontainers.image.revision="$(git rev-parse HEAD)" \
  --label org.opencontainers.image.version="$VERSION" \
  -t "$IMAGE:$SHA" -t "$IMAGE:$VERSION" -t "$IMAGE:1.4" -t "$IMAGE:1" \
  --push .

# Record the digest for deployment
docker buildx imagetools inspect "$IMAGE:$VERSION" --format '{{json .Manifest.Digest}}'

Deploy manifests then reference ghcr.io/example/api:1.4.2@sha256:... (tag for readability, digest for exactness). Tools such as Renovate keep digests updated automatically.

Why Not latest

Problem Effect
Ambiguous Nobody knows which version is running
Cached on nodes Kubernetes with IfNotPresent, or Docker, may keep running an old latest
Rollbacks There is no “previous latest” to go back to
Implicit docker pull nginx silently means nginx:latest

Registry Settings

  • Tag immutability (ECR, Artifact Registry, Harbor, GHCR via policies) prevents overwriting release tags.

  • Retention policies remove old SHA tags, for example keeping the last 50 and every release.

  • Signing (Cosign) attaches signatures to digests, not tags, which is another reason to deploy by digest.

Pitfalls

  • Overwriting a release tag with a different build, so two environments run different code under the same tag.

  • Only a version tag without a SHA, losing traceability to the exact commit.

  • Inconsistent schemes across teams (v1.4.2 versus 1.4.2 versus release-1.4.2).

  • Mutable environment tags in deployment manifests, making rollbacks and audits hard.

Interview Tips

  • Recommend Git SHA plus semantic versions, with floating major or minor tags for consumers.

  • Explain why to avoid latest and to deploy by digest.

  • Mention tag immutability, OCI labels and retention policies.

40

When should you use a .dockerignore file?

Use a .dockerignore file in practically every project that has a Dockerfile, and especially: - when the build context contains large directories the image does not need, such as .git, node_modules, virtual environments, build output, logs, test data or datasets; - when it contains sensitive files: .env, credentials, SSH keys, cloud configuration; - when the Dockerfile uses broad copies like COPY . .; - when frequently changing files would otherwise invalidate the build cache; - when host-built artifacts, such as macOS-compiled node_modules, must not leak into a Linux image.

It is cheap insurance: builds get faster, caching more reliable, images smaller and safer. You might skip it only when the Dockerfile copies specific files from a minimal, dedicated build directory.

Read full answer

Applies toDocker Engine 27+ with BuildKit

Situations and What to Ignore

Situation Typical entries
Any Git repository .git, .gitignore, .github
Node.js node_modules, npm-debug.log, dist (if rebuilt in the image), coverage
Python **/__pycache__, */.pyc, .venv, .pytest_cache, .mypy_cache
Java and Go target, build, bin, *.class
Secrets .env, .env.*, *.pem, *.key, credentials.json, .aws, .ssh
Editors and OS files .vscode, .idea, .DS_Store, *.swp
Large data data/, *.csv, *.parquet, model checkpoints not needed at run time
Docker files Dockerfile*, compose*.yaml (optional; harmless to include)

Starter File for a Python Service

.git
.github
.venv
**/__pycache__
**/*.pyc
.pytest_cache
.mypy_cache
coverage.xml
.env
.env.*
!.env.example
*.pem
*.key
data/
notebooks/
.DS_Store

The Effect on Build Speed and Caching

Without .dockerignore: "transferring context: 812MB"   (node_modules, .git, data)
With .dockerignore:    "transferring context: 1.9MB"

Every git commit changes files in .git. Without ignoring it, a COPY . . step misses the cache on every build, even when the application code is unchanged.

Monorepos

With several Dockerfiles in one repository, use per-Dockerfile ignore files (api/Dockerfile.dockerignore next to api/Dockerfile), or set each service’s own subdirectory as the build context. The build context should be as small as possible.

An Allow-List Approach

For strict control, ignore everything and re-include only what the build needs:

*
!src/
!package.json
!package-lock.json

This is safest against accidentally copying new sensitive files, but you must update it when the build needs more files.

When It Matters Less

  • The Dockerfile copies only explicit paths (COPY src/ ./src/) from a clean context, and nothing sensitive is in the directory. Even then, the context is still sent to the builder, so large files still slow builds.

Pitfalls

  • Ignoring files the build needs (lock files, go.sum), causing confusing COPY failures.

  • Assuming .gitignore applies: Docker reads only .dockerignore.

  • Forgetting **/ for nested matches.

  • Relying on it as the only secret protection: keep secrets out of the repository too.

Interview Tips

  • Answer “almost always”, and give the triggers: large directories, secrets, broad COPY, cache invalidation.

  • Mention the allow-list pattern and per-Dockerfile ignore files for monorepos.

  • Show the context size difference as evidence.

41

Why is it advised to run only one process per container?

The guideline is really “one concern per container”: a container should run one main service, such as a web server, a worker or a database, as its PID 1. Docker’s model is built around that main process: - the container lives and dies with it; - docker stop signals it; - its stdout and stderr are the container’s logs; - health checks, restart policies and resource limits apply to the container as one unit.

With one service per container you get independent scaling and deployment (scale workers without scaling the web tier), clear failure handling (a crash restarts the container, instead of a supervisor hiding it), simple logs, smaller and more secure images, and easier reuse. Packing several services in, for example nginx, the app, cron and a database, means you need a process supervisor. You lose signal handling and logging clarity, and you couple lifecycles that should be separate. “One process” is not absolute: apps that fork worker processes (Gunicorn, nginx, PHP-FPM) are fine, and tightly coupled helpers belong in a separate container sharing namespaces, like a Kubernetes sidecar.

Read full answer

Applies toDocker containers and Kubernetes pods

Benefits

Benefit Explanation
Independent scaling Run 10 web containers and 2 worker containers
Independent deployment Update the worker without restarting the web server
Clear health and restarts If the process dies, the container exits and the orchestrator restarts it
Clean logs One stream per service, labelled by container
Proper signals docker stop sends SIGTERM to PID 1, which shuts down gracefully
Smaller images Only one service’s dependencies
Security Smaller attack surface; separate users and privileges per service
Reuse Use the official postgres or redis image instead of bundling them

The Same App, Two Ways

# One concern per container (recommended)
services:
  web:
    image: example/web:2.0.0
  worker:
    image: example/web:2.0.0
    command: ["python", "-m", "worker"]
  scheduler:
    image: example/web:2.0.0
    command: ["python", "-m", "scheduler"]
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: devonly

The alternative, one image running supervisord with nginx, the app, cron and Postgres inside, cannot scale the parts separately, hides crashes, and makes a database upgrade require rebuilding the app image.

The PID 1 Problem

PID 1 has special duties in Linux: it must forward signals and reap zombie processes. Many apps do not do this. Solutions:

# Exec form: the app itself is PID 1 and receives SIGTERM
CMD ["gunicorn", "-b", "0.0.0.0:8000", "app:app"]
# Or let Docker add a tiny init (tini) as PID 1
docker run --init example/web:2.0.0

Shell-form CMD gunicorn ... runs under /bin/sh -c, which may not forward signals, so the container waits for the stop timeout and is killed.

Acceptable Exceptions

Case Approach
App forks its own workers (Gunicorn, nginx, Apache, PHP-FPM) Fine: still one service
Tightly coupled helper (log shipper, proxy, config reloader) Separate container sharing network or volumes (a sidecar)
Legacy app that needs several daemons Supervisor (s6-overlay, supervisord) as a migration step, with signals and logs handled
Short-lived scripts spawning subprocesses Fine; use --init to reap zombies

Pitfalls

  • SSH servers or cron daemons inside app containers.

  • Using supervisord to hide crashes, so the container looks healthy while a service is down.

  • Shell-form commands that break graceful shutdown.

Interview Tips

  • Rephrase as “one concern per container”, tied to lifecycle, logs, signals and scaling.

  • Mention the PID 1 problem and --init/tini.

  • Note forking servers and sidecars as legitimate exceptions.

42

How should you handle logging in Docker containers?

Follow the twelve-factor approach: applications write logs as event streams to stdout and stderr, not to files inside the container. Docker captures those streams through a logging driver, so docker logs works, and a log shipper forwards them to a central system where they can be searched, alerted on and retained. Concretely: - emit structured JSON with consistent fields (timestamp, level, service, trace ID); - configure rotation (local driver, or json-file with max-size and max-file) so logs cannot fill the disk; - choose a driver or agent to ship logs: Fluent Bit, Vector or the OpenTelemetry Collector reading container log files, or drivers such as fluentd, gelf, awslogs, gcplogs and journald; - never log secrets; - disable buffering so logs appear in real time.

Read full answer

Applies toDocker Engine 27+ logging drivers; Kubernetes uses the same stdout model

Application Side

FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1            # flush output immediately
WORKDIR /app
COPY . .
CMD ["gunicorn", "--access-logfile", "-", "--error-logfile", "-", "-b", "0.0.0.0:8000", "app:app"]

- sends Gunicorn’s logs to stdout and stderr. For software that insists on log files, the official nginx image links its log files to the standard streams:

RUN ln -sf /dev/stdout /var/log/nginx/access.log \
 && ln -sf /dev/stderr /var/log/nginx/error.log

Daemon Configuration With Rotation

{
  "log-driver": "local",
  "log-opts": {
    "max-size": "20m",
    "max-file": "5"
  }
}

Put this in /etc/docker/daemon.json and restart the daemon. Existing containers keep their old settings until they are recreated. Per container: docker run --log-driver local --log-opt max-size=10m ....

Logging Drivers

Driver Use docker logs works?
json-file (default) Simple; needs rotation options Yes
local Compact, rotated by default Yes
journald Hosts using systemd; query with journalctl Yes
syslog, gelf, fluentd, awslogs, gcplogs, splunk Direct shipping Yes, through dual logging (local cache), unless disabled
none Discard No

Shipping Logs Centrally

containers -> stdout/stderr -> Docker logging driver (local or json-file)
           -> agent on each host (Fluent Bit / Vector / OTel Collector) tails the log files
           -> parse JSON, add container name, image and labels, redact
           -> Loki / Elasticsearch or OpenSearch / cloud logging / Datadog

Using an agent that reads files is more robust than a remote logging driver. If a remote endpoint is down, some drivers block or drop logs; the mode=non-blocking option with max-buffer-size avoids blocking the application.

Compose Example

services:
  api:
    image: example/api:1.4.0
    logging:
      driver: local
      options:
        max-size: "10m"
        max-file: "3"
    labels:
      com.example.team: payments

Good Log Content

Practice Reason
JSON lines with consistent field names Easy parsing and querying
Trace and request IDs Correlation across services
Meaningful levels Filter noise; alert on errors
No secrets or personal data Logs are widely accessible and retained
One event per line Multi-line stack traces need special parsing; prefer JSON with a stack field

Pitfalls

  • Writing to files inside the container: lost on recreate, invisible to docker logs, and filling the writable layer.

  • No rotation, so the disk fills up and the host fails.

  • Buffered output, so logs appear late or are lost on crashes.

  • A blocking remote logging driver stalling the application when the logging backend fails.

Interview Tips

  • Lead with stdout and stderr, structured logs and central aggregation.

  • Mention logging drivers, rotation and node-level agents.

  • Cover buffering, redaction and non-blocking mode.

43

How would you diagnose high CPU or memory usage in a container?

Work from outside in: 1. Confirm and measure with docker stats (or cAdvisor and Prometheus over time): which container, how much, against which limit, and since when. 2. Look inside with docker top or docker exec ... ps/top to find the process and threads responsible. 3. Check for throttling and OOM events: CPU throttling counters in the container’s cgroup, OOMKilled in docker inspect, kernel messages. 4. Correlate with traffic, deployments and logs: did load rise, or did a release change behaviour? 5. Profile the application with language tools: py-spy, async-profiler or JFR for Java, pprof for Go, node --inspect or clinic for Node.js, or a continuous profiler. 6. Fix and verify: code changes (hot loops, leaks, unbounded caches), configuration (worker counts, heap size), or right-sized limits.

Remember that container memory includes the page cache, so “high memory” may be harmless file cache. Also check that the runtime respects the container’s limits (JVM heap, Node.js heap, Go GOMEMLIMIT).

Read full answer

Applies toDocker Engine 27+ on Linux with cgroups v2

Step 1: Measure

docker stats --no-stream                                   # all containers
docker stats api --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.PIDs}}'
docker inspect -f 'limit={{.HostConfig.Memory}} cpus={{.HostConfig.NanoCpus}} oom={{.State.OOMKilled}} restarts={{.RestartCount}}' api

CPUPerc above 100% means more than one core. A container capped at --cpus 2 peaks at about 200%.

Step 2: Which Process?

docker top api -eo pid,ppid,pcpu,pmem,rss,cmd
docker exec -it api top -H              # per-thread view (if top exists in the image)

Step 3: Throttling, OOM and Memory Breakdown

cid=$(docker inspect -f '{{.Id}}' api)
# cgroup v2 paths (systemd cgroup driver); nr_throttled rising means CPU limits are hit
cat /sys/fs/cgroup/system.slice/docker-$cid.scope/cpu.stat
# anon = application memory; file = page cache (reclaimable)
grep -E '^(anon|file|shmem) ' /sys/fs/cgroup/system.slice/docker-$cid.scope/memory.stat
journalctl -k | grep -i 'out of memory'      # kernel OOM kills

docker stats already subtracts inactive file cache, but memory.stat shows the real split between application memory and cache.

Step 4: Profile

Runtime Tool Example
Python py-spy py-spy top --pid <pid>; py-spy dump --pid <pid>
Java jcmd, JFR, async-profiler jcmd 1 Thread.print; jcmd 1 GC.heap_info; record JFR
Go pprof go tool pprof http://localhost:6060/debug/pprof/profile
Node.js inspector, clinic, heap snapshots node --inspect, --heapsnapshot-signal=SIGUSR2
Any perf, eBPF tools, continuous profilers Pyroscope, Parca

Profilers often need extra capabilities (for example SYS_PTRACE), or must run in a debug container sharing the PID namespace: docker run --pid container:api --cap-add SYS_PTRACE ....

Common Causes

Symptom Likely cause
CPU high, steady, after a release Inefficient code path, busy loop, regex backtracking
CPU high with high GC time Memory pressure; heap too small for the workload
CPU near the limit, latency spikes Throttling: limit too low for bursts
Memory grows steadily until OOM Leak: unbounded caches, listeners, global lists
Memory high but stable Page cache, or a heap sized near the limit (fine if it does not grow)
Many processes Fork bombs, too many workers (--pids-limit helps)
OOM kills with an “unused” heap Runtime not container-aware, or off-heap and native memory

Fixes

  • Code: fix hot paths and leaks; bound caches; stream instead of loading whole files.

  • Configuration: match worker and thread counts to --cpus; size heaps from the limit (-XX:MaxRAMPercentage, GOMEMLIMIT, --max-old-space-size).

  • Limits: raise them if the workload legitimately needs more; scale out instead of up.

  • Monitoring: alert on memory approaching the limit and on throttling, not only on usage.

Interview Tips

  • Describe the flow: docker stats → processes → throttling and OOM → profile → fix.

  • Mention page cache versus application memory and CPU throttling.

  • Name language profilers and container-aware runtime settings.

44

What would you do if a container keeps failing shortly after starting?

Treat it as a crash loop and gather evidence before changing anything: 1. Check its state and exit code with docker ps -a and docker inspect. The exit code narrows the cause: 1 = app error, 126/127 = command not executable or not found, 137 = killed (OOM or SIGKILL), 139 = segfault, 143 = SIGTERM. 2. Read the logs with docker logs. Most failures say why: missing configuration, a refused database connection, permission denied, port in use. 3. Reproduce interactively: run the image with a shell entrypoint (docker run -it --entrypoint sh image) and start the command by hand, or inspect the filesystem. 4. Check the environment: variables, secrets, mounted files and their permissions, user ID, networks and DNS, dependencies’ readiness, resource limits, and health checks that kill it too early. 5. Compare with the last good version (image diff, configuration changes).

Then fix the root cause, such as a retry loop for dependencies, correct configuration, enough memory, or the right platform (amd64 versus arm64). Do not just add restart policies.

Read full answer

Applies toDocker Engine 27+ (similar steps apply to Kubernetes CrashLoopBackOff)

Step 1: State and Exit Code

docker ps -a --filter name=api
docker inspect -f 'exit={{.State.ExitCode}} oom={{.State.OOMKilled}} err="{{.State.Error}}" restarts={{.RestartCount}}' api
docker events --since 10m --filter container=api      # die, oom and restart events with timestamps
Exit code Meaning Typical cause
0 Finished successfully The main process is not long-running (it ran a script and ended)
1 General application error Exception, bad configuration
125 Docker could not run the container Invalid docker run options
126 Command not executable Missing execute permission, wrong file type
127 Command not found Wrong CMD/ENTRYPOINT, missing binary, missing shell in a distroless image
137 SIGKILL OOM kill (check OOMKilled) or a forced stop
139 Segmentation fault Native library crash, wrong CPU architecture or libc mismatch
143 SIGTERM Stopped by Docker or an orchestrator, for example after failing health checks

Step 2: Logs

docker logs --tail 100 api
docker logs --tail 100 --timestamps api 2>&1 | less

If the logs are empty, the process may die before writing anything (exit code 127), or it buffers output (PYTHONUNBUFFERED=1).

Step 3: Reproduce Interactively

docker run --rm -it --entrypoint sh --env-file .env example/api:1.4.0
# inside: check files, permissions, environment, then run the real command manually
ls -la /app; id; env | sort; /app/start.sh

For distroless images, copy the filesystem out (docker create + docker cp), or use docker debug.

Step 4: Common Causes and Fixes

Cause Evidence Fix
Missing environment variable or secret Error about configuration in logs Provide it; validate configuration at start-up with clear messages
Dependency not ready “connection refused” to the database Retry with backoff in the app; Compose depends_on: service_healthy
Out of memory Exit 137, OOMKilled: true Raise the limit or reduce memory use
Wrong architecture exec format error, exit 139 or 1 Build multi-platform images; check docker image inspect -f '{{.Architecture}}'
Permission denied Errors writing to mounted directories Match UID and GID; fix volume ownership
Port already in use “address already in use” Change the port or the conflicting process
Health check too strict Exit 143 after the start period Lengthen start_period or the timeout
Main process exits immediately Exit 0 Run the service in the foreground (nginx -g 'daemon off;')
Bad entrypoint script Exit 126 or 127, r errors Exec permissions; Unix line endings; correct shebang

Step 5: Prevent Recurrence

  • Add start-up validation with clear error messages.

  • Run smoke tests in CI: start the container and probe its health endpoint.

  • Make dependencies tolerant: retry with backoff instead of exiting.

  • Pin base images and dependencies, and keep release notes of configuration changes.

Pitfalls

  • Adding --restart always and hiding the problem behind restarts.

  • Changing several things at once, so the real cause stays unknown.

  • Ignoring exit code 0: the container “succeeds” but the service is not long-running.

Interview Tips

  • Lead with exit code + logs + inspect, then reproduce interactively.

  • Know the exit codes (127, 137, 139, 143).

  • Mention dependency readiness, OOM, architecture and permissions as the common causes.

45

In what scenarios would you prune Docker objects, and how?

Docker never deletes unused objects automatically, so stopped containers, dangling and unused images, unused networks, volumes and build cache accumulate until the disk fills. Prune when: - disk space runs low on developer machines, CI runners or hosts; - CI agents build many images; - after experiments; - on a schedule on build servers.

The commands: - docker container prune: stopped containers; - docker image prune: dangling images, or -a for all images no container uses; - docker network prune and docker volume prune: anonymous volumes by default, -a for unused named ones; - docker builder prune: build cache; - docker system prune, which combines them (-a and --volumes widen it).

Read full answer

Use --filter until=... and labels to limit what is removed, run docker system df first to see where the space goes, and be very careful with volumes: pruning them deletes data permanently.

Applies to: Docker Engine 27+ CLI

See What Uses Space

docker system df          # images, containers, local volumes, build cache: total and reclaimable
docker system df -v       # per object

Prune Commands

Command Removes
docker container prune All stopped containers
docker image prune Dangling images (untagged, <none>)
docker image prune -a All images not used by any container
docker network prune Networks not used by any container
docker volume prune Unused anonymous volumes
docker volume prune -a All unused volumes, including named ones (data loss!)
docker builder prune Dangling build cache; -a for all build cache
docker system prune Stopped containers, unused networks, dangling images, dangling build cache
docker system prune -a --volumes Also all unused images and anonymous volumes

All of these ask for confirmation unless -f is given.

Filters for Safer Pruning

# Images unused and older than 3 days
docker image prune -a --filter "until=72h" -f

# Keep anything labelled keep=true
docker system prune -a --filter "label!=keep=true" -f

# Build cache older than a week
docker builder prune --filter "until=168h" -f

# Keep the build cache under 20 GB (newer BuildKit versions also accept --max-used-space)
docker builder prune --keep-storage 20GB -f

Scenarios

Scenario Approach
Developer laptop full docker system df, then docker system prune -a (and review volumes by hand)
CI runners Scheduled docker system prune -af --filter until=24h and build cache limits; or ephemeral runners that start clean
Production hosts Prune old images (image prune -a --filter until=...) after deployments; never prune volumes automatically
Kubernetes nodes Not by hand: the kubelet’s image garbage collection handles it (imageGCHighThresholdPercent)
Build servers Garbage collection settings for the BuildKit cache in the daemon configuration

Automating on a Host

# /etc/cron.daily/docker-prune (or a systemd timer)
#!/bin/sh
docker image prune -af --filter "until=168h"
docker builder prune -f --filter "until=168h"
docker container prune -f --filter "until=24h"

For build caches, the daemon can also garbage-collect automatically ("builder": {"gc": {"enabled": true, "defaultKeepStorage": "20GB"}} in daemon.json).

Pitfalls

  • --volumes or volume prune -a on a machine with databases: permanent data loss.

  • Pruning images needed for fast rollback on production hosts; keep the last few releases.

  • Pruning during builds on shared CI runners, which deletes cache another job is using.

  • Forgetting the build cache, often the largest consumer of space.

Interview Tips

  • Name the per-object prune commands and docker system prune with -a and --volumes.

  • Recommend docker system df first and filters (until, labels).

  • Warn about volume data loss, and mention automation on CI and kubelet garbage collection.

46

How can you monitor the performance of Docker containers?

Combine quick CLI checks with continuous metrics, logs and traces: - Ad hoc: docker stats for live CPU, memory, network, block I/O and PIDs per container; docker top, docker inspect, docker events and docker system df. - Continuous metrics: cAdvisor exports per-container resource metrics to Prometheus, node-exporter covers the host, the Docker daemon itself exposes Prometheus metrics, and Grafana shows dashboards and Alertmanager sends alerts. Managed alternatives include Datadog, New Relic, Dynatrace, Elastic, and cloud services such as CloudWatch Container Insights. - Application metrics: the apps expose RED metrics (rate, errors, duration) through Prometheus clients or OpenTelemetry. - Logs and traces: central logging and distributed tracing (OpenTelemetry) explain why something is slow.

Watch for CPU throttling, memory near the limit, OOM kills, restarts, and latency and error rates, not only raw usage.

Read full answer

Applies toDocker Engine 27+, Prometheus, cAdvisor, Grafana

Quick Checks

docker stats                                          # live view of all containers
docker stats --no-stream --format '{{.Name}} {{.CPUPerc}} {{.MemUsage}} {{.NetIO}} {{.BlockIO}}'
docker events --filter event=oom --filter event=die   # live crash and OOM events

A Monitoring Stack With Compose

services:
  cadvisor:
    image: gcr.io/cadvisor/cadvisor:v0.49.1
    privileged: true
    devices:
      - /dev/kmsg
    volumes:
      - /:/rootfs:ro
      - /var/run:/var/run:ro
      - /sys:/sys:ro
      - /var/lib/docker/:/var/lib/docker:ro
    ports:
      - "8080:8080"
  node-exporter:
    image: prom/node-exporter:v1.8.2
    pid: host
    volumes:
      - /:/host:ro,rslave
    command: ["--path.rootfs=/host"]
  prometheus:
    image: prom/prometheus:v2.54.1
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
    ports:
      - "9090:9090"
  grafana:
    image: grafana/grafana:11.2.0
    ports:
      - "3000:3000"
# prometheus.yml
scrape_configs:
  - job_name: cadvisor
    static_configs:
      - targets: ["cadvisor:8080"]
  - job_name: node
    static_configs:
      - targets: ["node-exporter:9100"]
  - job_name: docker-daemon
    static_configs:
      - targets: ["host.docker.internal:9323"]

The daemon metrics need "metrics-addr": "0.0.0.0:9323" in daemon.json (restrict access to that port). On Linux, host.docker.internal must be mapped with extra_hosts: ["host.docker.internal:host-gateway"]. cAdvisor needs broad host access, so run it only on trusted hosts and do not expose its port publicly.

Key Metrics and Queries

Signal cAdvisor metric Alert idea
CPU usage container_cpu_usage_seconds_total Sustained near the limit
CPU throttling container_cpu_cfs_throttled_periods_total Throttled share of periods above about 25%
Memory working set container_memory_working_set_bytes Above 90% of container_spec_memory_limit_bytes
OOM events container_oom_events_total Any increase
Network container_network_receive_bytes_total and transmit Unusual spikes or drops
Disk I/O container_fs_reads_bytes_total and writes Saturation
Restarts Docker events, or kube_pod_container_status_restarts_total in Kubernetes Crash loops
sum by (name) (rate(container_cpu_usage_seconds_total{name!=""}[5m]))

This gives CPU cores used per container over the last 5 minutes.

Beyond Resource Metrics

Layer Tooling
Application RED metrics Prometheus client libraries, OpenTelemetry metrics
Traces OpenTelemetry with Jaeger or Tempo
Logs Loki, OpenSearch, cloud logging
Profiles Pyroscope, Parca
SLOs and alerts Burn-rate alerts on latency and errors

Resource graphs show that a container is busy; application metrics and traces show whether users are affected and why.

Pitfalls

  • Only watching averages and missing p99 latency or short CPU spikes.

  • Ignoring throttling: a container at its CPU limit looks fine at 100% while its latency suffers.

  • High-cardinality labels (container IDs that churn) overloading Prometheus; aggregate by service.

  • No monitoring of the host (disk full, kernel OOM) under the containers.

Interview Tips

  • Mention docker stats for quick checks and cAdvisor + Prometheus + Grafana for continuous monitoring.

  • Highlight throttling, memory versus limit, OOM and restarts.

  • Add application metrics, logs and traces for a complete picture.

47

What common issues arise when using Docker in a CI/CD pipeline?

Common problems with Docker in CI/CD fall into a few groups: - Slow builds: no layer cache on fresh runners, large build contexts, poor Dockerfile ordering. - Docker access inside CI: Docker-in-Docker needs privileged mode; mounting the host socket is a security risk. - Registry limits and authentication: Docker Hub pull rate limits, expired tokens. - Non-reproducible builds: floating latest base images, unpinned dependencies. - Multi-architecture issues: images built on amd64 runners failing on arm64 servers. - Secrets leaking into images or build logs. - Disk space filling up on persistent runners. - Flaky integration tests: services not ready, port clashes, timing. - Promotion problems: rebuilding for each environment instead of promoting one image.

The remedies are remote BuildKit caching, rootless or daemonless builders, authenticated pulls through a mirror, pinned versions and digests, buildx multi-platform builds, secret mounts, pruning or ephemeral runners, health-based waits and Testcontainers, and build once, promote by digest.

Read full answer

Applies toDocker BuildKit/buildx in CI (GitHub Actions, GitLab CI, Jenkins and similar)

Issues and Fixes

Issue Symptom Fix
No cache on ephemeral runners Every build installs all dependencies --cache-from and --cache-to with a registry or the CI cache (type=gha); good layer order
Large build context “transferring context: 900MB” .dockerignore; narrower context directory
Docker-in-Docker Needs --privileged; nested storage problems Rootless BuildKit, Kaniko or Buildah, or remote builders
Mounting /var/run/docker.sock Jobs can control the host and other jobs’ containers Isolated runners; avoid on shared runners
Pull rate limits toomanyrequests errors Authenticate; registry mirror or pull-through cache
Floating base images Builds change without code changes Pin versions or digests; Renovate for updates
Wrong architecture exec format error on deploy docker buildx build --platform linux/amd64,linux/arm64
Secrets in images or logs Tokens visible in docker history or job logs RUN --mount=type=secret; masked CI variables; no ARG for secrets
Disk full on runners “no space left on device” Scheduled pruning; cache size limits; ephemeral runners
Flaky integration tests Tests fail when the database is not ready Health checks with docker compose up --wait; Testcontainers waits; random ports
Rebuilding per environment Staging and production run different bytes Build once; tag with the SHA; promote the same digest
Slow image pushes and pulls Long deploys Smaller images; registry close to runners and clusters
Time zone and clock issues, non-root permissions File ownership errors on mounted workspaces Match UIDs; avoid writing to bind-mounted workspaces from root containers

A Cache-Friendly CI Build (GitHub Actions)

name: image
on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4
      - uses: docker/setup-qemu-action@v3
      - uses: docker/setup-buildx-action@v3
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: docker/build-push-action@v6
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ghcr.io/example/api:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          secrets: |
            npm_token=${{ secrets.NPM_TOKEN }}

Integration Tests Without Flakiness

docker compose -f compose.ci.yaml up -d --wait     # waits until health checks pass
docker compose -f compose.ci.yaml run --rm tests
docker compose -f compose.ci.yaml down -v

--wait relies on health checks in the Compose file. Without them, Compose only waits until the containers are running.

Pitfalls

  • Testing one image and deploying a rebuilt one.

  • Privileged Docker-in-Docker on shared runners.

  • Ignoring cache and context size until builds take 20 minutes.

  • Hard-coded host ports clashing when jobs run in parallel on one runner.

Interview Tips

  • Group the issues: speed, security, reproducibility, platform and test stability.

  • Give a concrete fix for each: remote cache, rootless builders, pinning, buildx, secret mounts, --wait.

  • Stress build once, promote by digest.

48

How do you define a multi-container application with docker-compose?

Write a compose.yaml file in the project root. Under services:, define each container: its image (or build: context), ports, environment, volumes, networks, depends_on with health conditions, healthcheck, command, restart policy and resource limits. Declare shared volumes:, networks:, secrets: and configs: at the top level. Compose creates a default network in which services reach each other by service name. docker compose up -d builds and starts everything in dependency order, and docker compose down removes it. Use .env files for variable substitution, override files (compose.override.yaml) for local and CI differences, and profiles for optional services.

Read full answer

Applies toDocker Compose v2 (Compose Specification)

Example: Web App, API, Worker, Postgres and Redis

name: shop

services:
  web:
    build:
      context: ./web
      args:
        API_URL: http://localhost:8000
    ports:
      - "3000:3000"
    depends_on:
      - api

  api:
    build: ./api
    image: ghcr.io/example/shop-api:${API_TAG:-dev}
    ports:
      - "8000:8000"
    env_file: .env
    environment:
      DATABASE_URL: postgres://shop:${DB_PASSWORD}@db:5432/shop
      REDIS_URL: redis://cache:6379/0
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_started
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health')"]
      interval: 10s
      start_period: 15s
    restart: unless-stopped

  worker:
    image: ghcr.io/example/shop-api:${API_TAG:-dev}
    command: ["python", "-m", "worker"]
    env_file: .env
    depends_on:
      api:
        condition: service_healthy
    deploy:
      replicas: 2

  db:
    image: postgres:17
    environment:
      POSTGRES_USER: shop
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: shop
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U shop"]
      interval: 5s
      retries: 10

  cache:
    image: redis:7.4
    volumes:
      - redisdata:/data

  adminer:
    image: adminer:4.8.1
    ports:
      - "8081:8080"
    profiles: ["tools"]

volumes:
  pgdata: {}
  redisdata: {}
# .env (git-ignored; Compose reads it automatically for ${...} substitution)
DB_PASSWORD=devonly
API_TAG=dev

Running It

docker compose up -d --build           # build images and start everything
docker compose ps                      # status and health
docker compose logs -f api worker
docker compose --profile tools up -d   # also start adminer
docker compose exec db psql -U shop
docker compose down                    # stop and remove containers and networks (volumes kept)

Key Elements

Element Purpose
services One entry per container type
build / image Build from a Dockerfile, or use (and tag) an image
ports Publish to the host (host:container)
environment, env_file Configuration
volumes Named volumes for data, bind mounts for development
depends_on + condition Start order and readiness (service_healthy, service_completed_successfully)
healthcheck Readiness checks used by depends_on and up --wait
networks Custom networks for isolation (a default network exists anyway)
profiles Optional services
deploy Replicas and resource limits
name Project name (prefix of containers, networks and volumes)

Variations per Environment

# compose.yaml + compose.override.yaml are merged automatically (local development)
docker compose up -d
# Explicit files for CI
docker compose -f compose.yaml -f compose.ci.yaml up -d --wait

Compose v2.20+ also supports include: to combine Compose files from several directories.

Pitfalls

  • depends_on without conditions, which only orders start-up and does not wait for readiness.

  • Secrets committed in compose.yaml or .env.

  • localhost between services: use service names.

  • The obsolete version: key: it is ignored and can be removed.

Interview Tips

  • Describe services, volumes and networks in one YAML file and docker compose up.

  • Mention service-name DNS, health-based depends_on, .env interpolation, profiles and overrides.

  • Show up, ps, logs, exec and down.

49

What should you consider when deploying Docker containers in production?

Running containers in production is about much more than docker run. The main considerations: - Orchestration and availability: Kubernetes, ECS or Swarm for scheduling, self-healing, rolling updates and multiple replicas across zones. - Image quality: minimal, pinned, scanned and signed images, deployed by digest. - Security: non-root users, dropped capabilities, read-only filesystems, seccomp, network policies, secrets from a secret manager, a protected Docker socket. - Resources: CPU and memory requests and limits; runtimes tuned to them. - Configuration: from the environment or mounted files, not baked into images. - State: stateless containers; data in managed databases or persistent volumes with backups. - Observability: logs to stdout shipped centrally, metrics, traces, health checks and alerts. - Networking: TLS at the edge, internal service discovery, load balancing. - Operations: CI/CD with progressive rollout and rollback, graceful shutdown, patching hosts and images, capacity planning and cost.

Read full answer

Applies tocontainerised production workloads (Docker images on Kubernetes, ECS or Swarm)

Checklist

Area Considerations
Images Small base images, multi-stage builds, pinned versions, SBOM, vulnerability scanning, signing, immutable tags and digests
Runtime security Non-root (USER), --cap-drop ALL, no-new-privileges, read-only root filesystem, seccomp and AppArmor defaults, no --privileged, never expose the Docker socket
Secrets Secret managers or orchestrator secrets mounted as files; rotation; nothing in images or Git
Resources Requests and limits; container-aware runtimes; autoscaling; capacity headroom
Health Liveness, readiness and startup checks (HEALTHCHECK or Kubernetes probes)
Availability Multiple replicas across zones, disruption budgets, no single points of failure
Deployments Rolling, canary or blue-green; automatic rollback; backward-compatible database migrations
Shutdown Handle SIGTERM, drain connections, sensible grace periods, exec-form CMD or --init
State and data Stateless app containers; managed databases or volumes with replication; tested backups
Configuration Twelve-factor configuration per environment; same image everywhere
Networking TLS termination, internal-only services, network policies, rate limiting
Observability Structured logs to stdout with rotation and shipping, Prometheus metrics, traces, dashboards, SLO alerts
Host and platform Patched hosts and Docker or containerd versions, minimal host OS, time sync, disk monitoring, log rotation
Compliance and cost Audit logs, data residency, right-sizing, image retention policies

A Production-Minded Run (Single Host Example)

docker run -d --name api \
  --restart unless-stopped \
  --user 10001:10001 \
  --read-only --tmpfs /tmp \
  --cap-drop ALL --security-opt no-new-privileges \
  --memory 512m --cpus 1 --pids-limit 256 \
  --log-driver local --log-opt max-size=20m --log-opt max-file=5 \
  --health-cmd "/app/healthcheck" --health-interval 15s --health-start-period 20s \
  --env-file /etc/api/env \
  -p 127.0.0.1:8000:8000 \
  ghcr.io/example/api@sha256:3f1c0d9e8b7a6c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d

The port is bound to 127.0.0.1, with a reverse proxy such as nginx or Caddy handling TLS in front. Be aware that published ports bypass host firewalls like ufw on Linux, because Docker writes its own iptables rules.

Single Host or Orchestrator?

Single host (Compose, docker run) Orchestrator (Kubernetes, ECS, Swarm)
Simple, cheap Self-healing across machines
A host failure means downtime Multiple nodes and zones
Manual or scripted deploys Rolling updates, autoscaling, declarative state
Fine for small internal tools Standard for customer-facing services

Pitfalls

  • latest tags and rebuilding images per environment.

  • Unrotated logs filling disks.

  • Containers as pets: fixing them by hand with docker exec.

  • Databases in containers without a backup and recovery plan.

  • Docker’s iptables rules exposing ports that the host firewall appears to block.

Interview Tips

  • Structure the answer as images, security, resources, availability, data, observability and operations.

  • Mention orchestration, digest pinning, non-root, health checks and graceful shutdown.

  • Note the iptables or firewall gotcha and stateless containers.

50

Explain the process of integrating Docker with a continuous integration system.

Integrating Docker with CI means every change produces a tested, scanned, versioned image. The usual pipeline: 1. Check out the code on a runner that can build images (a Docker daemon, BuildKit, or a daemonless builder such as Buildah or Kaniko). 2. Lint the Dockerfile (Hadolint). 3. Build with BuildKit/buildx, using a remote layer cache, and inject secrets with secret mounts. 4. Run tests inside or against the image: unit tests in a build stage, then integration tests with dependencies started by Docker Compose or Testcontainers. 5. Scan the image for vulnerabilities and secrets, and generate an SBOM. 6. Tag it with the Git SHA, plus a version for releases. 7. Push it to a registry, and sign it (Cosign) with provenance attestations. 8. Hand the digest to the CD stage.

The principles: the same image is tested and deployed, builds are reproducible and cached, and credentials stay out of images and logs.

Read full answer

Applies toGitHub Actions, GitLab CI, Jenkins, CircleCI and similar, with Docker BuildKit

Pipeline Stages

push / PR -> lint (hadolint) -> build image (buildx + cache) -> unit tests (target: test)
          -> integration tests (compose --wait or Testcontainers) -> scan (Trivy) + SBOM
          -> push :<sha> (main branch only) -> sign + attest -> output digest for CD

Dockerfile With a Test Stage

# syntax=docker/dockerfile:1
FROM python:3.12-slim AS base
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

FROM base AS test
COPY requirements-dev.txt .
RUN pip install --no-cache-dir -r requirements-dev.txt
COPY . .
RUN pytest -q

FROM base AS runtime
COPY . .
USER 10001
CMD ["gunicorn", "-b", "0.0.0.0:8000", "app:app"]

docker build --target test . runs the tests in the build, and the runtime image contains no test dependencies.

GitLab CI Example

stages: [build, test, scan, publish]

variables:
  IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA

build:
  stage: build
  image: docker:27
  services: ["docker:27-dind"]
  script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" "$CI_REGISTRY"
    - docker buildx create --use
    - docker buildx build --target test --cache-from type=registry,ref=$CI_REGISTRY_IMAGE:cache .
    - >
      docker buildx build --target runtime
      --cache-from type=registry,ref=$CI_REGISTRY_IMAGE:cache
      --cache-to type=registry,ref=$CI_REGISTRY_IMAGE:cache,mode=max
      -t "$IMAGE" --push .

integration:
  stage: test
  image: docker:27
  services: ["docker:27-dind"]
  script:
    - docker compose -f compose.ci.yaml up -d --wait
    - docker compose -f compose.ci.yaml run --rm tests
  after_script:
    - docker compose -f compose.ci.yaml down -v

scan:
  stage: scan
  image:
    name: aquasec/trivy:0.56.2
    entrypoint: [""]
  script:
    - trivy image --exit-code 1 --severity CRITICAL --ignore-unfixed "$IMAGE"

Docker-in-Docker (dind) needs privileged runners. Where that is not allowed, use Kaniko, Buildah or a remote BuildKit service. In practice, the scan job also needs registry credentials to pull a private image.

Good Practices

Practice Why
Remote cache (type=registry or type=gha) Fast builds on ephemeral runners
Tests in a build stage, or against the built image Test what will ship
Health-based waits (compose up --wait) Stable integration tests
Push only from protected branches Unreviewed code never reaches the registry
SHA tags + digests passed to CD Traceability; no rebuilds
Secret mounts and masked variables No credentials in layers or logs
Scan gates on fixable critical issues Security without blocking on noise
Clean up (down -v, ephemeral runners) No leftovers between jobs

Pitfalls

  • Rebuilding the image in the deploy stage instead of promoting the tested one.

  • Privileged runners shared between projects.

  • No cache, so builds take many minutes.

  • Tests that depend on fixed host ports, colliding on shared runners.

Interview Tips

  • Walk through build → test → scan → tag → push → sign.

  • Mention BuildKit caching, test stages, Compose or Testcontainers, and DinD versus daemonless builders.

  • Stress build once, deploy the same digest.

51

How would you migrate an on-premise application to Docker?

Migrate in phases, reducing risk at each step: 1. Assess the application. Map its components (web, workers, scheduled jobs), runtime and OS dependencies, configuration and secrets, state (local files, sessions, databases), network dependencies (other systems, licences tied to hosts or IPs), and non-functional needs. 2. Make it container-friendly, ideally following twelve-factor practices: configuration from the environment, logs to stdout, stateless processes with state moved to databases, object storage or volumes, a health endpoint, and graceful shutdown. 3. Containerise: write Dockerfiles (one service per container), pin versions, and build images in CI. 4. Recreate the environment locally and in test with Compose, including dependencies. 5. Migrate data and integrations, and test functionally, for performance, security and failover. 6. Choose the runtime (a single host with Compose, Kubernetes, ECS) and add observability. 7. Cut over gradually (parallel run, canary or the strangler pattern), with a rollback plan. 8. Decommission the old servers once stable.

Read full answer

Applies tocontainerising existing (legacy) applications

Assessment Checklist

Question Why it matters
Which OS, runtime and library versions? Choose base images; find old runtimes that need upgrading
Does it write to local disk? (uploads, sessions, caches, logs) Must move to volumes, object storage, Redis or stdout
How is it configured? (files, registry, hard-coded paths) Externalise into environment variables or mounted files
Scheduled jobs (cron)? Separate containers or scheduler jobs
Inbound and outbound connections? Firewall rules by IP? Container IPs change; update allow lists
Licensing tied to MAC addresses or hostnames? May block containerisation
Does it need special hardware or kernel modules? May not fit containers
Windows-only components? Windows containers or refactoring

Typical Refactors

Legacy behaviour Container-friendly change
Config file edited on the server Template from environment variables, or a mounted config file
Logs written to /var/log/app Log to stdout; ship centrally
User uploads on local disk Object storage (S3-compatible) or a shared volume
In-memory or file sessions Redis or database sessions, so any replica can serve
Cron on the same server Separate scheduled container or CronJob
Several daemons on one VM One container per service
Starts as a background daemon Run in the foreground as PID 1

Example Dockerfile for a Legacy PHP App

FROM php:8.3-apache
RUN apt-get update \
 && apt-get install -y --no-install-recommends libpq-dev \
 && docker-php-ext-install pdo_pgsql opcache \
 && rm -rf /var/lib/apt/lists/*
COPY docker/php.ini /usr/local/etc/php/conf.d/app.ini
COPY . /var/www/html/
RUN chown -R www-data:www-data /var/www/html/storage
ENV APACHE_DOCUMENT_ROOT=/var/www/html/public
RUN sed -ri 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
HEALTHCHECK CMD curl -fsS http://localhost/health || exit 1

The official php:apache image already includes curl and runs Apache in the foreground.

Cut-Over Strategies

Strategy How
Parallel run Containers serve a copy of the traffic, or internal users, while the old system stays primary
Canary Route a small percentage of traffic to containers; increase gradually
Strangler pattern Move one component or route at a time behind a proxy
Big bang with rollback Switch DNS or the load balancer in a maintenance window; keep the old servers ready

Migrate the database separately, often to a managed service, with replication to keep downtime short.

Pitfalls

  • “Lift and shift” without fixing state: local files disappear with each redeploy.

  • Giant images that copy a whole VM’s software.

  • Running as root because the old app expected it.

  • Missing operational parity: no monitoring, backups or runbooks in the new environment.

  • Underestimating integration dependencies: IP allow lists, mounted network shares, licence servers.

Interview Tips

  • Present it as assess → refactor for twelve-factor → containerise → test → deploy gradually → decommission.

  • Highlight state, configuration and logging changes.

  • Mention cut-over strategies and rollback.

52

How do you automate Docker container deployment with a CI/CD pipeline?

Automate it as a pipeline from commit to running containers, where the CI stage builds, tests, scans and pushes an immutable image tagged with the Git SHA, and the CD stage deploys that exact image (by digest) to each environment in turn. Deployment can be push-based: the pipeline runs kubectl apply, helm upgrade, an ECS service update, or docker compose/docker stack deploy over SSH. Or it can be pull-based (GitOps): the pipeline updates the image tag in a Git repository, and Argo CD or Flux syncs the cluster. Promotion is gated: automatic to dev or staging, then approval or automated checks for production. Rollouts are progressive (rolling, canary, blue-green) with health checks and automatic rollback. Secrets come from the CI secret store or a secret manager, and every step is auditable.

Read full answer

Applies toGitHub Actions example; the same design works with GitLab CI, Jenkins, Azure DevOps and others

Pipeline Overview

commit -> CI: build, test, scan, push ghcr.io/example/api:<sha> (digest recorded)
       -> deploy to staging (automatic) -> smoke tests
       -> manual approval or automated checks
       -> deploy to production (canary 10% -> 50% -> 100%, automatic rollback on errors)

GitHub Actions: Build Then Deploy to Kubernetes

name: deliver
on:
  push:
    branches: [main]
jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    outputs:
      digest: ${{ steps.push.outputs.digest }}
    steps:
      - uses: actions/checkout@v4
      - uses: docker/setup-buildx-action@v3
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - id: push
        uses: docker/build-push-action@v6
        with:
          push: true
          tags: ghcr.io/example/api:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

  deploy-staging:
    needs: build
    runs-on: ubuntu-latest
    environment: staging
    steps:
      - uses: azure/setup-kubectl@v4
      - run: |
          echo "${{ secrets.STAGING_KUBECONFIG }}" > kubeconfig
          export KUBECONFIG=$PWD/kubeconfig
          kubectl -n shop set image deployment/api api=ghcr.io/example/api@${{ needs.build.outputs.digest }}
          kubectl -n shop rollout status deployment/api --timeout=5m

  deploy-production:
    needs: [build, deploy-staging]
    runs-on: ubuntu-latest
    environment: production          # required reviewers configured on this environment
    steps:
      - uses: azure/setup-kubectl@v4
      - run: |
          echo "${{ secrets.PROD_KUBECONFIG }}" > kubeconfig
          export KUBECONFIG=$PWD/kubeconfig
          kubectl -n shop set image deployment/api api=ghcr.io/example/api@${{ needs.build.outputs.digest }}
          kubectl -n shop rollout status deployment/api --timeout=10m || { kubectl -n shop rollout undo deployment/api; exit 1; }

Prefer OIDC federation to cloud providers (short-lived credentials) over long-lived kubeconfig secrets where possible.

GitOps Alternative

# CI updates the desired state in the deployment repository instead of touching the cluster
cd deploy-repo/apps/api/overlays/staging
kustomize edit set image ghcr.io/example/api=ghcr.io/example/api@sha256:...
git commit -am "api: deploy ${GITHUB_SHA}" && git push
# Argo CD or Flux notices the commit and syncs the cluster
Push-based Pull-based (GitOps)
The pipeline needs cluster credentials The cluster pulls; no inbound credentials
Simple to start Git history is the audit log; drift is corrected
State can drift from Git Easy rollbacks with git revert

Deploying to Simpler Targets

Target Automation
Single host with Compose Pipeline runs docker compose pull && docker compose up -d over SSH (or with a Docker context)
Docker Swarm docker stack deploy against a manager
Amazon ECS Register a new task definition and update the service (CodeDeploy for blue-green)
Cloud Run, App Service gcloud run deploy --image ..., az webapp config container set ...

Safety Features

  • Health checks and readiness probes gate traffic.

  • Progressive delivery: Argo Rollouts or Flagger canaries with metric analysis, or blue-green switches.

  • Automatic rollback when a rollout fails or metrics degrade.

  • Backward-compatible database migrations (expand and contract), run as a separate step.

  • Environment protection: approvals, deployment windows, concurrency limits.

Pitfalls

  • Deploying latest, which makes rollbacks and audits impossible.

  • Rebuilding per environment.

  • Long-lived, broad credentials in CI secrets.

  • No rollout status check, so the pipeline reports success while pods crash-loop.

Interview Tips

  • Describe CI builds an immutable image; CD promotes the same digest through environments.

  • Compare push-based deploys with GitOps.

  • Mention approvals, progressive delivery, rollout checks and rollback.

53

When would you use a bind mount over a volume?

A bind mount maps a specific host path into the container. A volume is storage managed by Docker in its own area, or by a volume driver. Use a bind mount when the container must work with files the host owns or edits: - local development: mount the source code so edits appear instantly, with hot reload; - host configuration files such as nginx.conf or TLS certificates managed on the host; - sharing output with the host: build artifacts, reports, test results in CI; - access to host resources such as sockets or device files (with care).

Use a volume for application data the container owns: databases, uploads, caches. Volumes are portable, independent of the host’s directory layout, easier to back up and migrate, can be pre-populated from the image, and perform better on Docker Desktop (macOS and Windows), where bind mounts cross a VM boundary.

Read full answer

Applies toDocker Engine 27+ and Docker Compose v2

Comparison

Aspect Bind mount Volume
Location Any host path you choose Docker-managed (/var/lib/docker/volumes/...) or a driver
Created by You (the path must exist for --mount) Docker, automatically if missing
Portability Depends on the host’s directory structure Portable across hosts and environments
Initial content Hides the container’s files at that path An empty volume is pre-filled from the image’s files at that path
Performance on Docker Desktop Slower (file sharing across the VM), improved by VirtioFS and synchronised file shares Fast (inside the VM)
Management Normal host tools docker volume commands, drivers, backups
Security Container can change host files; risky for sensitive paths Isolated from the host filesystem layout
Typical use Source code, config files, CI output Databases, persistent app data

Examples

# Bind mount: live code reloading in development
docker run --rm -it -p 8000:8000 \
  --mount type=bind,source="$PWD"/src,target=/app/src \
  example/api:dev

# Bind mount: host-managed config, read-only
docker run -d -p 443:443 \
  -v /etc/myapp/nginx.conf:/etc/nginx/nginx.conf:ro \
  -v /etc/letsencrypt:/etc/letsencrypt:ro \
  nginx:1.27

# Volume: database data
docker run -d -e POSTGRES_PASSWORD=devonly \
  --mount type=volume,source=pgdata,target=/var/lib/postgresql/data \
  postgres:17

In Compose

services:
  api:
    build: .
    volumes:
      - ./src:/app/src               # bind mount (path with ./ or /)
      - ./config/app.yaml:/etc/app/app.yaml:ro
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: devonly
    volumes:
      - pgdata:/var/lib/postgresql/data   # named volume
volumes:
  pgdata: {}

Compose also offers develop.watch (docker compose watch), which syncs changed files into the container. That avoids bind-mount performance problems on Docker Desktop.

Decision Guide

Need Use
Edit code on the host, see changes in the container Bind mount (or Compose watch)
Host-managed config or certificates Bind mount, read-only (:ro)
Get build or test output onto the host Bind mount
Database or upload storage Volume
Data that must move between hosts or be backed up with Docker tooling Volume
Kubernetes production Neither directly: PersistentVolumes; hostPath only for special cases

Pitfalls

  • Bind-mounting over a directory that has files in the image (for example /app), which hides them, including installed node_modules.

  • UID and GID mismatches: files created by the container are owned by root on the host, or the container cannot write.

  • Bind-mounting sensitive host paths (/, /etc, /var/run/docker.sock) into untrusted containers.

  • Using bind mounts for production databases, tying data to one host’s path layout.

Interview Tips

  • Summarise: bind mounts for host-owned files (development, config); volumes for container-owned data.

  • Mention pre-population, Docker Desktop performance and security.

  • Note :ro and Compose watch.

54

How do you create a Docker volume, and what is its lifecycle?

Create a volume explicitly with docker volume create <name>, optionally with a driver and driver options (for example NFS) and labels. Volumes are also created implicitly: by docker run -v name:/path or --mount source=name,... when the name does not exist yet, as anonymous volumes from a Dockerfile VOLUME instruction or -v /path, and by Docker Compose from its top-level volumes: key. The lifecycle is independent of containers: 1. create; 2. mount into one or more containers. An empty volume is pre-populated with the image’s files at that path the first time; 3. use: data persists across container restarts, recreations and image upgrades; 4. unmount when containers are removed. The volume stays; 5. inspect, back up, migrate; 6. remove explicitly with docker volume rm, docker volume prune, docker rm -v for anonymous volumes, or docker compose down -v.

Docker never deletes a named volume unless you ask it to.

Read full answer

Applies toDocker Engine 27+ and Docker Compose v2

Creating Volumes

docker volume create appdata
docker volume create --label team=payments --label env=dev appdata2

# NFS-backed volume with the built-in local driver
docker volume create --driver local \
  --opt type=nfs --opt o=addr=10.0.0.5,rw,nfsvers=4 --opt device=:/exports/app \
  nfsdata

docker volume ls
docker volume inspect appdata       # driver, mountpoint, labels, created time

Lifecycle Walkthrough

# 1-2. Mount into a container (the volume would be created here if it did not exist)
docker run -d --name db -e POSTGRES_PASSWORD=devonly -v appdata:/var/lib/postgresql/data postgres:17

# 3. Data survives restarts and recreation
docker restart db
docker rm -f db
docker run -d --name db -e POSTGRES_PASSWORD=devonly -v appdata:/var/lib/postgresql/data postgres:17

# 4. Remove the container: the volume remains
docker rm -f db
docker volume ls --filter name=appdata

# 5. Back up through a helper container
docker run --rm -v appdata:/data:ro -v "$PWD":/backup alpine:3.20 tar czf /backup/appdata.tgz -C /data .

# 6. Delete when no longer needed
docker volume rm appdata

docker volume rm fails while a container, even a stopped one, still references the volume.

Lifecycle Stages

Stage Commands and behaviour
Create docker volume create; implicitly on first use; Compose volumes:
Populate First mount of an empty volume copies the image’s files at the mount path (volumes only, not bind mounts; disable with volume-nocopy)
Use Mounted read-write or read-only (:ro) in any number of containers
Persist Survives docker stop, docker rm, image upgrades, daemon restarts
Inspect docker volume inspect, docker system df -v
Back up or migrate Helper containers with tar; driver snapshots; application dumps
Remove docker volume rm, docker volume prune (anonymous by default; -a for all unused), docker rm -v (anonymous volumes of that container), docker compose down -v

Named Versus Anonymous Volumes

Named Anonymous
Created by docker volume create, -v name:/path VOLUME in a Dockerfile, -v /path
Name Chosen by you Random 64-character ID
Reuse Easy to remount Hard to find; new one per container
Cleanup Manual docker run --rm removes them with the container; docker volume prune

In Compose

services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: devonly
    volumes:
      - pgdata:/var/lib/postgresql/data
volumes:
  pgdata:
    labels:
      backup: daily

Compose names it <project>_pgdata. docker compose down keeps it; docker compose down -v deletes it. external: true makes Compose use an existing volume without managing it.

Pitfalls

  • Accidental deletion with down -v or volume prune -a.

  • Orphaned anonymous volumes piling up from images with VOLUME instructions.

  • Assuming volumes are replicated: a local volume lives on one host.

  • Copying live database files for backups instead of using dumps or stopping the database.

Interview Tips

  • Show docker volume create, plus implicit creation on first use.

  • Explain that the lifecycle is independent of containers, including pre-population and explicit removal.

  • Compare named and anonymous volumes, and mention backups and drivers.

55

What strategies would you use for data persistence in Docker clusters?

In a cluster, a container can be rescheduled to any node, so local volumes, which live on one host, are not enough on their own. Strategies, from most to least recommended for critical data: 1. Keep containers stateless and put state in managed services: cloud databases (RDS, Cloud SQL), object storage (S3, GCS), managed caches and queues. This is the simplest and most reliable option. 2. Network-attached persistent volumes provisioned through CSI drivers: cloud block disks (EBS, Persistent Disk, Azure Disk) attached to whichever node runs the container, or shared file systems (NFS, EFS, Azure Files) for multi-node access. In Kubernetes these are PersistentVolumeClaims with StorageClasses. In Swarm, they are volume plugins or CSI. 3. Replicated storage systems: Ceph/Rook, Longhorn, Portworx. 4. Application-level replication: databases deployed with StatefulSets and operators (CloudNativePG, Strimzi for Kafka) that replicate data between instances on node-local disks. 5. Node pinning with local volumes, with placement constraints and backups. This is acceptable only for non-critical or self-replicating data.

Every strategy needs backups, restore tests, and a plan for zone failures.

Read full answer

Applies toKubernetes 1.30+ (CSI, StatefulSets) and Docker Swarm

Strategy Comparison

Strategy Survives node loss? Multi-node access Performance Complexity
Managed database or object storage Yes (provider-managed HA) Yes Good Lowest for the team
Network block volume (EBS, PD) via CSI Yes, reattached on another node (same zone) Single writer (ReadWriteOnce) Good Low
Shared file system (NFS, EFS, Azure Files) Yes Many readers and writers (ReadWriteMany) Lower; latency for small files Low to medium
Distributed storage (Ceph/Rook, Longhorn) Yes (replicated) Depends Varies High
Database replication with an operator, local disks Yes, via replicas Through the database Best Medium (operator knowledge)
Node-pinned local volume No No Best Low, but fragile

Kubernetes: StatefulSet With Persistent Volumes

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
spec:
  serviceName: postgres
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
        - name: postgres
          image: postgres:17
          env:
            - name: PGDATA
              value: /var/lib/postgresql/data/pgdata
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: pg-secret
                  key: password
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: gp3
        resources:
          requests:
            storage: 50Gi

Each replica gets its own claim (data-postgres-0), which follows the pod when it is rescheduled. For production Postgres, an operator such as CloudNativePG adds replication, failover and backups.

Docker Swarm Options

services:
  db:
    image: postgres:17
    volumes:
      - dbdata:/var/lib/postgresql/data
    deploy:
      placement:
        constraints: ["node.labels.storage == ssd"]
volumes:
  dbdata:
    driver: local
    driver_opts:
      type: nfs
      o: addr=10.0.0.5,rw,nfsvers=4
      device: ":/exports/dbdata"

The volume is mounted from NFS on whichever node runs the task, or the task can be pinned to a labelled node. Running databases on NFS needs care: performance and locking semantics vary.

Backups and Recovery

Data type Backup approach
Relational databases Logical dumps plus continuous WAL or binlog archiving (point-in-time recovery) to object storage
Volumes CSI snapshots (VolumeSnapshot), Velero for cluster resources and volumes
Object storage Versioning, replication across regions, lifecycle rules
Everything Regular restore tests, offsite copies, documented RPO and RTO

Design Principles

  • Separate compute from state: app containers stay disposable.

  • Know the access modes: most block volumes are single-node (ReadWriteOnce) and bound to one zone.

  • Plan for zones: zonal disks cannot follow a pod to another zone; use replication across zones.

  • Use the database’s own replication rather than replicating its files at the storage layer.

Pitfalls

  • Local volumes for important data in a cluster: the data is lost or unreachable when the node fails.

  • Several writers on one ReadWriteOnce volume, or databases on shared file systems that do not support their locking.

  • No backups because “the storage is replicated”: replication also copies deletions and corruption.

  • Ignoring zone affinity of persistent disks.

Interview Tips

  • Lead with stateless containers plus managed data services.

  • Explain CSI persistent volumes, StatefulSets and operators, and access modes.

  • Stress backups, restore tests and zone-aware design.

Sign in to keep reading

You've opened 2 full answers. Sign in to read all 55 Docker answers, mark what you know and pick up where you left off.

Report a mistake

What's wrong?

All System Design subjects