Docker Interview Questions: From Beginner to Advanced
📅 Published: June 2026
⏱️ Estimated Reading Time: 25 minutes
🏷️ Tags: Docker Interview, Containerization, DevOps Interview, Docker Certification
Introduction: What Docker Interviewers Look For
Docker interviews test your understanding of containerization concepts, practical Docker commands, and real-world troubleshooting. Interviewers want to see that you understand not just how to use Docker, but why containers work the way they do.
This guide organizes questions by difficulty level, from foundational concepts to advanced scenarios. Each question includes the answer you should give, plus additional context to help you understand why interviewers ask it.
Part 1: Foundational Questions (Beginner Level)
Q1: What is Docker and why is it used?
Answer:
Docker is a platform for developing, shipping, and running applications in containers. Containers package an application with all its dependencies—code, runtime, system tools, libraries—so it runs consistently across any environment.
Docker solves the "it works on my machine" problem. It ensures that an application runs the same way on a developer's laptop, in testing, and in production.
Why interviewers ask this: It tests your basic understanding of Docker's value proposition.
Q2: What is the difference between a Docker image and a container?
Answer:
A Docker image is a read-only template containing the application code, libraries, dependencies, and configuration. It is the blueprint for creating containers. Images are stored in registries like Docker Hub.
A Docker container is a runnable instance of an image. It adds a writable layer on top of the image layers. You can create, start, stop, move, or delete a container. Multiple containers can run from the same image.
The analogy: An image is like a class in programming; a container is an instance of that class.
Why interviewers ask this: This is the most fundamental Docker concept. Confusing images and containers suggests a lack of hands-on experience.
Q3: What is a Dockerfile?
Answer:
A Dockerfile is a text file containing instructions for building a Docker image. Each instruction creates a layer in the image. Common instructions include FROM (base image), RUN (execute commands), COPY (add files), WORKDIR (set working directory), EXPOSE (document ports), and CMD (default command).
Example:
FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . USER node EXPOSE 3000 CMD ["node", "server.js"]
Why interviewers ask this: Writing Dockerfiles is a core Docker skill.
Q4: What is the difference between CMD and ENTRYPOINT?
Answer:
CMD provides default arguments for the container. It can be overridden by command-line arguments when running the container.
ENTRYPOINT defines the executable that runs when the container starts. It is NOT overridden by command-line arguments. Instead, command-line arguments are appended to the ENTRYPOINT.
When both are used together, ENTRYPOINT defines the executable and CMD provides default arguments.
Example:
ENTRYPOINT ["nginx"] CMD ["-g", "daemon off;"]
Running docker run nginx -g "daemon on;" overrides CMD but not ENTRYPOINT.
Why interviewers ask this: This distinguishes developers who have written production Dockerfiles from those who only ran basic containers.
Q5: How do you copy files from host to container?
Answer:
Two main ways:
In Dockerfile (build time):
COPY ./local-file /container/path/ ADD ./local-file /container/path/ # ADD can also extract tar files
In running container (runtime):
docker cp /host/file.txt container_name:/container/path/
COPY is preferred over ADD unless you need ADD's special features (tar extraction or URL downloads).
Why interviewers ask this: It tests practical file management knowledge.
Q6: What is the difference between COPY and ADD?
Answer:
COPY copies files from the build context to the image. It is simple and transparent.
ADD does everything COPY does plus:
Automatically extracts tar files
Can copy from URLs
Because ADD has unexpected behavior (automatic extraction), COPY is preferred for most cases. Use ADD only when you specifically need the extra features.
Why interviewers ask this: It tests attention to Dockerfile best practices.
Part 2: Intermediate Questions
Q7: Explain Docker layers and how caching works.
Answer:
Every instruction in a Dockerfile creates a layer. Layers are stacked on top of each other. Docker caches each layer during build.
When you rebuild an image, Docker checks if a layer has changed. If a layer is unchanged, Docker reuses the cached layer. This makes subsequent builds much faster.
Layer invalidation occurs when:
The instruction itself changes
Files in COPY or ADD change
Optimization strategy: Put rarely changing instructions (FROM, WORKDIR, RUN apt-get) before frequently changing instructions (COPY .). This maximizes cache reuse.
Example optimization:
# Good: Dependencies first (change rarely) FROM node:18 WORKDIR /app COPY package*.json ./ RUN npm install COPY . . # Bad: Code first (changes every build, invalidates everything) FROM node:18 COPY . . RUN npm install
Why interviewers ask this: Understanding layers and caching is essential for building efficient images.
Q8: How do you reduce Docker image size?
Answer:
Use minimal base images: Alpine variants are much smaller than full OS images
node:18-alpine(170 MB) vsnode:18(1 GB)
Use multi-stage builds: Separate build environment from runtime environment
# Build stage FROM node:18 AS builder WORKDIR /app COPY . . RUN npm run build # Runtime stage FROM node:18-alpine COPY --from=builder /app/dist ./dist CMD ["node", "dist/server.js"]
Combine RUN commands to reduce layers
# Bad: Three layers RUN apt-get update RUN apt-get install -y package RUN apt-get clean # Good: One layer RUN apt-get update && apt-get install -y package && apt-get clean
Clean up in the same layer: Remove temporary files, package manager caches
Use .dockerignore: Exclude unnecessary files (node_modules, .git, logs)
Why interviewers ask this: Large images slow deployments and increase security risks.
Q9: What are Docker volumes and why are they needed?
Answer:
Volumes persist data beyond the container lifecycle. Containers are ephemeral—when a container is removed, everything written to its writable layer disappears. Databases, user uploads, and logs need to survive container restarts.
Volumes are the preferred way to persist data. They are managed by Docker and stored in /var/lib/docker/volumes/.
Why volumes over bind mounts:
Managed by Docker (backup, migration)
Work the same across all platforms
Better performance on Linux
Support volume drivers (network storage, cloud storage)
# Create and use a volume docker volume create postgres-data docker run -v postgres-data:/var/lib/postgresql/data postgres
Why interviewers ask this: Stateful applications are common; understanding storage is essential.
Q10: What is the difference between a volume and a bind mount?
Answer:
| Aspect | Volume | Bind Mount |
|---|---|---|
| Managed by | Docker | You |
| Location | /var/lib/docker/volumes/ | Anywhere on host |
| Backup | Docker commands | Manual |
| Cross-platform | Yes | Limited |
| Permissions | Docker manages | You manage |
| Use case | Production data | Development, config files |
Volumes are preferred for production persistent data. Bind mounts are convenient for development (mounting code for live reload) and for mounting specific configuration files.
Why interviewers ask this: Distinguishes understanding of development vs. production patterns.
Q11: How do you manage environment variables in Docker?
Answer:
Dockerfile ENV (build-time, hardcoded):
ENV NODE_ENV=production
docker run -e (runtime):
docker run -e DATABASE_URL=postgres://localhost myapp
docker run --env-file (from file):
docker run --env-file .env myappDocker Compose environment:
environment: - NODE_ENV=production - DATABASE_URL=${DATABASE_URL}
For secrets, use Docker Secrets (Swarm) or external secrets managers (Vault, AWS Secrets Manager). Never hardcode secrets in images or environment variables in code.
Why interviewers ask this: Configuration management is a real-world challenge.
Q12: What is Docker Compose?
Answer:
Docker Compose is a tool for defining and running multi-container Docker applications. You define your application's services, networks, and volumes in a docker-compose.yml file. Then with one command, you create and start all services.
Example docker-compose.yml:
version: '3.8' services: web: build: . ports: - "3000:3000" database: image: postgres environment: POSTGRES_PASSWORD: secret
docker-compose up -d # Start all services docker-compose down # Stop all services docker-compose logs # View logs
Why interviewers ask this: Real applications have multiple services; Compose is the standard tool.
Q13: Explain Docker networking. What are the different network drivers?
Answer:
Docker provides network drivers for different isolation levels:
| Driver | Use Case |
|---|---|
| bridge | Default. Single-host container communication |
| host | Removes network isolation (performance-sensitive) |
| overlay | Multi-host container communication (Swarm) |
| macvlan | Assigns MAC addresses (legacy apps) |
| none | No network (isolated containers) |
For most applications, user-defined bridge networks provide the best balance of isolation and functionality.
# Create custom bridge network docker network create my-network # Run containers on it docker run --network my-network --name web nginx docker run --network my-network --name db postgres # Containers can communicate by name # web can ping db, db can ping web
Why interviewers ask this: Networking is a common source of issues in production.
Part 3: Advanced Questions
Q14: How do you handle database migrations in Docker?
Answer:
Pattern 1: Run migrations before app starts
# Dockerfile ENTRYPOINT ["/entrypoint.sh"]
#!/bin/bash npm run migrate exec npm start
Pattern 2: Separate migration container
# docker-compose.yml services: migrate: image: myapp command: npm run migrate depends_on: - db app: image: myapp command: npm start depends_on: - migrate
Pattern 3: Entrypoint script with health checks
Wait for database to be ready before running migrations.
#!/bin/bash while ! nc -z db 5432; do sleep 1 done npm run migrate exec "$@"
Why interviewers ask this: Database migrations are a common production challenge.
Q15: What are the security best practices for Docker?
Answer:
Image security:
Use official images from trusted sources
Use specific tags, never
latestUse minimal base images (alpine)
Scan images for vulnerabilities (
docker scan,trivy)Run as non-root user
Runtime security:
Drop all capabilities, add only needed
docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE nginx
Use read-only root filesystem
docker run --read-only nginxSet resource limits
docker run --memory=512m --cpus=1 nginx
Use seccomp and AppArmor profiles
Never embed secrets in images. Use secrets managers or environment variables at runtime.
Why interviewers ask this: Security is everyone's responsibility.
Q16: How do you debug a container that exits immediately?
Answer:
# 1. Check logs docker logs mycontainer # 2. Check logs from previous instance docker logs mycontainer --previous # 3. Run with interactive shell to see the issue docker run -it myapp /bin/sh # 4. Override entrypoint to debug docker run -it --entrypoint /bin/sh myapp # 5. Inspect container after exit docker inspect mycontainer
Common causes:
Missing dependencies
Incorrect CMD or ENTRYPOINT
Missing environment variables
Permission issues
Application error on startup (exit code 1)
OOM kill (exit code 137)
Why interviewers ask this: Debugging failing containers is a daily task for DevOps engineers.
Q17: Explain the difference between Docker Swarm and Kubernetes.
Answer:
| Aspect | Docker Swarm | Kubernetes |
|---|---|---|
| Complexity | Simple | Complex |
| Setup | Minutes | Hours |
| Learning curve | Gentle | Steep |
| Features | Basic | Extensive |
| Scaling | Good | Excellent |
| Self-healing | Basic | Advanced |
| Service discovery | Built-in | Via DNS/CoreDNS |
| Load balancing | Built-in | Via Service/Ingress |
| Storage | Volumes | PV/PVC, CSI |
| Use case | Smaller deployments | Enterprise, complex apps |
Swarm is integrated into Docker and simpler to operate. Kubernetes is more powerful with a larger ecosystem. Choose Swarm for simplicity, Kubernetes for scale and features.
Why interviewers ask this: Shows awareness of the container orchestration landscape.
Q18: How do you implement health checks in Docker?
Answer:
In Dockerfile:
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost/ || exit 1
In docker-compose.yml:
services: web: healthcheck: test: ["CMD", "curl", "-f", "http://localhost"] interval: 30s timeout: 10s retries: 3 start_period: 40s
Health check states:
starting: Initial state during start_periodhealthy: Container is workingunhealthy: Container failed health checks
Health checks enable Docker to automatically restart unhealthy containers.
Why interviewers ask this: Health checks are critical for production container deployments.
Q19: What is the difference between docker stop and docker kill?
Answer:
docker stop sends SIGTERM to the main process, giving it time to clean up (default 10 seconds). After the grace period, it sends SIGKILL.
docker kill sends SIGKILL immediately. The process does not have a chance to clean up.
# Graceful stop (recommended) docker stop mycontainer # Immediate kill (last resort) docker kill mycontainer # Custom grace period docker stop -t 30 mycontainer
When to use which:
Use
docker stopfor normal shutdownsUse
docker killwhen the process is hung and not responding to SIGTERM
Why interviewers ask this: Shows understanding of process signaling.
Q20: What are the best practices for writing Dockerfiles for production?
Answer:
Use specific base image tags
# Bad FROM node:latest # Good FROM node:18.17.0-alpine
Run as non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nodejs -u 1001 -G nodejs
USER nodejsUse multi-stage builds
FROM node:18 AS builder # build step FROM node:18-alpine COPY --from=builder /app/dist ./dist
Sort multi-line arguments alphabetically (easier to maintain)
Leverage build cache (order layers from least to most frequently changing)
Use .dockerignore to exclude unnecessary files
Use specific WORKDIR, not default root
Set appropriate timeouts and health checks
Use COPY instead of ADD unless you need ADD's special features
Remove package manager cache in same layer
Why interviewers ask this: Production Dockerfiles separate experienced practitioners from beginners.
Part 4: Scenario-Based Questions
Scenario 1: Image Too Large
Problem: Your Docker image is 1.2 GB, causing slow deployments. How do you reduce it?
Solution:
Use multi-stage build to exclude build tools
Switch to alpine base image
Combine RUN commands and clean up in same layer
Use .dockerignore to exclude node_modules, .git, logs
Remove unnecessary packages and files
Expected result: Image size reduced to 150-200 MB.
Scenario 2: Container Can't Connect to Database
Problem: Your app container cannot connect to the database container. Both run on the same host.
Troubleshooting steps:
Check if both containers are on same network:
docker network lsCreate user-defined bridge network:
docker network create mynetConnect both containers:
docker network connect mynet appanddocker network connect mynet dbVerify connectivity:
docker exec app ping dbCheck app is using correct hostname (container name, not localhost)
Scenario 3: Container Exits Immediately
Problem: Your container exits immediately after starting.
Troubleshooting steps:
Check logs:
docker logs mycontainerCheck previous logs:
docker logs --previous mycontainerRun with interactive shell:
docker run -it myimage /bin/shOverride entrypoint:
docker run -it --entrypoint /bin/sh myimageInspect container:
docker inspect mycontainerCheck exit code: 0 = normal, non-zero = error, 137 = OOM kill
Scenario 4: Port Already in Use
Problem: docker run -p 80:80 nginx fails with "port already allocated".
Solutions:
Find what's using port 80:
sudo lsof -i :80Stop the conflicting container:
docker stop existing-nginxOr use different host port:
docker run -p 8080:80 nginx
Docker Commands Cheat Sheet for Interviews
# Basic commands docker --version docker info # Image management docker images docker build -t myapp:tag . docker pull nginx:alpine docker push myregistry/myapp:tag docker rmi myimage docker tag myapp:latest myapp:v1 # Container management docker run -d --name myapp -p 80:80 nginx docker ps docker ps -a docker stop myapp docker start myapp docker restart myapp docker rm myapp docker rm -f myapp docker logs myapp docker logs -f myapp docker exec -it myapp /bin/bash docker cp file.txt myapp:/app/ # Network docker network ls docker network create mynet docker network connect mynet myapp docker network disconnect mynet myapp # Volumes docker volume ls docker volume create myvol docker volume rm myvol docker volume prune # System docker system prune docker system df docker stats docker inspect myapp
Interview Preparation Checklist
Foundational Concepts
Explain Docker architecture (client, daemon, registry)
Differentiate images and containers
Write a basic Dockerfile
Explain CMD vs ENTRYPOINT
Understand Docker layers and caching
Intermediate Skills
Optimize image size (multi-stage, alpine)
Use volumes for persistent data
Configure Docker networking
Write docker-compose.yml for multi-service apps
Manage environment variables
Advanced Topics
Implement health checks
Apply security best practices
Debug failing containers
Understand orchestration (Swarm vs Kubernetes)
Design production-ready Dockerfiles
Hands-on Practice
Containerize a Node.js/Python/Java app
Build a multi-container app with Docker Compose
Reduce image size from 1GB to under 200MB
Set up volume for database persistence
Debug a crashing container
Common Mistakes in Docker Interviews
| Mistake | Better Answer |
|---|---|
| "Docker is a virtual machine" | Docker is containerization, shares host kernel |
| "Images and containers are the same" | Images are templates, containers are running instances |
| "CMD and ENTRYPOINT are interchangeable" | Different purposes: CMD provides defaults, ENTRYPOINT defines executable |
| "latest tag is fine for production" | Specific tags ensure reproducibility |
| "Run as root is fine" | Non-root users are more secure |
| "I don't know how to debug failing containers" | Describe the systematic approach: logs, exec, inspect |
Summary
| Topic | Key Points |
|---|---|
| Images vs Containers | Image = blueprint, Container = running instance |
| Dockerfile | FROM, RUN, COPY, CMD, ENTRYPOINT, WORKDIR |
| Layers | Each instruction creates a layer, caching speeds builds |
| Volumes | Persist data beyond container lifecycle |
| Networks | bridge, host, overlay, macvlan, none |
| Compose | Define multi-container apps in YAML |
| Security | Non-root, drop capabilities, scan images |
Learn More
Practice Docker with hands-on exercises in our interactive labs:
https://devops.trainwithsky.com/
Comments
Post a Comment