Docker Interview Questions for Beginners to Advanced ✌️
Why do we need Docker if we already have Virtual Machines?
We use Docker because containers are much lighter and faster than virtual machines. They let us package applications with all dependencies, so they run consistently anywhere without the overhead of a full operating system
What problem does Docker solve in real-world development?
Docker solves the real-world problem of inconsistent environments. It lets developers package applications with all dependencies so they run the same everywhere, while being faster, lighter, and easier to scale than virtual machines.
What are the main advantages of Docker?
Docker is lightweight, fast, consistent, portable, and makes scaling (horizantal scalling , no auto scalling )
Why do companies prefer Docker for microservices architecture?
Companies prefer Docker for microservices because it gives isolation, consistency, portability, and fast horizontal scaling.
If we already have Kubernetes, why do we still need Docker?
We still need Docker because Kubernetes doesn’t build or run containers by itself, it orchestrates them. Docker provides the container runtime, Kubernetes manages them at scale.
Why do Docker containers start faster than virtual machines?
VMs boot an OS, containers just start the app — that’s why Docker is faster.
What are the limitations of Docker?
Managing many containers is complex, so companies use Kubernetes. Docker runs the containers, and Kubernetes organizes, scales, and monitors them.
How does Docker help standardize environments across development, testing, and production?
Docker ensures consistency by running the same container image everywhere.
What is monolithic architecture? What is microservices architecture? What are the disadvantages of monolithic architecture? What are the advantages of microservices architecture?
Monolithic architecture: The whole application is built as one large unit where all components are tightly coupled.
Microservices architecture: The application is split into small, independent services that communicate with each other.
Disadvantages of monolithic: Hard to scale, difficult to maintain, one small change can affect the whole system, and deployments are slow.
Advantages of microservices: Easier to scale horizontally, faster deployments, independent development of services, and better fault isolation.
Why is Docker well suited for microservices architecture? Can monolithic applications also run inside Docker containers?
Docker runs both monolithic and microservices apps, but it shines with microservices by giving isolation, portability, and easy scaling
What challenges occur when migrating from monolithic architecture to microservices?
Migrating from monolithic to microservices is challenging because it requires breaking down services, managing distributed data, handling communication overhead, and adopting new tools and team practices.
If a monolithic application becomes difficult to scale, how would you redesign it using microservices and Docker?
You redesign a monolith by splitting it into independent microservices, containerizing them with Docker, and orchestrating them with Kubernetes for scalability and flexibility.
If one microservice crashes, how does containerization help isolate the failure?
If one microservice crashes, containerization helps isolate the failure because each service runs in its own container with its own resources. The crash affects only that container, not the others. Other microservices continue running normally, and orchestration tools like Kubernetes can automatically restart the failed container
Can you explain Docker architecture? What are the main components of Docker architecture?
Docker architecture is client–server based: the client sends commands, the daemon executes them on the host, images come from registries, and containers plus objects form the runtime environment.
| Component | Role |
|---|---|
| Docker Client | User interface; sends commands to daemon |
| **Docker Daemon (**dockerd) | Core engine; manages containers, images, volumes, networks |
| Docker Host | Machine running the daemon; executes containers |
| Docker Registry | Repository for images (Docker Hub or private registry) |
| Docker Objects | Includes images, containers, volumes, and networks |
What happens if the Docker daemon stops?
If the Docker daemon stops, you can’t manage containers, but running ones keep going until the daemon is restarted
How does Docker communicate with the host operating system?
Docker talks to the host OS through its daemon, which leverages kernel features like namespaces, cgroups, and networking to run containers in isolation.
Where are Docker images stored on a Linux system?
On Linux, Docker images are stored under /var/lib/docker/, usually in the overlay2 directory, where all image layers and metadata are managed by the storage driver
If Docker host CPU usage becomes very high, how would you identify which container is consuming the most resources?
You identify the container consuming the most CPU by using docker stats, cross‑checking with host process monitors, or using monitoring tools like cAdvisor or Prometheus.
Which protocol is used for communication between Docker client and daemon?
The Docker Client sends commands (like docker run) to the Docker Daemon using REST API calls. These calls travel over a socket (local UNIX socket by default)
If the Docker client cannot communicate with the Docker daemon, how would you troubleshoot the issue?
If the Docker client can’t talk to the daemon, check if the daemon is running, verify the socket or TCP connection, review permissions, and inspect logs to find the root cause
What is a Docker image?What is the difference between a Docker image and a container?What are Docker image layers?
A Docker image is a blueprint, a container is its running instance, and images are built in layers that make them efficient, reusable, and lightweight.
Why are Docker images considered lightweight?
Docker images are lightweight because they use layered storage, share common layers, and add only a small writable layer at runtime.
How does Docker manage CPU and memory resources for containers?
Docker uses Linux cgroups to control CPU and memory, letting you set limits, quotas, and shares so containers don’t overwhelm the host.
Can two containers run on the same port on the same host?
Two containers cannot bind to the same host port directly, but you can run them on different host ports, different interfaces, or behind a reverse proxy to share traffic.
How do you check resource usage of running containers?
Use
docker stats→ shows live CPU, memory, network, and I/O usage per container.Use
docker system df→ shows disk space usage by images, containers, and volumes.For deeper analysis, tools like cAdvisor, Prometheus + Grafana, or
htopon the host can be used.
Can two containers run on the same port on the same host?
Directly, no. Two containers cannot bind to the same host port (e.g., both mapping
-p 80:80).Workarounds:
Map them to different host ports (
-p 8080:80,-p 9090:80).Use a reverse proxy/load balancer (like Nginx, HAProxy, Traefik) to expose one host port and route traffic internally to multiple containers.
Bind to different host IPs if available.
If a container is deleted, does the Docker image also get deleted?
No. Deleting a container removes only that container instance.
The image it was created from remains on the host until you explicitly remove it with
docker rmi.
What happens to container data if the container is deleted?
Data stored in the container’s writable layer is lost when the container is deleted.
Data stored in volumes or bind mounts persists, because volumes are managed separately from the container lifecycle.
Can containers communicate with each other, and how?
Yes, containers can communicate if they are on the same Docker network.
By default, Docker creates a
bridgenetwork where containers can reach each other by IP.In user‑defined networks, containers can resolve each other by name (DNS).
For cross‑host communication, you’d use overlay networks (Swarm/Kubernetes).
Why are containers considered lightweight compared to virtual machines?
No separate OS per container: Containers share the host’s kernel, unlike VMs which each run a full guest OS.
Fast startup: Containers launch in seconds, VMs take minutes.
Lower resource usage: Containers only need the app + dependencies, not an entire OS.
Layered storage: Images reuse layers, saving disk space.
Higher density: You can run many more containers on the same hardware compared to VMs.
Why docker images are immutable?
Docker images are immutable because they’re built in read‑only layers, ensuring consistency, reproducibility, and security. Any change creates a new layer or a new image, never altering the original.
What is a Union File System, and how does Docker use it? Explain how Docker images are built using layers.
Docker uses a Union File System (like OverlayFS) to merge multiple read‑only image layers into a single unified view, with a writable layer on top for container changes
PORT numbers to remember
HTTP: 80 | HTTPS: 443 | SSH: 22 | MySQL: 3306 | MongoDB: 27017 | Redis: 6379 |
Jenkins: 8080
Some Basic Commands TO remember
yum install docker -y #To install docker on ec2
systemctl start docker #To start the docker
systemctl status docker #To get status of docker
docker images #To get list of images
docker pull <ImageName> #To pull a image
docker rmi nginx #To delete a single image
docker rmi $(docker images) #To delete all images
docker image prune #To remove dangling images
docker image prune -a #To rmve all images which r nt usd
docker build -t myimage:v1 . #To Build a image
docker ps #To get running containers
docker ps -a #To get all containers
docker start <containerName> #To start a container
docker stop <containerName> #To stop one container
docker stop <container1> <container2> #To mutiple all containers
docker stop $(docker ps) #To stop all running containers
docker rm $(docker ps -a) #To remove all stopped containers
docker rm <containerName> #To remove a single container
docker inspect <containerName> #To inspect a contianer
docker exec -it <containerName> bash #To excute a container
docker logs <containerName> #To get the logs of container
docker run -itd --name cont1 -p 4399:80 nginx #To create a container
docker run -d --name cont1 -p 4300:80 nginx #To create a container
docker stats #To get my usage of cont
What is a Dockerfile and why is it used?
A Dockerfile is a text-based script that contains a set of instructions to build a Docker image. It acts like a blueprint for creating containers by defining the base image, dependencies, configurations, and the commands needed to run an application.
What are the main components of a Dockerfile?
A Dockerfile is made up of a series of instructions that define how to build a Docker image. The main components include:
FROM – Specifies the base image from which the build starts.
WORKDIR – Sets the working directory inside the container.
COPY / ADD – Copies files from the host system into the image.
RUN – Executes commands during the build process, often used to install dependencies.
ENV – Defines environment variables.
EXPOSE – Declares the ports the container will listen on.
CMD – Provides the default command to run when the container starts.
ENTRYPOINT – Defines the main executable for the container, often used to make the container behave like a single command.
Why are Dockerfile instructions written in uppercase?
Dockerfile instructions are written in uppercase primarily for readability and convention. It helps distinguish the Dockerfile keywords — like FROM, RUN, COPY, and CMD — from the arguments or values that follow them.
What is the purpose of the FROM instruction? What is a base image in Docker?
The FROM instruction in a Dockerfile sets the base image for building. It's the first step because it establishes the starting point. By selecting a base image, you get its operating system, libraries, and settings, saving time and ensuring consistency. For example, FROM ubuntu:20.04 begins with Ubuntu, while FROM python:3.10 gives you a Python setup.
A base image is the foundational image upon which other images are built. It can be a minimal operating system image like Ubuntu or Alpine, or a language/runtime image like Node.js or Python.
Can a Dockerfile have multiple FROM Instructions?
Yes, a Dockerfile can have multiple FROM instructions. This is called a multi-stage build. Each FROM starts a new stage, and you can copy files or artifacts from one stage into another using COPY --from=<stage>.
It’s mainly used to:
Reduce image size → only the final stage becomes the actual image, so unnecessary build tools and files don’t get included.
Improve security → production images don’t contain compilers or extra dependencies.
Separate concerns → one stage for building, another for running.
What is the COPY instruction used for?What is the difference between COPY and ADD?When should you use ADD instead of COPY?
COPY is used in a Dockerfile to copy files or directories from your local machine (the build context) into the container’s filesystem.
COPY → Only copies files and directories from the local build context into the image.
ADD → Does everything COPY does, plus some extra features:
Can automatically extract compressed files (like
.tar) into the container.Can download files from a URL directly into the container.
ADD archive.tar.gz . # unzip and move files and folder to workdir
What does the --chown option do in the COPY instruction?
--chown is used with the COPY instruction to set the owner and group of the files being copied into the container. By default, files copied into the image are owned by root. With --chown, you can assign them to a specific user and group.
What is the purpose of the ARG instruction?When are ARG variables available?What is the difference between ARG and ENV?
ARG defines a variable that you can pass at build time using the --build-arg flag. It’s useful for parameterizing builds — for example, setting a version number or a proxy setting during the image build process."
Example:
dockerfile
ARG APP_VERSION=1.0
RUN echo "Building version $APP_VERSION"
You can override it when building:
bash
docker build --build-arg APP_VERSION=2.0 .
| Feature | ARG |
ENV |
|---|---|---|
| Scope | Build-time only | Runtime (available when container runs) |
| Default value | Can have defaults, overridden with --build-arg |
Can have defaults, overridden with -e at docker run |
| Persistence | Not saved in final image | Saved in final image |
| Use case | Customize build (e.g., version, proxy) | Configure runtime environment (e.g., DB host, API keys) |
Can ENV variables be overridden while running a container?
docker run -e APP_ENV=development myimage
What happens if the directory specified in WORKDIR does not exist?
If WORKDIR is not specified, Docker defaults to /. It’s best practice to always set WORKDIR so your files and commands are executed in a predictable, clean directory.
What is the purpose of the RUN instruction? When are RUN commands executed in the Docker lifecycle?
RUN is used in a Dockerfile to execute commands inside the image at build time. It’s typically used to install packages, set up dependencies, or perform configuration tasks.
Key Difference from RUN & CMD/ENTRYPOINT
RUN → executes at build time
CMD/ENTRYPOINT → executes at container runtime (when you start the container).
Can CMD be overridden while running the container?
Yes. The CMD instruction provides default arguments or commands for the container. But when you run the container, you can override it by specifying a command at the end of docker run.
docker run myimage node debug.js
What happens if multiple CMD instructions are used in a Dockerfile?
Only the last CMD instruction takes effect. Earlier ones are ignored.
What is the difference between CMD and ENTRYPOINT?
| Feature | CMD | ENTRYPOINT |
|---|---|---|
| Purpose | Provides defaults (command/args) | Defines the main command |
| Overridable | Fully overridden at runtime | Runtime args are appended to ENTRYPOINT |
| Best use | Default arguments | Fixed executable behavior |
Can ENTRYPOINT be overridden at runtime?
By default, no — the command defined in
ENTRYPOINTwill always run when the container starts.However, you can override it explicitly using the
--entrypointflag indocker run.
Why is the order of Dockerfile instructions important during build?
The order of Dockerfile instructions matters because Docker builds images in layers. Good ordering improves caching, reduces build time, ensures commands run in the right context, and keeps images small and clean
What are some best practices for writing an efficient Dockerfile?
Put rarely changing instructions first (like installing system packages).
Put frequently changing instructions later (like copying source code).
Use small base images (e.g.,
alpineinstead ofubuntuwhen possible).Clean up temporary files in the same
RUNinstruction:Separate build and runtime stages to avoid shipping compilers or build tools in production images.
Exclude unnecessary files (like
.git,node_modules, local configs).Add a non-root user and use
USERto improve security.
Docker File for NGINX
FROM nginx
RUN rm -rf /usr/share/nginx/html/*
COPY index.html /usr/share/nginx/html/
RUN echo "This is my nginx docker file"
Docker File for HTTPD
FROM HTTPD
RUN rm -rf /usr/local/apache2/htdocs/*
COPY index.html /usr/local/apache2/htdocs/
RUN echo "This is my HTTPD docker file"
Docker File for Python
FROM python
WORKDIR /app/mycode/
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY app.py .
ENTRYPOINT ["python"]
CMD ["app.py"]
Multi Stage Docker file for Python
# Build Stage
FROM python:3.11 AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
# Production Stage
FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /usr/local /usr/local
COPY app.py .
EXPOSE 5000
CMD ["python", "app.py"]
What does pip install --user do?
It installs Python packages in the current user's home directory (~/.local) instead of the system-wide Python directory.
Docker File for Java
FROM openjdk:17
WORKDIR /app
COPY target/app.jar /app/app.jar
EXPOSE 8000
CMD ["java","-jar","app.jar"]
Multi Stage Docker File for Java
# Build stage
FROM maven AS build
WORKDIR /app
COPY . .
RUN mvn package
# Production Stage
FROM openjdk
COPY --from=build /app/target/app.jar app.jar
CMD ["java","-jar","app.jar"]
Docker File for node.js
FROM node
WORKDIR /app
COPY . .
RUN npm install
EXPOSE 3000
CMD ["node","app.js"]
Multi Stage Docker File for Node.js
# Build stage
FROM node AS build
WORKDIR /app
COPY . .
RUN npm install
# Run stage
FROM node
WORKDIR /app
COPY --from=build /app .
EXPOSE 3000
CMD ["node","app.js"]
What is a Docker Volume? Why do we need Docker Volumes in containers? What happens to container data if the container is deleted?
A Docker Volume is a persistent storage mechanism provided by Docker that allows data to live outside the container’s writable layer, stored on the host machine and reusable across containers.
We need Docker Volumes to ensure data persistence, enable data sharing between containers, and keep application data separate from container images. They also improve performance compared to storing data inside the container itself.
If data is stored only inside the container’s writable layer, it is lost when the container is deleted. But if the data is stored in a Docker Volume, it remains intact and can be reused by new containers.
How do Docker volumes provide data persistence?
A Docker Volume stores data on the host machine outside of the container’s writable layer. This means the data is not tied to the container’s lifecycle so even if the container is stopped, restarted, or deleted, the data in the volume remains intact. Volumes can also be mounted into new containers, allowing data to be reused and shared across multiple containers.
What are the types of Docker Volumes?
Docker mainly supports two types: Named Volumes and Bind Mounts.
What is a Named Volume?
A Named Volume is managed entirely by Docker. It stores data in Docker’s designated location on the host and is referenced by a name.
What is a Bind Mount?
A Bind Mount directly maps a specific directory or file from the host machine into the container.
What is the difference between Named Volume and Bind Mount?
Named Volumes are Docker‑managed and portable, while Bind Mounts give direct control by linking to exact host paths. Named Volumes are better for portability and abstraction, whereas Bind Mounts are useful when you need tight integration with host files.
Where are Docker volumes stored in Linux?
/var/lib/docker/volumes/
Can multiple containers share the same volume?
Yes, multiple containers can share a single volume.
This is done by mounting the same volume into different containers.
Can you delete a volume attached to a running container?
No, you cannot delete a volume that is currently attached to a running container.
What are some real-world use cases of Docker volumes?
Running databases like MySQL, PostgreSQL, or MongoDB inside containers.Multiple containers (e.g., a web server and a logging service) need access to the same files.
Can we create a volume using Dockerfile?
Yes , but it always created anonymous volume
docker volume create <vlumName> #To create a new volume
docker volume ls #To get the list of volumes
docker run -itd --name cont1 --mount source=myvolume,destination=/rama/app nginx:latest #Attaching a volume to contianer while creating
docker inspect <volumName> #To inspect a volume
docker volume rm <volumName> #To remove a volume
docker volume prune #To delete unused volume
What is Docker Networking?
Docker Networking is the mechanism that allows containers to communicate with each other, with the host system, and with external networks. It provides isolation, flexibility, and scalability by creating virtual networks where containers can be attached. This ensures that microservices running in different containers can interact seamlessly while still maintaining security boundaries.
What are the different types of Docker networks?
Docker supports several types of networks, each serving a specific purpose:
Bridge Network – The default network for containers. It allows communication between containers on the same host but isolates them from external networks unless explicitly exposed.
Host Network – Removes network isolation between the container and the host. The container shares the host’s networking namespace, which improves performance but reduces isolation.
Overlay Network – Enables communication between containers across multiple Docker hosts. It’s commonly used in Docker Swarm or Kubernetes for distributed applications.
None Network – Disables networking entirely for a container. This is used when strict isolation is required.
What is Docker Networking?
Docker Networking is the mechanism that allows containers to communicate with each other, with the host system, and with external networks. It provides isolation, flexibility, and scalability by creating virtual networks where containers can be attached. This ensures that microservices running in different containers can interact seamlessly while still maintaining security boundaries.
What are the different types of Docker networks?
Docker supports several types of networks, each serving a specific purpose:
Bridge Network – The default network for containers. It allows communication between containers on the same host but isolates them from external networks unless explicitly exposed.
Host Network – Removes network isolation between the container and the host. The container shares the host’s networking namespace, which improves performance but reduces isolation.
Overlay Network – Enables communication between containers across multiple Docker hosts. It’s commonly used in Docker Swarm or Kubernetes for distributed applications.
Macvlan Network – Assigns a MAC address to each container, making it appear as a physical device on the network. This is useful when containers need to be directly accessible on the local LAN.
None Network – Disables networking entirely for a container. This is used when strict isolation is required.”
Difference between Default Bridge and User-Defined Bridge Networks
Default Bridge Network
By default, when you run a container without specifying a network, it gets attached to the default bridge.
In this network, containers can only communicate with each other using IP addresses.
There is no built-in DNS resolution, so you cannot simply use container names to connect.
User-Defined Bridge Network
When you create a custom bridge network, Docker automatically enables embedded DNS resolution.
This means containers can communicate using container names (hostnames) instead of just IP addresses.
It also provides better isolation and flexibility, since you can define multiple user-defined networks for different application stacks.
Create a user-defined bridge network
docker network create my_bridge_network
Run containers attached to this network
docker run -dit --name container1 --network my_bridge_network alpine
docker run -dit --name container2 --network my_bridge_network alpine
Test communication using container name
docker exec -it container1 ping container2
What is a Bridge network in Docker?
A bridge network is the default network driver in Docker. It creates an isolated virtual network on the host, allowing containers connected to it to communicate with each other using private IP addresses.
What is the difference between Bridge and Host network?
The key difference lies in isolation. In a bridge network, containers get their own private IP addresses and communicate through Docker’s virtual networking layer, requiring port mapping to expose services externally. In contrast, the host network removes this isolation — containers share the host’s network stack, using the host’s IP and ports directly
What is Host network mode?
Host network mode means the container runs in the same network namespace as the host. Instead of having its own IP, the container uses the host’s IP and ports directly
What is the None Network in Docker?
None network is a special network driver in Docker that completely disables networking for a container. When a container is attached to the None network, it has no external connectivity and cannot communicate with other containers or the host. This is useful when you want strict isolation or when networking is not required
When Would You Use the None Network?
I would use the None network in scenarios where a container should run in complete isolation. For example, if I’m running a batch job or a data-processing task that doesn’t need to communicate with other services, attaching it to the None network ensures maximum security by preventing any network access
What is an Overlay Network in Docker?
An overlay network is a Docker network driver that enables communication between containers across multiple Docker hosts. It uses a distributed key-value store to manage networking information and creates a virtual network that spans all participating hosts. Overlay networks are essential for orchestrators like Docker Swarm or Kubernetes, where containers need to communicate seamlessly across node
When Do We Use Overlay Networks in Real Projects?
In real-world projects, overlay networks are commonly used in distributed applications. For example, in a Docker Swarm cluster, microservices running on different nodes need to communicate with each other as if they were on the same local network. Overlay networks make this possible by providing secure, scalable, and host-independent connectivity. This is especially valuable in production environments where services are deployed across multiple servers.
What is --link in Docker and why is it deprecated?
--link was an older Docker feature used to connect containers together
Can a container be connected to multiple networks?
Yes, a container can be attached to multiple networks. This allows it to communicate with different sets of containers depending on the network. For example, a container could be part of a front-end network to talk to web services and also part of a back-end network to access databases. This provides flexibility and isolation in complex architectures.
How does Docker assign IP addresses to containers?
Docker uses its internal network drivers to assign IP addresses. For bridge networks, it creates a private subnet and assigns each container an IP from that range. For overlay networks, it uses a distributed key-value store to manage IPs across multiple hosts. The assignment is automatic, but you can also configure static IPs if needed
docker inspect container #To inspect a container to know n/w
docker network ls #To get list of networks
#To create a network with host type
docker run -itd --name mycontainer -p 80 --network=host newimage:v1
#To link containers manually
docker run -itd --name <container1Name> -p 1100:8080 --link <container2Name> <imageNameofContainer1Name>
docker network create <networkName> #To create a network
docker network prune #To dlt unused networks
docker network connect <n/wname> <conName> #To connect network to container
apt update
apt install iputils-ping -y
Docker Restart Policies ?
Default (
no) → Container won’t restart automatically.always → Restarts every time it stops, even after daemon restarts.
unless-stopped → Restarts automatically unless manually stopped.
on-failure[:max-retries] → Restarts only if container exits with a non-zero code, with optional retry limit
We can set this policy in compose.yaml
What is Docker Compose? Why do we use Docker Compose?
Docker Compose is a tool that allows you to define and manage multi-container Docker applications. Instead of running containers individually with long docker run commands, you use a YAML configuration file (docker-compose.yml) to specify services, networks, and volumes. With a single command (docker-compose up), you can start and orchestrate all the containers defined in that file, making it easier to manage complex applications.
We use Docker Compose to simplify the development and deployment of applications that require multiple services working together. For example, a web application might need a backend service, a frontend, and a database. Docker Compose lets us:
Define everything in one place using a YAML file.
Ensure consistency across environments (development, testing, production).
Easily scale services by adjusting configurations.
Automate orchestration so developers don’t have to manually start and link containers.
Improve productivity by reducing setup time and avoiding configuration errors.
What is the name of the Docker Compose configuration file?
File should be in format like docker-compose.yaml (or) compose.yaml
What are the main sections in a docker-compose.yml file?
version – Specifies the Compose file format version being used.
services – Defines the individual containers (like web, database, cache), their images, ports, environment variables, and dependencies.
networks – Configures how services communicate with each other, either through default or custom networks.
volumes – Declares persistent storage that can be shared across containers.
What is the difference between Docker and Docker Compose?
Docker is about running one container, Docker Compose is about running many containers together in a coordinated way
How do containers communicate in Docker Compose?
In Docker Compose, containers communicate with each other through networks that Compose automatically creates. By default, when you run docker-compose up, it sets up a dedicated network for your application, and all the services defined in the docker-compose.yml file are attached to that network.
Difference between docker-compose up and docker-compose up -d ?
docker-compose up: Starts all services defined in thedocker-compose.ymlfile in the foreground, showing logs directly in the terminal.docker-compose up -d: Starts the same services but in detached mode, meaning containers run in the background and you regain control of your terminal.
Can we scale containers using Docker Compose?
Yes. Docker Compose allows scaling of services using the command:
docker-compose up --scale <service>=<number>
How do you define environment variables in Docker Compose?
services:
web:
image: nginx
environment:
- APP_ENV=production
- DEBUG=false
Simple Docker Compose File
version: "3"
services:
web:
image: nginx
ports:
- "8080:80"
depends_on:
- db
networks:
- mynetwork
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: mypassword
volumes:
- dbdata:/var/lib/mysql
networks:
- mynetwork
volumes:
dbdata:
networks:
mynetwork:
docker-compose up -d #To execute docker-compose file
docker-compose ps #To get containers for compose
docker-compose down #To delete all containers created by compose
docker-compose build #To build images
docker-compose stop #To stop the containers
docker-compose logs #To get logs
docker-compose pause #To pause container (rqsts cant be accepted)
docker-compose config #To get config of compose file
docker-compose up --scale frontend=2 -d #To scale conatiners
If we scale frontend to 2 containers, how does traffic get distributed?
Docker Compose itself does not provide load balancing. Usually we place a reverse proxy like Nginx or HAProxy in front to distribute traffic.
How to Do reverse proxy in docker ?
nginx.config file
events {}
http {
upstream backend {
server site1:80;
server site2:80;
}
server {
listen 80;
location / {
proxy_pass http://backend;
}
}
}
docker-compose.yaml
version: "3"
services:
nginx:
image: nginx
ports:
- "8080:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
depends_on:
- site1
- site2
site1:
image: nginx
volumes:
- ./site1:/usr/share/nginx/html
site2:
image: nginx
volumes:
- ./site2:/usr/share/nginx/html
site1/index.html
<h1>Hello from Server 1</h1>
site2/index.html
<h1>Hello from Server 2</h1>
What is Docker Swarm?
Docker Swarm is a container orchestration tool built into Docker Engine that allows you to manage multiple Docker hosts as a cluster (called a swarm).
Why do we use Docker Swarm?
Scalability: Easily scale applications up or down by adjusting the number of replicas.
High Availability: If a node fails, tasks are automatically rescheduled on healthy nodes.
Load Balancing: Traffic is distributed across containers using Docker’s built-in load balancer.
Ease of Use: Integrated directly into Docker CLI, making it simpler than external tools like Kubernetes for smaller setups.
Rolling Updates: Allows updating services without downtime by gradually replacing old containers with new ones.
What is a Swarm cluster?
A Swarm cluster is a group of Docker nodes (machines running Docker) that are joined together and managed as a single system.
It consists of manager nodes and worker nodes, working collectively to run containerized applications with high availability and scalability.
What are the components of Docker Swarm?
Nodes
Manager nodes
Worker nodes
Services – Define the desired state of an application (e.g., number of replicas).
Tasks – Individual containers that are part of a service, scheduled on nodes.
Overlay Network – Enables communication between containers across different nodes.
Load Balancer – Distributes traffic among containers in a service.
What is a Manager node in Docker Swarm?
Role: Manager nodes handle the orchestration and management of the cluster.
Responsibilities:
Maintain the cluster state.
Schedule tasks across worker nodes.
Handle service definitions and scaling.
Perform leader election if multiple managers exist (to ensure high availability).
What is a Worker node in Docker Swarm?
Role: Worker nodes are responsible for executing tasks assigned by the manager.
Responsibilities:
Run containers (tasks) as instructed.
Report back status and health to the manager.
What is a Docker Service in Swarm?
A Docker service is the definition of how containers should run in a Swarm cluster.
It specifies the desired state: which image to use, how many replicas to run, what ports to expose, and how to distribute tasks across nodes.
Services are the unit of deployment in Swarm. Instead of managing individual containers, you manage services, and Swarm ensures the actual state matches the desired state.
Example: Running a web service with 5 replicas — Swarm will automatically distribute those 5 containers across available worker nodes.
What is task in swarm service?
A task is the smallest unit of scheduling in Docker Swarm.
It represents a single container instance that is part of a service.
What happens if a node fails in Docker Swarm?
Automatic rescheduling: If a worker node fails, the manager detects the failure and reschedules the tasks (containers) on healthy nodes.
High availability: This ensures that services remain available even if part of the cluster goes down.
Manager node failure: If a manager fails, Swarm uses Raft consensus to elect a new leader among the remaining managers.
What is Routing Mesh in Docker Swarm?
Routing mesh is a networking feature in Swarm that allows you to access a service on any node in the cluster, regardless of where the actual containers are running.
docker swarm init #To intialize swarm
docker swarm join --token <token> <manager-ip>:2377 #To join worker
docker node ls #To get list of nodes
docker service create --name rama --publish 4399:80 --replicas=1 nginx
docker service ls #To get list of services
docker service ps rama #To get contianers for rama service
docker service rm rama #To remove a service
docker swarm leave #To leave a swarm
What is Docker Stack?
Compose + Swarm = Stack
A Docker Stack is a way to deploy and manage a group of services in a Docker Swarm cluster using a single configuration file (usually a
docker-compose.yml).It allows you to define multiple services, networks, and volumes together as one application stack.
When you run
docker stack deploy, Swarm interprets the Compose file and creates the services across the cluster.
Why do we use Docker Stack?
Simplified deployment: Instead of deploying services one by one, you can deploy an entire application (with multiple services) in a single command.
Consistency: Uses the familiar Docker Compose format, making it easy to transition from local development to production in Swarm.
Scalability: Automatically distributes services across nodes in the cluster.
Maintainability: You manage the whole application as a single unit (stack), which is easier than handling individual services.
Version control: Since stacks are defined in YAML files, they can be stored in Git and versioned like code.
docker stack deplodocker run -d --memory=512m nginx
y -c docker-compose.yml mystack #To deploy a stack
docker stack ls #To Get all stacks
docker stack services mystack #To get list of services in a stack
docker stack ps mystack #To get containers in a stack
docker stack rm mystack #To remove a stack
How do you set resource limits for Docker containers?
docker run -d --memory=512m nginx
docker run -d --cpus="1.5" nginx
What is .dockerignore?
It prevents unnecessary files from being sent to the Docker build context (like .git, node_modules, logs), making builds faster and images smaller.
How do containers share OS resources?
Containers share OS resources by using the host’s kernel, with namespaces for isolation and cgroups for resource control
How does resource allocation work for containers?
Containers use cgroups to allocate CPU, memory, and I/O resources, ensuring fair usage and isolation while still sharing the host kernel.
What are namespaces in Docker?
In Docker, namespaces are a Linux kernel feature used to provide isolation between containers. They make each container feel like it has its own dedicated environment, even though multiple containers share the same host system.
PID namespace → Isolates process IDs so each container has its own process tree.
NET namespace → Provides each container with its own network stack (interfaces, routing tables, ports).
How do you troubleshoot container memory leaks?
Troubleshoot memory leaks by monitoring, profiling, and enforcing cgroup limits.
How does Jenkins integrate with Docker?
Jenkins integrates with Docker to run builds in containers and manage images in pipelines.
What is withDockerRegistry?
withDockerRegistry authenticates Jenkins pipelines with Docker registries for secure image operations.
Where are Docker logs stored in Linux?
/var/lib/docker/containers/<container_id>/<container_id>-json.log
