Docker has become an essential technology in modern software development and deployment. Whether you’re preparing for your first interview or advancing your career, mastering Docker concepts is crucial. This comprehensive guide covers 30 interview questions spanning basic to advanced levels, with clear explanations suitable for freshers, mid-level professionals, and experienced developers.
Basic Docker Concepts
1. What are Docker containers?
Docker containers are lightweight, portable, and isolated environments that package applications along with their dependencies. Unlike virtual machines, containers share the host operating system kernel, making them more efficient in terms of resource usage and startup time. Each container runs in isolation, ensuring that applications don’t interfere with one another.
2. What is a Dockerfile?
A Dockerfile is a text file containing a series of instructions to build a Docker image. Each command in the Dockerfile creates a new layer in the image. These instructions define the base operating system, dependencies, application code, ports, and startup commands needed for your application.
3. How do you create a Docker container from a Docker image?
You use the docker run command to create and start a container from an image. The basic syntax is docker run [image_name]. For interactive containers, you can use the -it flag: docker run -it [image_name]. To run a container in the background (detached mode), use the -d flag: docker run -d [image_name].
4. What is the difference between a Docker image and a Docker container?
A Docker image is a read-only blueprint or template used to create containers. It contains all the code, runtime, libraries, and dependencies needed for an application. A Docker container is a running instance of an image. You can create multiple containers from a single image, and each container is isolated from others.
5. What does the -d flag mean in Docker commands?
The -d flag stands for “detached mode.” When you use this flag with docker run, the container starts in the background, and you regain control of your terminal. Without this flag, the container runs in the foreground, and you see its output directly in your terminal.
6. How do you list all running containers?
Use the command docker ps to list all currently running containers. To view all containers (including stopped ones), use docker ps -a. This command displays container IDs, names, images used, status, and other useful information.
7. How do you check the Docker version?
Use the docker version command to display information about both the Docker client and server versions. You can also use docker info to get more detailed information about your Docker installation, including the number of running containers, images, storage driver, and other system-level details.
8. What is Docker Engine?
Docker Engine is an open-source containerization technology that allows you to build and run containerized applications. It consists of three main components: the Docker Daemon (a background service that manages containers), the Docker Command-Line Interface (CLI) for user interaction, and the Docker Engine REST API for programmatic access.
9. What is a Docker layer?
A Docker layer is an intermediate image created by each instruction in a Dockerfile. When you build a Docker image, each command (FROM, RUN, COPY, etc.) creates a new layer on top of the previous one. These layers are stacked to form the final image. Docker uses layer caching to speed up image builds when layers haven’t changed.
10. What is a Docker namespace?
A namespace is a Linux feature that provides isolation for containers. Docker uses several types of namespaces: PID (process isolation), Mount (filesystem isolation), IPC (inter-process communication), User (user privilege isolation), and Network (network interface isolation). Namespaces ensure that containers remain isolated from each other and the host system.
Intermediate Docker Concepts
11. How do you write a Dockerfile? Provide an example.
A typical Dockerfile follows this structure:
# Step 1: Choose a base image
FROM python:3.9-slim
# Step 2: Specify the working directory
WORKDIR /app
# Step 3: Copy project files into the container
COPY . .
# Step 4: Install dependencies
RUN pip install -r requirements.txt
# Step 5: Expose the port the app runs on
EXPOSE 5000
# Step 6: Define the default command
CMD ["python", "app.py"]
Each instruction builds a layer. The FROM instruction specifies the base image, WORKDIR sets the working directory, COPY transfers files, RUN executes commands, EXPOSE declares ports, and CMD defines the default startup command.
12. What is the difference between CMD and ENTRYPOINT in a Dockerfile?
Both CMD and ENTRYPOINT specify the default command to run when a container starts, but they work differently. CMD provides default arguments and can be overridden easily when running a container. ENTRYPOINT is the primary command that always executes, though its arguments can be overridden. Best practice: use ENTRYPOINT for the main process and CMD for default arguments.
13. What is the difference between COPY and ADD commands in a Dockerfile?
Both commands copy files from the host to the container, but ADD has additional features. ADD can handle remote URLs and automatically extract compressed files (tar, gzip, etc.), while COPY only copies local files. For most use cases, COPY is preferred because it’s more predictable and transparent about what it does.
14. How do you stop a running container?
Use the docker stop [container_id_or_name] command to gracefully stop a container. The container receives a SIGTERM signal and is given time to shut down. If you need to force-stop a container immediately, use docker kill [container_id_or_name], which sends a SIGKILL signal.
15. What is the difference between docker run and docker create?
docker create creates a container from an image but does not start it. The container remains in a stopped state. docker run both creates and starts the container immediately. After using docker create, you must use docker start to run the container.
16. How do you push a Docker image to a registry?
Use the docker push [repository_name]/[image_name]:[tag] command. Before pushing, ensure you’ve tagged your image correctly. For example: docker tag myapp:1.0 myregistry/myapp:1.0 followed by docker push myregistry/myapp:1.0. You must be authenticated to the registry before pushing.
17. What is Docker Compose and when would you use it?
Docker Compose is a tool for defining and running multi-container Docker applications using a YAML configuration file. Instead of running multiple docker run commands, you define all services in a single docker-compose.yml file. It’s ideal for development environments, testing, and scenarios where your application requires multiple interdependent containers.
18. What is the difference between expose and publish in Docker?
EXPOSE in a Dockerfile documents which ports the container listens on, but it doesn’t actually publish the ports. Publish (using the -p flag in docker run) actually maps container ports to host ports, making them accessible from outside. For example: docker run -p 8080:5000 maps port 5000 inside the container to port 8080 on the host.
19. What is a Docker volume and why is it important?
A Docker volume is a mechanism for persisting data generated by a container. Unlike container filesystems (which are ephemeral and deleted when the container stops), volumes persist across container restarts. Volumes are essential for databases, configurations, and any data that should survive beyond the container’s lifecycle.
20. What is the difference between a repository and a registry in Docker?
A registry is a centralized service that stores Docker images (like Docker Hub or a private registry). A repository is a collection of related images within a registry, typically grouped by application name or function. For example, in Docker Hub, “library/ubuntu” is a repository within the Docker Hub registry.
21. How do you remove a Docker container?
Use docker rm [container_id_or_name] to remove a stopped container. To remove a running container, use docker rm -f [container_id_or_name] (the -f flag forces removal). Be careful: removing a container also removes any data stored in the container that wasn’t persisted in a volume.
22. What is build cache in Docker?
Docker build cache stores intermediate layers from previous builds. When rebuilding an image, Docker reuses unchanged layers instead of rebuilding them. This significantly speeds up subsequent builds. However, if a layer changes, all subsequent layers are rebuilt. You can disable caching with the --no-cache flag: docker build --no-cache .
23. How do you transfer a Docker image between machines without using a repository?
Use the docker save and docker load commands. First, save the image to a tar file: docker save myimage:latest > myimage.tar. Then transfer the file to another machine and load it: docker load < myimage.tar. This method works for private images or when you don't want to use a registry.
24. What happens to data when a Docker container exits?
Data stored in the container's filesystem is lost when the container is removed. However, data stored in volumes persists even after the container stops or is deleted. For any important data, always use volumes or bind mounts to ensure persistence beyond the container's lifecycle.
Advanced Docker Concepts
25. How do you link containers in Docker?
Container linking is an older Docker feature (now largely replaced by user-defined networks). Using the --link flag in docker run, you can connect containers: docker run --link [container_name]:[alias] [image]. Modern best practice is to create a user-defined bridge network and connect containers to it, as networks provide better isolation and flexibility.
26. What is the difference between Docker and virtual machines?
Docker containers share the host operating system kernel, making them lightweight and fast. Virtual machines include a complete OS, making them heavier but providing stronger isolation. Containers start in seconds while VMs take minutes. Containers are more resource-efficient, but VMs offer better isolation for untrusted or diverse workloads.
27. Explain Docker's basic usage workflow.
The typical Docker workflow involves: (1) Creating a Dockerfile with build instructions, (2) Building an image from the Dockerfile using docker build, (3) Running containers from the image using docker run, (4) Managing containers with commands like docker stop and docker rm, (5) Optionally pushing images to a registry for sharing and deployment.
28. What are Docker namespaces and how do they provide isolation?
Docker uses Linux namespaces to isolate containers. PID namespace isolates process IDs so containers have their own process tree. Mount namespace isolates filesystem views. IPC namespace isolates inter-process communication. User namespace isolates user IDs and permissions. Network namespace isolates network interfaces and routing tables. Together, these namespaces ensure complete isolation between containers.
29. How do you limit CPU and memory for a Docker container?
Use the -m or --memory flag to limit memory and --cpus to limit CPU. For example: docker run -m 512m --cpus 1 myimage limits the container to 512MB of memory and 1 CPU core. You can also use --memory-swap for swap memory limits. These limits prevent a single container from consuming all host resources.
30. Is it a good practice to run stateful applications on Docker?
Running stateful applications (like databases) on Docker is possible but requires careful planning. Challenges include managing persistent data, handling replication and backups, and ensuring data consistency. Best practice: use volumes or bind mounts for data persistence, implement proper backup strategies, and consider managed services for critical stateful workloads. Docker is better suited for stateless applications that scale horizontally.
31. How do you implement multi-stage builds in Docker?
Multi-stage builds use multiple FROM statements in a single Dockerfile to optimize image size. Each stage can use different base images and dependencies. You copy only necessary artifacts from earlier stages to the final image. For example:
# Stage 1: Build
FROM python:3.9 AS builder
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
# Stage 2: Runtime
FROM python:3.9-slim
WORKDIR /app
COPY --from=builder /app /app
CMD ["python", "app.py"]
This approach significantly reduces final image size by excluding build tools and dependencies from the runtime image.
32. What security measures should you implement for Docker containers?
Key security practices include: (1) Using distroless or minimal base images with fewer packages to reduce attack surface, (2) Running containers as non-root users rather than root, (3) Using read-only filesystems where possible, (4) Implementing resource limits to prevent denial-of-service, (5) Scanning images for vulnerabilities, (6) Keeping base images and dependencies updated, (7) Using security scanning tools and image signing for integrity verification.
33. How do you handle secrets and sensitive data in Docker?
Never hardcode secrets in Dockerfiles or images. Instead: (1) Use environment variables passed at runtime via -e flag or env files, (2) Use Docker Secrets in Docker Swarm for orchestrated environments, (3) Implement secret management tools like HashiCorp Vault, (4) Use build arguments for non-sensitive configuration and secrets only for runtime values, (5) Avoid logging or exposing sensitive data in container output.
34. Explain the Docker container lifecycle.
A Docker container goes through several states: Created (after docker create), Running (after docker start or docker run), Paused (after docker pause), Stopped (after docker stop), and Removed (after docker rm). Understanding these states helps you manage containers effectively. You can restart stopped containers, unpause paused containers, and monitor their current state with docker ps.
35. What is the purpose of the ONBUILD instruction in a Dockerfile?
The ONBUILD instruction specifies commands that should be executed when a derived image (built FROM this image) is created. It's useful for creating base images that automatically run setup steps. For example, a base application image might have ONBUILD COPY and ONBUILD RUN commands that execute when child images are built, ensuring consistent setup across all derived images.
Conclusion
Mastering Docker requires understanding concepts from basic container creation to advanced security and optimization techniques. These 35 questions cover the essential knowledge needed for Docker interviews at various experience levels. Focus on understanding the "why" behind each concept, and practice hands-on implementation to reinforce your learning. Regular practice with real-world scenarios will make you confident in Docker-related interviews.