Docker Interview Questions and Answers
What is Docker?
- Docker is an open-source platform that automates the deployment, scaling, and management of applications using containerization.
What is containerization?
- Containerization is a lightweight form of virtualization that packages an application and its dependencies into a self-contained unit (a container) that can run consistently across different environments.
How is containerization different from virtualization (VMs)?
- VMs: Virtualize the entire operating system and hardware. Each VM has its own OS kernel. They are heavier and slower to start.
- Containers: Share the host OS kernel. They package only the application and its dependencies. They are lightweight, faster to start, and use fewer resources.
What are the key components of Docker?
- Docker Engine: The core runtime for building and running containers. It includes the Docker Daemon, Docker Client, and REST API.
- Docker Images: Read-only templates with instructions for creating a container.
- Docker Containers: Runnable instances of Docker images.
- Docker Registry: A repository for storing and sharing Docker images (e.g., Docker Hub).
- Dockerfile: A script containing instructions to build a Docker image.
What is a Docker Image?
- A Docker Image is a lightweight, stand-alone, executable package that includes everything needed to run a piece of software, including the code, runtime, libraries, environment variables, and config files. Images are built from Dockerfiles.
What is a Docker Container?
- A Docker Container is a runnable instance of a Docker Image. It is an isolated process running on the host system, with its own filesystem, network interface, and process space.
What is a Dockerfile?
- A Dockerfile is a text file that contains a set of instructions that Docker uses to build a Docker image. Each instruction in a Dockerfile creates a layer in the image.
What is Docker Hub?
- Docker Hub is a cloud-based registry service provided by Docker where you can find, store, and share Docker images (both public and private).
What is the Docker Daemon?
- The Docker Daemon (
dockerd
) is the background process that runs on the host machine. It listens for Docker API requests and manages Docker objects like images, containers, networks, and volumes.
What is the Docker Client?
- The Docker Client is the primary command-line interface (CLI) that users interact with. It sends commands to the Docker Daemon, which performs the requested actions.
How do you run a Docker container?
- Using the command:
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
.
Explain the docker run
command and its common options.
docker run
: Creates and starts a new container from a specified image.-d
: Run container in detached mode (in the background).-p host_port:container_port
: Publish a container's port(s) to the host.-v host_path:container_path
: Mount a volume (bind mount or named volume).--name container_name
: Assign a name to the container.-it
: Run container interactively (allocate a pseudo-TTY and keep STDIN open).--rm
: Automatically remove the container when it exits.--env KEY=VALUE
or-e KEY=VALUE
: Set environment variables.
How do you list running Docker containers?
docker ps
.
How do you list all Docker containers (including stopped ones)?
docker ps -a
.
How do you list Docker images on your system?
docker images
.
How do you stop a running container?
docker stop container_id_or_name
.
How do you remove a container?
docker rm container_id_or_name
(the container must be stopped first, or use-f
to force removal).
How do you remove a Docker image?
docker rmi image_id_or_name
.
How do you pull an image from Docker Hub?
docker pull image_name[:tag]
.
How do you push an image to Docker Hub?
- First, tag the image with your Docker Hub username:
docker tag local_image_name[:tag] your_dockerhub_username/image_name[:tag]
. - Then, push the tagged image:
docker push your_dockerhub_username/image_name[:tag]
.
What is the purpose of the CMD
instruction in a Dockerfile?
CMD
provides default arguments for an executing container. There can only be oneCMD
instruction in a Dockerfile. If you provide arguments todocker run
, they will override theCMD
.
What is the purpose of the ENTRYPOINT
instruction in a Dockerfile?
ENTRYPOINT
configures a container that will run as an executable. Arguments passed todocker run
are appended to theENTRYPOINT
command. It's often used to define the main command, whileCMD
provides default arguments to that command.
What is the difference between CMD
and ENTRYPOINT
?
CMD
: Defines the default command or arguments for a container. Overridden bydocker run
arguments.ENTRYPOINT
: Defines the command that will always be executed when the container starts.docker run
arguments are appended to theENTRYPOINT
.
What is the purpose of the RUN
instruction in a Dockerfile?
RUN
executes commands during the image build process. EachRUN
instruction creates a new layer in the image. Used for installing packages, compiling code, etc.
What is the purpose of the COPY
instruction?
COPY source_path destination_path
copies files or directories from the source (host machine) to the filesystem of the image at the specified destination.
What is the purpose of the ADD
instruction?
ADD source_path destination_path
is similar toCOPY
but has additional features: it can extract tar files and can copy files from a URL. Generally,COPY
is preferred unless you need these extra features.
What is the purpose of the WORKDIR
instruction?
WORKDIR /path/to/directory
sets the working directory for any subsequentRUN
,CMD
,ENTRYPOINT
,COPY
, andADD
instructions in the Dockerfile.
What is the purpose of the EXPOSE
instruction?
EXPOSE port_number
informs Docker that the container listens on the specified network ports at runtime. It does *not* publish the port to the host; it's documentation and can be used by the-P
(publish all exposed ports) option indocker run
.
What is the purpose of the ENV
instruction?
ENV KEY=VALUE
sets environment variables inside the Docker image (and thus in the running container).
What is the purpose of the VOLUME
instruction?
VOLUME /path/in/container
creates a mount point with the specified name and marks it as holding externally mounted volumes. This is used to persist data generated by and used by Docker containers.
What are Docker Image Layers?
- Docker Images are built up from a series of read-only layers. Each instruction in a Dockerfile typically creates a new layer. When a container is created from an image, a thin, writable layer is added on top of the image layers.
How does Docker optimize builds using layers?
- Docker caches layers. When building an image, if a layer hasn't changed since the last build (the instruction and its context are the same), Docker reuses the cached layer instead of executing the instruction again. This significantly speeds up builds.
What is the difference between a bind mount and a volume mount?
- Bind Mount: Mounts a file or directory from the host machine directly into the container. The host file/directory path must exist. Less portable as it depends on the host's filesystem structure.
- Volume Mount: Docker manages the storage on the host machine (usually in
/var/lib/docker/volumes/
). Docker creates the volume if it doesn't exist. More portable and the preferred way for persisting container data.
How do you create a named volume?
docker volume create volume_name
.
How do you use a named volume with docker run
?
docker run -v volume_name:/path/in/container image_name
.
How do you use a bind mount with docker run
?
docker run -v /host/path:/path/in/container image_name
.
What is the default network mode for Docker containers?
bridge
network mode. Each container gets its own IP address and can communicate with other containers on the same bridge network.
How do you publish a container port to the host?
- Using the
-p
option:docker run -p host_port:container_port image_name
.
How do you link containers (deprecated)?
- Using the
--link
option (e.g.,docker run --link db_container:db image_name
). This is now deprecated in favor of user-defined networks.
How do you create a user-defined network?
docker network create network_name
.
How do you connect a container to a user-defined network?
- Using the
--network
option:docker run --network network_name image_name
.
How do containers on the same user-defined network resolve each other?
- By their container names (using Docker's built-in DNS server).
What is Docker Compose?
- Docker Compose is a tool for defining and running multi-container Docker applications. It uses a YAML file (
docker-compose.yml
) to configure the application's services, networks, and volumes.
What is the main file used by Docker Compose?
docker-compose.yml
.
What is the command to start services defined in a docker-compose.yml
file?
docker-compose up
.
What is the command to stop and remove services, networks, and volumes defined in a Compose file?
docker-compose down
.
How do you rebuild images defined in a Compose file?
docker-compose up --build
ordocker-compose build
.
What is Docker Swarm?
- Docker Swarm is Docker's native clustering and orchestration solution. It allows you to create a swarm of Docker nodes (managers and workers) and deploy and manage services across them.
What is a Docker Swarm Service?
- A service in Docker Swarm is the definition of the tasks to be executed on manager or worker nodes. It defines which Docker image to use, the number of replicas, ports, volumes, networks, etc.
What is a Docker Swarm Task?
- A task is the atomic unit of scheduling in a Swarm. It contains a single Docker container and the commands to run inside it.
How do you initialize a Docker Swarm?
docker swarm init
(on the manager node).
How do you add a worker node to a Swarm?
- Run the command provided by
docker swarm init
on the worker node.
How do you deploy a stack (multi-service application) to a Swarm?
- Using a version 3 Compose file and the command:
docker stack deploy -c your_compose_file.yml stack_name
.
How do you scale a service in Docker Swarm?
docker service scale service_name=number_of_replicas
or by updating the stack definition in the Compose file and redeploying.
What is Kubernetes and how does it relate to Docker?
- Kubernetes is a powerful open-source container orchestration platform. While Docker is focused on building and running individual containers, Kubernetes is focused on managing and orchestrating containerized applications at scale across clusters of machines. Kubernetes can run Docker containers (and other container runtimes).
What are some best practices for writing Dockerfiles?
- Use smaller base images (e.g., Alpine).
- Combine
RUN
instructions where possible to reduce layers. - Order instructions from least-frequently to most-frequently changing to leverage caching.
- Use
.dockerignore
to exclude unnecessary files. - Run applications as non-root users.
- Use multi-stage builds to separate build-time dependencies from runtime dependencies.
What is a multi-stage build?
- A multi-stage build is a Dockerfile technique where you use multiple
FROM
statements. EachFROM
instruction starts a new build stage. You can selectively copy artifacts from one stage to another, allowing you to discard build-time dependencies in the final image, resulting in a smaller image.
What is the purpose of the .dockerignore
file?
- The
.dockerignore
file specifies files and directories that should be excluded when the Docker client sends the build context to the Docker daemon. This helps speed up the build process and keep the image size smaller.
How do you inspect a running container?
docker inspect container_id_or_name
. This provides detailed information about the container's configuration, state, network settings, etc.
How do you view the logs of a container?
docker logs container_id_or_name
.
How do you execute a command inside a running container?
docker exec container_id_or_name command
.
How do you attach to a running container's standard input, output, and error streams?
docker attach container_id_or_name
. Be cautious, exiting this can stop the container depending on the container's CMD/ENTRYPOINT.
What is the difference between docker stop
and docker kill
?
docker stop
: Sends aSIGTERM
signal to the container's main process, allowing it to gracefully shut down. After a timeout, it sends aSIGKILL
.docker kill
: Sends aSIGKILL
signal to the container's main process, forcing an immediate shutdown without allowing for graceful cleanup.
How do you remove all stopped containers?
docker container prune
.
How do you remove all unused images?
docker image prune
ordocker image prune -a
(to remove all dangling and unused images).
How do you remove all unused volumes?
docker volume prune
.
How do you remove all unused networks?
docker network prune
.
What is the command to remove all unused Docker objects (containers, images, volumes, networks)?
docker system prune
. Usedocker system prune -a
to also remove stopped containers and all unused images (not just dangling ones).
What are dangling images?
- Dangling images are layers that have no relationship to any tagged image. They often occur after rebuilding an image without removing the old layers. They can be removed using
docker image prune
.
How do you build a Docker image without using the cache?
- Use the
--no-cache
option withdocker build
:docker build --no-cache .
.
How do you build a Docker image from a specific directory?
docker build /path/to/build/context
(where the Dockerfile is located).
How do you build a Docker image from a Dockerfile located in a different directory or with a different name?
docker build -f /path/to/Dockerfile .
(the.
indicates the build context).
What is the Docker build context?
- The build context is the set of files and directories at the specified location (usually the current directory
.
) that are sent to the Docker daemon during the build process. The Dockerfile is also part of the build context.
How do you set environment variables when running a container?
- Using the
-e KEY=VALUE
or--env KEY=VALUE
option withdocker run
.
How do you set environment variables in a Dockerfile?
- Using the
ENV KEY=VALUE
instruction.
What is the purpose of the HEALTHCHECK
instruction in a Dockerfile?
HEALTHCHECK
specifies a command that Docker should run inside the container to check if it's healthy and functioning correctly. Docker will periodically run this command, and if it exits with a non-zero status, the container is marked as unhealthy.
What is the difference between CMD ["executable", "param1", "param2"]
(exec form) and CMD command param1 param2
(shell form)?
- Exec form: The command is run directly as the container's main process (PID 1). Recommended as it allows signals (like SIGTERM) to be properly received.
- Shell form: The command is run inside a shell (e.g.,
/bin/sh -c command
). The shell becomes PID 1, and signals may not be properly handled by your application process.
What is the purpose of the STOPSIGNAL
instruction?
STOPSIGNAL signal
sets the system call signal that will be sent to the container to exit. Defaults toSIGTERM
.
What is the purpose of the ARG
instruction?
ARG name[=default value]
defines a variable that can be passed to the build process using the--build-arg VARNAME=value
flag withdocker build
.ARG
variables are only available during the build process and do not persist in the final image.
What is the difference between ENV
and ARG
?
ENV
: Defines environment variables that are available both during the build process and in the running container.ARG
: Defines build-time variables that are only available during the build process and are not accessible in the running container.
How can you limit resources (CPU, memory) for a container?
-
Using options with
docker run
:--memory LIMIT
(e.g.,--memory 512m
)--cpus NUMBER
(e.g.,--cpus 1.5
)--cpu-shares WEIGHT
What is the purpose of the --restart
option in docker run
?
--restart
defines the restart policy for the container (e.g.,no
,on-failure
,always
,unless-stopped
). It determines how Docker should handle the container if it stops.
How do you copy files between a host and a container?
-
Using the
docker cp
command:- Host to container:
docker cp /host/path container_id_or_name:/container/path
- Container to host:
docker cp container_id_or_name:/container/path /host/path
- Host to container:
What is the purpose of the docker save
command?
docker save image_name > image.tar
saves one or more images to a tar archive. Useful for transferring images without a registry.
What is the purpose of the docker load
command?
docker load < image.tar
loads an image from a tar archive created bydocker save
.
What is the purpose of the docker export
command?
docker export container_id_or_name > container.tar
exports a container's filesystem as a tar archive. It does not include the history or metadata of the image layers.
What is the purpose of the docker import
command?
docker import container.tar image_name
imports the contents of a tarball created bydocker export
to create a filesystem image.
What is the difference between docker save/load
and docker export/import
?
save/load
: Works with Docker Images, preserving layers and history.export/import
: Works with container filesystems, creating a flat image without history.
What is the purpose of the docker stats
command?
docker stats
displays a live stream of resource usage statistics (CPU, memory, network I/O, block I/O) for running containers.
What is the purpose of the docker events
command?
docker events
displays a live stream of events from the Docker daemon (e.g., container start, stop, image pull, push).
What is the purpose of the docker version
command?
docker version
displays version information for the Docker client and daemon.
What is the purpose of the docker info
command?
docker info
displays system-wide information about the Docker installation, including the number of containers, images, storage driver, etc.
What is the storage driver in Docker?
- The storage driver manages how Docker images and containers are stored on the host machine. It handles the layering and copy-on-write filesystem. Examples include OverlayFS, AUFS, Device Mapper.
What is the copy-on-write (CoW) strategy in Docker?
- CoW is a strategy used by storage drivers. When a container writes to a file in one of the image layers, the file is copied from the image layer to the container's writable layer, and the change is made there. The original file in the image layer remains unchanged. This optimizes storage and allows multiple containers to share the same image layers.
What is the purpose of docker network inspect
?
docker network inspect network_name_or_id
provides detailed information about a specific Docker network, including connected containers.
What is the purpose of the --link-local-ip
option? (Deprecated)
- This option was used with
--link
to specify a specific IP address to use for linking containers. Deprecated in favor of user-defined networks.
What is the purpose of the --network host
option?
--network host
makes the container share the host's network stack. The container's network is not isolated from the host. The container can access services running on the host usinglocalhost
, and vice versa.
What is the purpose of the --network none
option?
--network none
disables networking for the container. It will not have a network interface.
What is the purpose of the docker commit
command?
docker commit container_id_or_name new_image_name[:tag]
creates a new image from the current state of a running or stopped container. While useful for debugging, it's generally not recommended for production as it doesn't provide a clear history of how the image was built (unlike a Dockerfile).
What is the recommended way to build Docker images?
- Using Dockerfiles. This provides a clear, repeatable, and versionable process for building images.
What is the purpose of the LABEL
instruction in a Dockerfile?
LABEL key="value"
adds metadata to an image. This can be used for various purposes like specifying the maintainer, version, or other information.
What is the purpose of the USER
instruction?
USER username
sets the user and/or group to use when running the image and for anyRUN
,CMD
, andENTRYPOINT
instructions that follow it in the Dockerfile. Running containers as non-root is a security best practice.
What is the purpose of the SHELL
instruction?
SHELL ["executable", "parameters"]
allows you to override the default shell used for the shell form ofRUN
,CMD
, andENTRYPOINT
instructions.
What is the purpose of the ARG DOCKER_BUILDKIT=1
environment variable?
- Setting this environment variable (usually before the
docker build
command) enables BuildKit, a next-generation build engine for Docker that offers performance improvements, concurrent builds, and new features like multi-stage build outputs and caching.
What is the difference between docker-compose exec
and docker exec
?
docker exec
is a command for the core Docker CLI, used to execute commands in a single container.docker-compose exec service_name command
is a command for the Docker Compose CLI, used to execute commands in a container managed by Docker Compose (specifically, one of the containers for the specified service).
What is the purpose of the restart_policy
in a Docker Compose file?
restart_policy
in a service definition specifies how the service's containers should be restarted if they exit (e.g.,no
,on-failure
,always
,unless-stopped
). Similar to the--restart
option fordocker run
.
What is the purpose of the depends_on
key in a Docker Compose file?
depends_on
specifies that a service has a dependency on another service. Compose ensures that the dependency is running before starting the dependent service. Note that this only waits for the container to start, not necessarily for the application *inside* the container to be ready.
How can you ensure one service is ready before another starts in Docker Compose?
depends_on
is a start-order guarantee, not a health check. For true readiness, you typically need application-level health checks, waiting loops, or tools likewait-for-it.sh
or Docker's built-independs_on
withcondition: service_healthy
(Compose v2.2+).
What is the purpose of the networks
key in a Docker Compose file?
networks
allows you to define and connect services to user-defined networks, enabling communication between services by their service names.
What is the purpose of the volumes
key in a Docker Compose file?
volumes
allows you to define and use named volumes or bind mounts for persisting data used by your services.
What is the purpose of the build
key in a Docker Compose service?
build: .
(orbuild: /path/to/context
) specifies that Docker Compose should build the image for this service from a Dockerfile located in the specified path (the build context). You can also specify thedockerfile
andargs
within the build section.
What is the purpose of the image
key in a Docker Compose service?
image: image_name[:tag]
specifies that Docker Compose should use a pre-built image from a registry for this service.
What is the difference between build
and image
in a Compose service?
build
: Instructs Compose to build the image from a Dockerfile.image
: Instructs Compose to use an existing image (either local or from a registry). You typically use one or the other for a given service.
What is the purpose of the deploy
key in a Docker Compose file (v3+)?
- The
deploy
key specifies configuration related to deploying the service in a Swarm or Kubernetes environment, including replicas, update policies, resource limits, restart policies, etc.
What is the purpose of the docker stack ls
command?
docker stack ls
lists all running stacks in a Docker Swarm.
What is the purpose of the docker service ls
command?
docker service ls
lists all running services in a Docker Swarm.
What is the purpose of the docker service ps service_name
command?
docker service ps service_name
lists the tasks (containers) associated with a specific service in a Docker Swarm, showing their status and where they are running.
What is the purpose of the docker node ls
command?
docker node ls
lists all nodes in the Docker Swarm and their status (manager, worker, ready, down).
What is the purpose of the docker swarm join-token worker
command?
- This command (run on a manager node) generates the command needed for a new worker node to join the Swarm.
What is the purpose of the docker swarm join-token manager
command?
- This command (run on a manager node) generates the command needed for a new node to join the Swarm as a manager.
What is the difference between a manager node and a worker node in Docker Swarm?
- Manager Node: Manages the Swarm, handles orchestration tasks (scheduling services, maintaining desired state), and stores the Swarm state.
- Worker Node: Executes tasks assigned by the manager nodes.
What is the purpose of the docker service update
command?
docker service update
allows you to update the configuration of a running service in a Docker Swarm, such as scaling the number of replicas, changing the image, or updating resource limits.
What is a rolling update in Docker Swarm?
- A rolling update is a deployment strategy where new versions of service tasks are deployed gradually, replacing old tasks one by one or in batches. This allows for zero-downtime deployments and easy rollback if issues occur.
How does Docker handle secrets?
- Docker has a built-in secrets management system (available in Swarm mode). Secrets are encrypted at rest and in transit, and are only mounted into the container's in-memory filesystem (
/run/secrets/
) when needed by the service.
How does Docker handle configuration?
- Docker has a built-in configs management system (available in Swarm mode). Configs are similar to secrets but are intended for non-sensitive configuration data. They are also mounted into the container's filesystem (
/path/in/container/
).
What is the purpose of the docker login
command?
docker login
authenticates the Docker client with a Docker registry (like Docker Hub or a private registry) so you can pull and push private images.
How do you remove dangling volumes?
docker volume prune
.
How do you remove dangling networks?
docker network prune
.
What is the purpose of the --squash
option during image build?
- The
--squash
option (experimental) allows you to squash all the layers created during the build process into a single new layer after the base image layer. This can result in smaller images but loses the history of the build steps.
What is the purpose of the docker history
command?
docker history image_name_or_id
shows the history of a Docker image, listing the instructions from the Dockerfile that created each layer.
What are the different states of a Docker container?
- Created, Running, Paused, Stopped, Exited, Dead.
How do you pause and unpause a running container?
- Pause:
docker pause container_id_or_name
. - Unpause:
docker unpause container_id_or_name
.
What is the purpose of the docker system df
command?
docker system df
shows Docker disk usage information, including the total size of images, containers, local volumes, and build cache.
How do you specify a specific Dockerfile to use with docker build
?
- Using the
-f
option:docker build -f path/to/Dockerfile .
What is the purpose of the --tag
option in docker build
?
- The
--tag
or-t
option is used to name and optionally tag the image after a successful build (e.g.,docker build -t myimage:latest .
).
What is the default tag if you don't specify one when building or pulling an image?
latest
.
Is it a good practice to use the latest
tag in production? Why or why not?
- Generally no. The
latest
tag is mutable and can change over time, making your deployments unpredictable. It's better to use specific, immutable tags (like version numbers or commit hashes) for reproducibility.
What is the purpose of the --network bridge
option in docker run
? (Default)
- Connects the container to the default bridge network. Containers on this network can communicate with each other by IP address or, if linked (deprecated) or on a user-defined bridge network, by name.
What is the purpose of the --add-host
option in docker run
?
--add-host name:ip
adds an entry to the container's/etc/hosts
file, allowing the container to resolve a hostname to a specific IP address. Useful for connecting to services outside the standard DNS resolution.
What is the purpose of the --privileged
option in docker run
?
--privileged
gives the container elevated privileges, essentially giving it access to all devices on the host and bypassing kernel security features. This is generally not recommended for security reasons unless absolutely necessary.
What is the purpose of the --cap-add
and --cap-drop
options?
- These options allow you to add or drop specific Linux capabilities to a container, providing more fine-grained control over container privileges than the all-or-nothing
--privileged
option.
What is the purpose of the --read-only
option?
--read-only
mounts the container's root filesystem as read-only. This enhances security by preventing the container from writing to its own filesystem, forcing it to use volumes for any persistent data.
What are Docker entrypoint scripts?
- A script specified as the
ENTRYPOINT
in a Dockerfile. This script often performs setup tasks (like waiting for a database) before executing the main application command, which is typically provided byCMD
.
How can you reduce the size of Docker images?
- Use smaller base images (e.g., Alpine).
- Use multi-stage builds.
- Combine
RUN
instructions to reduce layers. - Clean up package manager caches and temporary files after installing packages.
- Use
.dockerignore
. - Avoid installing unnecessary dependencies.
What is the purpose of the docker attach
vs docker exec -it
?
docker attach
: Attaches to the container's standard input, output, and error streams. Exiting can sometimes stop the container.docker exec -it
: Runs a new command inside a running container and connects your terminal to its standard input, output, and error. Exiting this command does not stop the original container.docker exec
is generally safer for interactive debugging.