Containers and Docker Interview Questions

261 multiple-choice tech interview questions on Containers and Docker: containers vs VMs, images and layers, Dockerfiles, multi-stage builds, volumes and networking, registries and security. Written for technical phone screens and interview prep, organized by subtopic, with a short explanation for every answer. Learn the 241 key terms with the flashcards first, then test yourself.

Take the practice test · Flashcards · All study tools

What it covers

  1. 6.1 Container fundamentals
  2. 6.2 Dockerfile instructions
  3. 6.3 Layers, caching and image size
  4. 6.4 BuildKit and multi-platform builds
  5. 6.5 Running and managing containers
  6. 6.6 Storage and networking
  7. 6.7 Docker Compose
  8. 6.8 Registries and image distribution
  9. 6.9 Container security and supply chain

Key terms

6.1 Container fundamentals

Container
An isolated process running from an image and sharing the host kernel
Image
A read-only, layered template for creating containers
Namespaces and cgroups
Linux features that isolate container processes and limit their resources
PID namespace
Separate process ID numbering per container
Network namespace
Isolated network stack
UTS namespace
Isolated hostname and domain name
overlay2
Union file system driver for layers
Copy-on-write
Copying a file up before modifying it
Docker architecture
CLI, daemon, containerd and runc
runc
Low-level OCI container runtime
Docker Desktop
Docker with a managed Linux VM on Mac and Windows
Docker Desktop licensing
Paid plans for larger organizations
Kernel sharing
Containers need a compatible host kernel
Windows isolation modes
Process versus Hyper-V isolation
Isolation strength
Shared kernel versus hypervisor
Container states
Lifecycle stages of a container
docker ps
Listing containers
Main process
A container lives as long as PID 1
Rootless mode
Docker daemon without root privileges
Containers as processes
Isolated host processes
Content addressing
Identifying layers by hash
nerdctl
Docker-style CLI for containerd
Moby
Open-source base of Docker Engine
cgroup v2
Unified control group hierarchy
docker pause
Freezing all processes in a container

6.2 Dockerfile instructions

Dockerfile
A text file of instructions for building an image
Layer caching
Reusing unchanged image layers to speed up builds
Multi-stage build
Building in one stage and copying only output into a small final image
FROM
Sets the base image for a build stage
COPY vs ADD
Plain copy versus copy with extras
WORKDIR
Sets the working directory for later steps
ARG vs ENV
Build-time versus runtime variables
ARG scope
ARGs before FROM aren't visible inside stages
Exec vs shell form
JSON array versus shell string
USER
Sets the user for later steps and runtime
OCI labels
Standard image metadata keys
VOLUME instruction
Declares a path for volume mounts
SHELL
Default shell for shell-form instructions
STOPSIGNAL
Signal for stopping the container
ONBUILD
Deferred instructions for child images
COPY --chown
Setting ownership while copying
COPY --from
Copying files from a stage or image
--entrypoint
Overriding ENTRYPOINT at run time
Dockerfile heredocs
Multi-line RUN scripts
Syntax directive
Picks the Dockerfile frontend version
exec "$@"
Handing PID 1 to the real command
ADD --checksum
Verifying remote downloads
JSON quoting
Exec form needs valid JSON arrays
Multiple CMDs
Only the final CMD takes effect
docker build -f
Choosing a Dockerfile by name
Build context
The files available to a build
Variable defaults
Fallback values in substitutions
Build-only settings
Keeping build tweaks out of runtime

6.3 Layers, caching and image size

Layer-creating steps
Instructions that change files
Cache invalidation
A change rebuilds all later steps
Combined apt steps
Update and install in one layer
Cleaning apt lists
Removing index files in the same layer
--no-install-recommends
Installing only required packages
docker history
Lists an image's layers
dive
Layer explorer for images
COPY cache key
Content checksums of copied files
--no-cache
Building without the cache
--pull
Refreshing base images during build
--target
Building a specific stage
Named stages
Labeling build stages with AS
Stage skipping
BuildKit builds only needed stages
musl vs glibc
Alpine's C library differs
pip --no-cache-dir
Not storing pip's cache
Builder-stage venv
Building deps apart from the runtime
COPY --link
Independent copy layers
Squashing
Merging layers into one
Layer sharing
Reusing identical layers across images
Compressed size
Layer size in transit versus on disk
Cache busting
Forcing a rebuild from one step
Late volatile steps
Putting changing values last
docker system df
Docker disk usage summary
Dangling images
Untagged leftover images
Slim variants
Trimmed official base images

6.4 BuildKit and multi-platform builds

BuildKit
Docker's modern build engine
buildx
BuildKit CLI plugin
Cache mounts
Persistent build caches outside layers
Secret mounts
Build-time secrets not stored in layers
--secret
Passing secrets to a build
SSH mounts
Forwarding an SSH agent into a build step
Bind mounts in builds
Reading files without a COPY layer
Parallel stages
Concurrent building of independent stages
Multi-platform builds
One image for several CPU architectures
Image index
Multi-platform manifest list
exec format error
Binary for the wrong architecture
QEMU emulation
Emulating other CPUs during builds
BUILDPLATFORM
Running build stages on the native platform
Platform args
Automatic build args for platforms
Image store limits
Local storage of multi-platform images
Builder drivers
Where BuildKit runs
Remote build cache
Sharing BuildKit cache across machines
Cache mode max
Caching all stages
GHA cache backend
BuildKit cache in GitHub Actions
buildx bake
Declarative multi-target builds
Local output
Exporting build results as files
Build attestations
SBOM and provenance attached to images
--load vs --push
Where buildx results go
Build checks
Linting a Dockerfile with BuildKit
--progress=plain
Full, uncollapsed build output
Git contexts
Building straight from a Git repo
Named contexts
Extra named inputs for a build
Native ARM builds
Building on ARM hardware
SOURCE_DATE_EPOCH
Fixed timestamps for reproducible builds

6.5 Running and managing containers

Volume
Persistent storage that outlives a container
Docker Compose
Tool for defining multi-container apps in YAML
Detached mode
Running a container in the background
--rm
Auto-removing a container on exit
Container names
Human-friendly identifiers
--env-file
Loading env vars from a file
Restart policies
When Docker restarts containers
docker stop
Graceful stop with a timeout
docker kill
Immediately signaling a container
--cpus
CPU time limit for a container
docker exec
Running a command in a running container
Following logs
Streaming recent container output
Log rotation
Capping container log files
docker inspect
Low-level JSON details
docker stats
Live resource usage
--init
Minimal init process for containers
docker cp
Copying files to or from containers
container prune
Deleting stopped containers
-it
Interactive terminal session
docker attach
Connecting to a container's main process
docker update
Changing limits on a running container
docker commit
Snapshotting a container as an image
docker events
Real-time daemon event stream
--pids-limit
Cap on processes in a container
Docker contexts
Switching between Docker engines

6.6 Storage and networking

Volume vs bind mount
Docker-managed storage versus host paths
Dev bind mounts
Sharing source code with a container
tmpfs mount
In-memory file system for a container
--mount vs -v
Two mount syntaxes
Volume location
Docker's volume storage path
Volume backup
Archiving volume contents via a helper container
Read-only mounts
Preventing writes to a mount
Volume pre-population
Copying image content into new volumes
Mount shadowing
Mounts covering image content
Bind mount permissions
Host ownership applies in containers
volume prune
Removing unused volumes
Volume drivers
Plugins for storage backends
Desktop file sharing
Host-to-VM file access overhead
User-defined bridge
Custom network with name resolution
docker network create
Making a new network
Host networking
Sharing the host's network namespace
No network
Containers with loopback only
Localhost publishing
Binding a published port to one IP
Docker and ufw
Published ports skipping host firewall rules
-P
Publishing all exposed ports
Reaching the host
Special hostname for the host machine
network connect
Attaching a container to another network
Network aliases
Extra DNS names on a network
Shared network namespace
Joining another container's network
macvlan
Containers appearing as LAN devices
Overlay network
Multi-host container networking
Embedded DNS
Docker's resolver for containers
docker port
Listing port mappings

6.7 Docker Compose

Compose v2
Compose as a Docker CLI plugin
Compose version key
Obsolete top-level field
compose.yaml
Default Compose file name
depends_on
Start order between services
service_healthy
depends_on condition on health checks
compose up
Starting a Compose project
compose down -v
Tearing down including volumes
compose logs
Logs from Compose services
compose exec
Running a command in a running service
compose run
One-off commands for a service
Compose interpolation
Variables substituted in Compose files
env_file
Loading container env vars from files
Override file
Automatically merged Compose overrides
Multiple Compose files
Layering configs with -f
Profiles
Optional groups of services
compose watch
File-change syncing and rebuilds
Project name
Prefix for Compose resources
Compose build
Building service images from Compose
up --build
Rebuilding images on start
Compose scaling
Running several replicas of a service
Compose restart
Restart policy in Compose
Top-level volumes
Declaring named volumes in Compose
ports vs expose
Host publishing versus documentation
include
Composing projects from several files
compose config
Rendering the effective configuration
Extension fields
x- keys for reusable config
Compose limits
Single-host scope of Compose

6.8 Registries and image distribution

Image reference
Registry, repository, tag and digest
Default registry
Short names expand to Docker Hub
latest tag
A default name, not a guarantee
docker tag and push
Naming and uploading images
Credential helpers
Secure storage for registry logins
Pull rate limits
Docker Hub caps on pulls
Official Images
Curated Docker Hub base images
Registry mirrors
Daemon-level pull mirrors
Self-hosted registries
Running your own registry
GHCR
GitHub's container registry
OCI artifacts
Non-image content in registries
Referrers API
Linking artifacts to images
save and load
Image transfer as tar files
export vs save
Container file system versus image
skopeo and crane
Daemonless registry tools
imagetools inspect
Reading remote manifests
Tagging strategy
Precise, floating and SHA tags
Image manifest
Index of an image's config and layers
Layer deduplication
Registries store each blob once
Insecure registries
Docker requires HTTPS by default
Registry garbage collection
Removing unreferenced blobs
Base image updates
Automated PRs for new base versions
Lowercase repositories
Repository naming rules
Pulling a platform
Choosing a variant from an index
Lazy pulling
On-demand image layer fetching
Distribution spec
Standard registry API
Push denied
Authorization failure on push
Listing digests
Showing image digests locally

6.9 Container security and supply chain

Registry
A service that stores and distributes container images
Distroless image
A minimal base image without a shell or package manager
Docker socket
The daemon's API socket
docker group
Access to the Docker daemon
Docker Content Trust
Legacy Notary v1 signing
Rebuild to patch
Fixing image CVEs by rebuilding
Hadolint
Dockerfile linter
Env var exposure
Secrets in environment variables can leak
Typosquatted images
Malicious look-alike images
Inter-container communication
Toggle for default-bridge traffic
Exposed daemon
Unprotected Docker API over TCP
docker-bench-security
CIS Docker Benchmark checker
docker-default
Docker's default AppArmor profile
Unconfined seccomp
Removing the default syscall filter
Enhanced Container Isolation
Hardened container mode in Docker Desktop
Scheduled rebuilds
Refreshing images for patches
Privileged ports
Ports below 1024 need privileges
Numeric UIDs
Using a number in USER
Docker Hardened Images
Docker's minimal secure base images
Syft
SBOM generator for images
Continuous scanning
Rescanning stored images over time
Checking the image user
Reading Config.User from an image
Host kernel patching
Shared kernel as an escape path
docker scout compare
Comparing images' packages and CVEs
Docker-in-Docker
Running Docker inside a container
Digest vs signature
Integrity versus authenticity

Sample practice questions

  1. How does a container differ from a virtual machine?

    1. Each container ships its own kernel; VMs share the host's kernel
    2. VMs always start faster than containers because they're pre-booted
    3. Containers share the host kernel; each VM runs a full guest OS
    4. Containers can't run on Linux hosts, only on Windows Server

    Answer: C. Containers share the host kernel; each VM runs a full guest OS Linux containers rely on kernel namespaces and cgroups for isolation and resource limits.

  2. In a Dockerfile, what is the difference between `RUN` and `CMD`?

    1. `RUN` runs when the container starts; `CMD` runs at build time
    2. `RUN` runs at build time, making a layer; `CMD` is the default start command
    3. They're interchangeable and produce exactly the same image
    4. `CMD` installs packages, while `RUN` only copies files

    Answer: B. `RUN` runs at build time, making a layer; `CMD` is the default start command Only the last `CMD` in a Dockerfile takes effect.

  3. Why order a Dockerfile so that `COPY package.json` and `RUN npm ci` come before `COPY . .`?

    1. npm refuses to run unless package.json is the very first file copied
    2. Cached dependency layers are reused when only source code changes
    3. Copying package.json first makes the final image noticeably smaller
    4. Docker runs the instructions in a Dockerfile in reverse order

    Answer: B. Cached dependency layers are reused when only source code changes Once one layer changes, every layer after it must be rebuilt.

  4. Since Docker Engine 23.0, what does `docker build` use by default on Linux?

    1. The legacy builder
    2. Kaniko
    3. BuildKit
    4. Buildah

    Answer: C. BuildKit BuildKit adds caching, parallelism and mounts.

  5. What does `docker run -p 8000:80 nginx` do?

    1. Runs nginx, mapping container port 8000 to host port 80
    2. Runs 8,000 nginx containers, numbered from port 80 up
    3. Runs nginx, mapping host port 8000 to container port 80
    4. Runs nginx with its memory limited to about 80 MB

    Answer: C. Runs nginx, mapping host port 8000 to container port 80 The format is `host:container`.

  6. Why are containers called ephemeral, and how do you keep data across restarts?

    1. Containers delete themselves every hour; schedule them to restart
    2. The writable layer goes with the container; persist data in volumes
    3. Data is saved into the image automatically, so nothing is ever lost
    4. Restarting a container wipes the host disk; back up the host daily

    Answer: B. The writable layer goes with the container; persist data in volumes Named volumes are managed by Docker; bind mounts map a host path into the container.

  7. What is Docker Compose used for?

    1. Merging several images together into one larger image
    2. Writing Dockerfiles automatically from existing source code
    3. Defining and running multi-container apps from a YAML file
    4. Running Kubernetes clusters in production environments

    Answer: C. Defining and running multi-container apps from a YAML file `docker compose up` starts all services with their networks and volumes.

  8. What is a container registry?

    1. A list of the containers currently running on a host
    2. A database that stores Dockerfiles and build history
    3. A service that stores and serves images, like ACR, ECR or Docker Hub
    4. The container runtime that actually starts containers

    Answer: C. A service that stores and serves images, like ACR, ECR or Docker Hub Registries support access control, tags, replication and vulnerability scanning.

  9. Why should containers not run as root?

    1. Containers that run as root can't access the network at all
    2. Docker refuses to start containers configured to run as root
    3. Running as root makes the container use much more memory
    4. An attacker breaking out of the app gets an easier path to the host

    Answer: D. An attacker breaking out of the app gets an easier path to the host Add a `USER` instruction; many official images provide a non-root user, and .NET 8+ images include an `app` user.

  10. Which Linux kernel features provide container isolation and resource limits?

    1. Namespaces for isolation and cgroups for CPU and memory limits
    2. SELinux and AppArmor, with no other kernel features involved
    3. systemd and cron, which start and schedule container processes
    4. iptables and DNS, which separate each container's traffic

    Answer: A. Namespaces for isolation and cgroups for CPU and memory limits Security modules such as seccomp, AppArmor and SELinux add further hardening.

Practice all 261 questions

More Cloud and DevOps