Docker Interview Questions and Answers (Comprehensive Guide)

Docker is an open-source platform for developing, shipping, and running applications in lightweight, portable containers. Containers bundle the application code with its dependencies (libraries, runtime, tools, etc.), ensuring consistent behavior across development, testing, and production environments.

Docker

Key Benefits

  • Portability — “Build once, run anywhere.”
  • Efficiency — Containers share the host OS kernel (unlike VMs), making them faster to start and lighter on resources.
  • Consistency — Eliminates “it works on my machine” issues.
  • Scalability — Easy to scale and orchestrate (e.g., with Docker Compose, Swarm, or Kubernetes).

Core Concepts

  • Docker Image: A read-only template (blueprint) for launching containers. Built from a Dockerfile.
  • Docker Container: A runnable instance of an image — lightweight, isolated process.
  • Dockerfile: Text file with instructions to build an image.
  • Docker Daemon (dockerd): Background service managing containers, images, networks, and volumes on the host.
  • Docker Client: CLI (docker command) that interacts with the daemon.
  • Docker Registry (e.g., Docker Hub): Repository for storing and sharing images (public/private).

Difference between Containers and VMs:

  • Containers virtualize at the OS level (share host kernel via namespaces and cgroups) → lightweight, fast startup.
  • VMs emulate a full OS → heavier, slower, better isolation.

Docker is one of the most frequently asked topics in Cloud, DevOps, Data Engineering, Platform Engineering, MLOps, and AWS interviews.


1. What is Docker?

Answer

Docker is an open-source containerization platform that allows developers to package applications along with their dependencies, libraries, and configurations into lightweight, portable containers.

Benefits

  • Consistent environments
  • Faster deployment
  • Efficient resource utilization
  • Easy scalability
  • Simplified CI/CD integration

Real Example

Without Docker:

Works on my machine
Fails in QA
Fails in Production

With Docker:

Build Once
Run Anywhere

2. What is Containerization?

Answer

Containerization packages:

  • Application code
  • Runtime
  • Libraries
  • Dependencies
  • Configuration

into a single container.

Example

Python application:

Python Code
Pandas
NumPy
Boto3

All packaged into one Docker image.


3. Difference Between Containers and Virtual Machines

FeatureDocker ContainerVirtual Machine
OSShares Host OSOwn OS
StartupSecondsMinutes
SizeMBsGBs
PerformanceHighLower
Resource UsageLowHigh

Interview Answer

Containers virtualize the OS level while VMs virtualize hardware.


4. Docker Architecture

Components:

Docker Client

docker build
docker run
docker pull

Docker Daemon

dockerd

Responsible for:

  • Building images
  • Running containers
  • Managing networks

Docker Registry

Stores images.

Examples:

  • Docker Hub
  • Amazon ECR
  • GitHub Container Registry

5. What is Docker Image?

Answer

Docker Image is a read-only template used to create containers.

Example:

ubuntu:22.04
python:3.11
nginx:latest

6. What is Docker Container?

Answer

A running instance of a Docker image.

Example:

docker run nginx

Image = Blueprint

Container = Running Application


7. Docker Lifecycle

Build Image

Create Container

Start Container

Stop Container

Remove Container

Commands:

docker build
docker run
docker stop
docker rm

8. What is Docker Hub?

Answer

Docker Hub is the default public registry used to store and distribute Docker images.

Example:

docker pull nginx

Downloads image from Docker Hub.


9. What is a Dockerfile?

Answer

Dockerfile is a text file containing instructions to build Docker images.

Example:

FROM python:3.11

WORKDIR /app

COPY . .

RUN pip install -r requirements.txt

CMD ["python","app.py"]

10. Explain Dockerfile Instructions

FROM

Base image.

FROM ubuntu:22.04

WORKDIR

Sets working directory.

WORKDIR /app

COPY

Copies files.

COPY . .

ADD

Copies files and extracts archives.

ADD sample.tar.gz /app

RUN

Executes commands during image build.

RUN apt-get update

CMD

Default command.

CMD ["python","app.py"]

ENTRYPOINT

Container executable.

ENTRYPOINT ["python"]

ENV

Sets environment variables.

ENV APP_ENV=prod

EXPOSE

Documents exposed port.

EXPOSE 8080

11. CMD vs ENTRYPOINT

CMDENTRYPOINT
Default argumentsMain executable
Can be overriddenDifficult to override

Example:

ENTRYPOINT ["python"]
CMD ["app.py"]

Execution:

python app.py

12. How to Build Docker Image?

docker build -t myapp:v1 .

Options:

-t

Tag image.


13. How to Run a Container?

docker run myapp:v1

Detached mode:

docker run -d myapp:v1

Interactive mode:

docker run -it ubuntu bash

14. Common Docker Commands

Images

docker images

Containers

docker ps

docker ps -a

Stop

docker stop container_id

Remove

docker rm container_id

Delete Image

docker rmi image_id

15. What is Docker Layering?

Answer

Each Dockerfile instruction creates a new layer.

Example:

FROM ubuntu

RUN apt-get update

RUN apt-get install python3

COPY app.py .

Layers:

Layer1 Ubuntu
Layer2 Update
Layer3 Python
Layer4 App

Benefits:

  • Faster builds
  • Reusability
  • Caching

16. What is Docker Cache?

Docker reuses unchanged layers.

Example:

COPY requirements.txt .
RUN pip install -r requirements.txt

If requirements.txt unchanged:

Cache Used

Build becomes faster.


17. How to Optimize Docker Images?

Use Smaller Base Images

FROM alpine

Multi-stage Build

FROM maven AS build

RUN mvn package

FROM openjdk:17

COPY --from=build app.jar .

Remove Unnecessary Files

Use:

.dockerignore

18. What is .dockerignore?

Similar to:

.gitignore

Example:

.git
*.log
node_modules
__pycache__

19. What is Docker Volume?

Answer

Volumes persist data beyond container lifecycle.

Example:

docker volume create myvolume

Attach:

docker run -v myvolume:/data nginx

20. Why Volumes are Needed?

Containers are ephemeral.

Without volume:

Container Deleted
Data Lost

With volume:

Container Deleted
Data Retained

21. Bind Mount vs Volume

Bind MountVolume
Host PathDocker Managed
Less PortablePortable
DevelopmentProduction

Example:

docker run -v /host:/app

22. What is Docker Network?

Allows communication between containers.

Example:

docker network create appnet

23. Types of Docker Networks

Bridge

Default network.

docker network create mybridge

Host

Shares host network.

--network host

None

No networking.

--network none

Overlay

Multi-host communication.

Used in Docker Swarm.


24. Port Mapping

Container:

8080

Host:

80

Command:

docker run -p 80:8080 app

Format:

host:container

25. Docker Compose

Answer

Tool for running multi-container applications.

Example:

services:

app:
image: app

mysql:
image: mysql

Start:

docker compose up

26. Benefits of Docker Compose

  • Multi-container deployment
  • Easy local development
  • Service dependencies
  • Single YAML configuration

27. Sample Docker Compose for Python + MySQL

version: '3'

services:

app:
build: .
ports:
- "5000:5000"

mysql:
image: mysql:8
environment:
MYSQL_ROOT_PASSWORD: admin

28. What is Docker Registry?

Stores Docker images.

Examples:

  • Docker Hub
  • Amazon ECR
  • GitHub Registry

29. Push Image to Docker Hub

Login:

docker login

Tag:

docker tag app myrepo/app:v1

Push:

docker push myrepo/app:v1

30. Docker Security Best Practices

Run as Non-root

USER appuser

Scan Images

docker scout

Minimal Images

FROM alpine

Secrets Management

Never hardcode:

ENV PASSWORD=123

31. What is Multi-Stage Build?

Example

FROM golang AS builder

RUN go build

FROM alpine

COPY --from=builder app .

Benefits:

  • Smaller image
  • Improved security
  • Faster deployment

32. Docker Logs

docker logs container_id

Follow logs:

docker logs -f container_id

33. Execute Command Inside Container

docker exec -it container_id bash

Useful for debugging.


34. Inspect Container

docker inspect container_id

Returns:

  • IP
  • Mounts
  • Environment variables
  • Configuration

35. Health Check

HEALTHCHECK CMD curl -f http://localhost || exit 1

Docker continuously monitors health.


36. Docker in CI/CD

Pipeline Flow:

Git Push

Build Image

Run Tests

Push to Registry

Deploy

Common Tools:

  • Jenkins
  • GitHub Actions
  • GitLab CI

37. Docker and AWS Interview Questions

How do you store Docker images in AWS?

Answer:

Use Amazon ECR.


How do you run Docker containers in AWS?

Answer:

  • Amazon ECS
  • Amazon EKS
  • AWS Fargate
  • EC2

Difference Between ECS and EKS?

ECSEKS
AWS NativeKubernetes
EasierMore Flexible
Less ComplexMore Complex

38. Docker Troubleshooting Questions

Container Keeps Restarting

Check:

docker logs

Inspect:

docker inspect

Port Already in Use

Error:

bind: address already in use

Solution:

netstat -an

Change port mapping.


Disk Space Full

Cleanup:

docker system prune -a

39. Senior-Level Docker Questions

How does Docker use Linux namespaces?

Namespaces isolate:

  • Process IDs
  • Network
  • Mounts
  • Users

What are Cgroups?

Control Groups manage:

  • CPU
  • Memory
  • I/O

limits for containers.


What is container runtime?

Software responsible for running containers.

Examples:

  • containerd
  • CRI-O
  • runc

40. Most Frequently Asked Docker Interview Questions

  1. What is Docker?
  2. Why Docker over VMs?
  3. What is containerization?
  4. Explain Docker architecture.
  5. What is Dockerfile?
  6. Difference between CMD and ENTRYPOINT?
  7. What are Docker layers?
  8. What is Docker cache?
  9. What is Docker Compose?
  10. What is Docker Volume?
  11. Bind mount vs volume?
  12. Docker networking types?
  13. Bridge network?
  14. Port mapping?
  15. Multi-stage builds?
  16. Docker security best practices?
  17. Docker registry?
  18. Docker Hub vs ECR?
  19. Troubleshooting containers?
  20. Docker in CI/CD?
  21. Docker with ECS?
  22. Docker with Kubernetes?
  23. Namespaces and cgroups?
  24. Health checks?
  25. How to optimize image size?

Data Engineer / AWS Interview Scenario

Question: How would you deploy a Python ETL application using Docker on AWS?

Answer:

  1. Create Dockerfile.
  2. Build Docker image.
  3. Test locally.
  4. Push image to Amazon ECR.
  5. Deploy on Amazon ECS/Fargate.
  6. Store secrets in AWS Secrets Manager.
  7. Use IAM Roles for permissions.
  8. Monitor using Amazon CloudWatch.
  9. Automate deployment through GitHub Actions or Jenkins.
  10. Use rolling deployments with health checks for zero downtime.

This end-to-end answer is commonly expected in senior Data Engineer, Cloud Engineer, DevOps Engineer, Platform Engineer, and AWS Solutions Architect interviews.

Basic Docker Interview Questions

1. What is Docker? Docker is a containerization platform that packages applications and dependencies into isolated, portable containers. It automates deployment and management, solving environment inconsistencies.

2. What are the main Docker components?

  • Client: CLI interface.
  • Daemon: Manages containers on the host.
  • Images: Templates.
  • Containers: Running instances.
  • Registry: Image storage (e.g., Docker Hub).

3. What is a Dockerfile? A text file containing instructions (e.g., FROM, RUN, COPY, CMD) to build a Docker image. Example:

dockerfile

FROM python:3.11-slim
WORKDIR /app
COPY . .
CMD ["python", "app.py"]
```<grok-card data-id="cf17b0" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**4. Difference between Docker image and container?**  
Image = static template (read-only). Container = running (or stopped) instance of an image. One image can spawn multiple containers.<grok-card data-id="957a85" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**5. Key Dockerfile instructions?**  
- `FROM`: Base image.  
- `RUN`: Execute commands during build.  
- `COPY` / `ADD`: Copy files.  
- `CMD` / `ENTRYPOINT`: Default command.  
- `EXPOSE`: Document ports.  
- `WORKDIR`: Set working directory.  
Best practice: Order layers for cache efficiency (dependencies before code).<grok-card data-id="166e12" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**6. Difference between `CMD` and `ENTRYPOINT`?**  
- `CMD`: Default command; easily overridden at runtime.  
- `ENTRYPOINT`: Main executable; arguments from `CMD` or `docker run` are appended (harder to override).  
Common: `ENTRYPOINT ["python"]` + `CMD ["app.py"]`.<grok-card data-id="6cd2e9" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**7. What is Docker Compose?**  
Tool for defining and running multi-container apps via `docker-compose.yml` (services, networks, volumes). Example use: web app + database.<grok-card data-id="12cb9a" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**8. Common Docker commands?**  
- `docker build -t image:tag .`  
- `docker run -d -p host:container image`  
- `docker ps -a` (all containers)  
- `docker images`  
- `docker exec -it container bash` (enter running container)  
- `docker logs container`  
- `docker stop/start/restart`  
- `docker rm -f container` / `docker rmi image`.<grok-card data-id="88445f" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**9. What are Docker volumes?**  
Persistent storage managed by Docker (outside container filesystem). Survive container removal. Preferred over bind mounts for production.  
`docker volume create myvol` and `-v myvol:/path`.<grok-card data-id="01fd05" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**10. What happens when you run a container?**  
Docker pulls the image (if needed), creates a writable layer on top of the image layers, and starts the process using namespaces/cgroups for isolation.<grok-card data-id="2051a6" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

## Intermediate Questions

**11. Docker networking types?**  
- **Bridge** (default): Single-host, containers communicate by name.  
- **Host**: Shares host network stack (no isolation).  
- **Overlay**: Multi-host (Swarm).  
- **None**: No networking.  
- **Macvlan**: Assigns MAC addresses.<grok-card data-id="6cf402" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**12. How does Docker handle data persistence?**  
- Volumes (Docker-managed).  
- Bind mounts (host path).  
- tmpfs (in-memory).  
Data in container layers is lost on removal unless persisted.<grok-card data-id="2ab02e" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**13. Multi-stage builds? Why use them?**  
Use multiple `FROM` statements. Build in one stage (with tools), copy artifacts to a slim final stage. Reduces image size and attack surface.<grok-card data-id="0d9304" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**14. Docker build cache?**  
Docker caches layers. Changes invalidate subsequent layers. Optimize by copying dependency files first (`requirements.txt` before source). Use `--no-cache` to bust cache.<grok-card data-id="0e76bf" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**15. `COPY` vs `ADD`?**  
- `COPY`: Simple file copy (recommended).  
- `ADD`: Can extract tar, fetch URLs (avoid unless needed; less predictable).<grok-card data-id="aafcbe" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**16. Docker daemon vs client?**  
Daemon (`dockerd`) does the work. Client sends commands via API. Can be remote.<grok-card data-id="ee190d" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**17. How to debug a running container?**  
- `docker logs`  
- `docker exec -it container sh`  
- Inspect with `docker inspect`  
- Check health checks, metrics.<grok-card data-id="08d909" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**18. What is `.dockerignore`?**  
Like `.gitignore` — excludes files from build context (reduces size, improves security/speed).<grok-card data-id="f88c3b" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

## Advanced / Scenario-Based Questions

**19. Docker Swarm vs Kubernetes?**  
Swarm: Native, simpler for basic orchestration. Kubernetes: More powerful, feature-rich (industry standard for complex deployments).<grok-card data-id="5a7668" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**20. Security best practices?**  
- Use official/minimal base images.  
- Run as non-root (`USER` instruction).  
- Scan images (Trivy, Clair).  
- Enable Content Trust (`DOCKER_CONTENT_TRUST=1`).  
- Least privilege, secrets management (not in images), network isolation, resource limits.  
- Regular updates.<grok-card data-id="8282b0" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**21. How to optimize Docker images?**  
- Multi-stage builds.  
- Small base images (alpine/slim).  
- Layer caching.  
- `.dockerignore`.  
- Remove unnecessary packages/files in `RUN` layers.  
- Use distroless where possible.<grok-card data-id="ed7600" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**22. Handling secrets?**  
Avoid baking into images. Use Docker secrets (Swarm), environment variables (with care), or external tools (Vault, AWS Secrets Manager). For Compose: `secrets` or env files.<grok-card data-id="719eb2" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**23. Container orchestration?**  
Automates deployment, scaling, networking, and management of containers. Docker Swarm (native) or Kubernetes (more common).<grok-card data-id="9db21c" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**24. Common production issues and troubleshooting?**  
- Resource limits (`--cpus`, `--memory`).  
- Logging drivers (json-file, syslog, etc.).  
- Restart policies (`--restart`).  
- Health checks in Compose/Dockerfile.  
- Monitor with `docker stats`, Prometheus, etc.  
- Out-of-disk, port conflicts, image bloat.<grok-card data-id="b68fd8" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**25. Difference between bind mounts and volumes?**  
Bind mounts: Direct host path (good for dev, security risks in prod). Volumes: Docker-managed (better for prod, portable).<grok-card data-id="b66a4b" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**26. Docker Content Trust (DCT)?**  
Verifies image signatures for integrity and authenticity.<grok-card data-id="32ca13" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**27. Scaling with Docker?**  
- Compose: `docker compose up --scale service=3`.  
- Swarm: `docker service scale`.  
- Orchestrators for advanced auto-scaling.<grok-card data-id="28c7fe" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**28. Explain Docker namespaces and cgroups.**  
Namespaces: Isolation (PID, network, mount, user, etc.).  
Cgroups: Resource control (CPU, memory, I/O).<grok-card data-id="839f23" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**29. Scenario: "App works locally but fails in container?"**  
Check: missing dependencies, port binding (`0.0.0.0`), permissions, volumes, environment variables, base image differences.<grok-card data-id="f106ca" data-type="citation_card" data-plain-type="render_inline_citation" ></grok-card>

**30. How have you used Docker in production?**  
(Behavioral) Discuss CI/CD pipelines (Jenkins/GitHub Actions), multi-stage builds, orchestration, monitoring, security practices, etc.

## Additional Tips for Interviews
- Know practical commands and common pitfalls (layer caching, image size, security).
- Be ready to discuss real-world use cases (microservices, CI/CD, data pipelines).
- Understand integration with tools like Kubernetes, Jenkins, Prometheus.
- Practice writing Dockerfiles and Compose files.

This covers **most common questions** (basic to advanced). Focus on understanding *why* things w

Here is a comprehensive list of Docker interview questions and answers, categorized by experience level (beginner, intermediate, advanced). Each answer includes sufficient detail to help you understand the concept fully.


🟢 Beginner Level (Fundamentals)

1. What is Docker? Why is it used?

Answer:
Docker is an open-source platform that automates the deployment, scaling, and management of applications inside containers. It packages an application with all its dependencies (libraries, binaries, config files) into a standardized unit.

Why used?

  • Portability – Runs the same on any system (dev, test, prod).
  • Isolation – Each container is independent.
  • Efficiency – Lightweight (shares OS kernel) vs. VMs.
  • Consistency – Eliminates “works on my machine” problems.

2. Difference between Docker Container and Virtual Machine?

FeatureContainerVM
OSShares host OS kernelEach VM has full guest OS
SizeMBs (lightweight)GBs (heavy)
Boot timeSecondsMinutes
IsolationProcess-levelHardware-level
Resource usageLowHigh

3. What is a Docker Image?

Answer:
A Docker image is a read-only template containing the application, runtime, system tools, libraries, and settings. Images are built from a Dockerfile and stored in a registry (e.g., Docker Hub). When you run an image, you get a container (writable layer added on top).

4. What is a Dockerfile? Give an example.

Answer:
Dockerfile is a text script with instructions to build a Docker image.

Example:

dockerfile

# Use official Python image
FROM python:3.9-slim

# Set working directory
WORKDIR /app

# Copy requirements first (for caching)
COPY requirements.txt .

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy the rest of the app
COPY . .

# Expose port
EXPOSE 5000

# Run application
CMD ["python", "app.py"]

5. Common Docker Commands?

CommandPurpose
docker pull <image>Download image from registry
docker build -t name .Build image from Dockerfile
docker run -d -p 80:80 nameRun container in background with port mapping
docker psList running containers
docker ps -aList all containers
docker stop <id>Stop container
docker rm <id>Remove container
docker rmi <image>Remove image
docker logs <id>View container logs
docker exec -it <id> bashAccess shell inside running container

🟡 Intermediate Level (Working with Docker)

6. Explain Docker Architecture.

Answer:

  • Docker Client – CLI commands (docker run, etc.)
  • Docker Daemon (dockerd) – Background service that manages containers, images, networks, volumes.
  • Docker Registry – Stores images (public like Docker Hub, or private).
  • Containerd – High-level container runtime (handles image transfer, execution).
  • Runc – Low-level runtime that interacts with kernel namespaces/cgroups.

Flow: Client → REST API → Daemon → Containerd → Runc → OS Kernel.

7. What is a Docker Hub?

Answer:
Docker Hub is the default public registry where you can:

  • Pull official images (Ubuntu, MySQL, Node.js, etc.)
  • Push your own images after docker login
  • Automate builds from GitHub/Bitbucket.

8. How do you manage persistent data in Docker?

Answer:

  • Volumes (recommended): Managed by Docker. Stored in /var/lib/docker/volumes/.bashdocker volume create mydata docker run -v mydata:/data myapp
  • Bind mounts: Map host directory directly.bashdocker run -v /host/path:/container/path myapp
  • tmpfs mounts: Stored in memory (temporary).

9. Difference between CMD and ENTRYPOINT?

CMDENTRYPOINT
PurposeDefault argumentsFixed command
OverrideCan be overridden by docker run argsCan be overridden with --entrypoint
ExampleCMD ["npm", "start"]ENTRYPOINT ["python"]
CombinedIf both exist, CMD becomes args to ENTRYPOINTUse ENTRYPOINT ["python"] + CMD ["app.py"]

Example:

dockerfile

ENTRYPOINT ["ping"]
CMD ["google.com"]

docker run myimage → ping google.com
docker run myimage localhost → ping localhost

10. How to reduce Docker image size?

Answer:

  1. Use alpine-based images (node:alpinepython:3.9-alpine).
  2. Multi-stage builds – separate build vs. runtime.
  3. Combine RUN commands – fewer layers.
  4. Remove package manager caches (apt-get cleanrm -rf /var/lib/apt/lists/*).
  5. Use .dockerignore to exclude unnecessary files.
  6. Use --squash (experimental) or docker build --squash.

Multi-stage example:

dockerfile

# Stage 1: build
FROM golang:alpine AS builder
COPY . /src
RUN go build -o myapp

# Stage 2: runtime (much smaller)
FROM alpine
COPY --from=builder /src/myapp /myapp
CMD ["/myapp"]

🔴 Advanced Level (Production & Orchestration)

11. Explain Docker Networking modes.

ModeDescription
bridge (default)Private internal network. Containers can communicate via IP. Ports manually mapped with -p.
hostContainer uses host’s network stack directly. No isolation but better performance.
noneNo network (loopback only).
overlayConnects containers across multiple Docker hosts (used in Swarm/Kubernetes).
macvlanAssigns a real MAC address to container, appears as physical device on network.

Create custom bridge network:

bash

docker network create --driver bridge mynet
docker run --network=mynet myapp

12. What is Docker Compose? Give an example.

Answer:
Docker Compose is a tool to define and run multi-container Docker applications using a YAML file.

Example docker-compose.yml:

yaml

version: '3.8'
services:
  web:
    build: .
    ports:
      - "5000:5000"
    depends_on:
      - redis
      - db
  redis:
    image: redis:alpine
  db:
    image: postgres:13
    environment:
      POSTGRES_PASSWORD: secret
    volumes:
      - pgdata:/var/lib/postgresql/data
volumes:
  pgdata:

Commands:

  • docker-compose up -d – start in background
  • docker-compose down – stop and remove
  • docker-compose logs – view logs

13. How do you implement health checks in Docker?

Answer:
In Dockerfile:

dockerfile

HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
  CMD curl -f http://localhost/ || exit 1

Or in docker-compose.yml:

yaml

services:
  web:
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost"]
      interval: 30s
      timeout: 5s
      retries: 3

Check status: docker ps shows (healthy) / (unhealthy).

14. What are the security best practices for Docker?

Answer:

  • Run as non-root – add USER appuser in Dockerfile.
  • Use trusted images – official or verified.
  • Keep images updated – regularly rebuild with patches.
  • Limit container capabilities – drop all, add only needed:bashdocker run –cap-drop=ALL –cap-add=NET_ADMIN …
  • Use secrets – Docker secrets or environment variables from files.
  • Enable user namespace remapping – map container root to non-root on host.
  • Read-only root filesystemdocker run --read-only ...
  • Scan imagesdocker scan (Snyk) or trivy.

15. How to debug a failing container?

Answer:

  1. Check logs: docker logs <container>
  2. Inspect exit code: docker inspect <container> --format='{{.State.ExitCode}}'
  3. Run interactive shell on same image:bashdocker run -it myimage /bin/sh
  4. Override entrypoint: docker run --entrypoint /bin/sh myimage
  5. Check resource limits: docker stats
  6. For stopped container, commit to new image and debug:bashdocker commit stopped-container debug-image docker run -it debug-image /bin/bash

16. Difference between Docker Swarm and Kubernetes?

FeatureDocker SwarmKubernetes
ComplexitySimple, built into DockerSteeper learning curve
Installationdocker swarm initRequires separate setup (kubeadm, minikube, etc.)
ScalabilityGood for small/mediumEnterprise-grade, auto-scaling, self-healing
NetworkingOverlay network, simplerCNI plugins, more flexible (Calico, Flannel)
Load balancingInternal round-robinIngress controllers, services
StorageVolumes, limitedCSI drivers, many options
Market adoptionLowIndustry standard

17. Explain Docker’s storage driver and copy-on-write (CoW).

Answer:
Docker uses Copy-on-Write to save space. When a container modifies a file from the read-only image:

  1. The file is copied to the container’s writable layer.
  2. Modifications are made only in writable layer.
  3. Image layers remain unchanged.

Common storage drivers:

  • overlay2 (default on Linux) – most efficient.
  • aufsdevicemapperbtrfszfs.

To check: docker info | grep "Storage Driver"

18. How to migrate Docker containers from one host to another?

Answer:
Method 1: Save & Load image

bash

# On source host
docker commit container-name myimage:v1
docker save -o myimage.tar myimage:v1
scp myimage.tar user@dest-host:/tmp/

# On destination host
docker load -i myimage.tar
docker run myimage:v1

Method 2: Export/Import (loses layer history)

bash

docker export container-name > container.tar
cat container.tar | docker import - mynewimage:v1

Method 3: Use registry (best)

bash

docker tag myimage myregistry.com/myimage:v1
docker push myregistry.com/myimage:v1
# On new host
docker pull myregistry.com/myimage:v1

19. What is the difference between docker rundocker start, and docker create?

  • docker create – Creates container from image (state = created). Does not run it.
  • docker start – Starts an existing (stopped/created) container.
  • docker run = docker create + docker start (plus attaches logs).

20. How to limit container resources?

Answer:

bash

# Memory limit
docker run --memory="512m" --memory-swap="1g" myapp

# CPU limit (4 CPU cores max)
docker run --cpus="4" myapp

# CPU share weighting (relative)
docker run --cpu-shares=1024 myapp

# Block IO (read/write)
docker run --device-read-bps=/dev/sda:1mb myapp

Check current usage: docker stats


🎯 Bonus: Scenario-Based Questions

Q: Your container exits immediately after starting. How do you investigate?

A:

  • Check logs: docker logs <container>
  • Run interactively: docker run -it myimage /bin/sh then run the CMD manually.
  • Override CMD to a sleep command: docker run myimage sleep 3600, then docker exec into it.
  • Inspect OOM killer: docker inspect <container> --format='{{.State.OOMKilled}}'

Q: Multiple containers need to share data. How?

A:

  • Named volume mounted to all:bashdocker volume create shared docker run -v shared:/data container1 docker run -v shared:/data container2
  • Bind mount the same host directory to all.
  • For read-only sharing, mount same volume as ro in some containers.

Q: How to make sure Docker daemon starts on boot?

A:

bash

# On Linux (systemd)
sudo systemctl enable docker
sudo systemctl start docker

# On Windows/macOS (Docker Desktop)
Set in settings: "Start Docker Desktop when you log in"

📌 Quick Reference Card

ConceptKey Command / File
Build imagedocker build -t name:tag .
Run with portdocker run -p host:container
List imagesdocker images
Remove unuseddocker system prune -a
Copy file to/from containerdocker cp <container>:<path> <host>
View layersdocker history <image>
Inspect low-level detailsdocker inspect <container>
Save image to tardocker save -o file.tar image
Load tar to imagedocker load -i file.tar

🤞 Sign up for our newsletter!

We don’t spam! Read more in our privacy policy

Scroll to Top