Docker
π³ What is Docker?
-
Docker is a platform to package applications into containers.
Docker is an open-source platform that enables developers to build, deploy, run, update, and manage applications using containers, which are ligh tweight, portable, and self-sufficient units that package an application and its dependencies together.
-
A container is a lightweight, portable, isolated environment that includes your app + dependencies + OS libraries.
-
Think of it as “ship your code with everything it needs” so it runs the same anywhere — your laptop, cloud, or production server.
Written in the Go programming language.
π Why Docker Containers Are Lightweight
✅ 1. They Don’t Need a Full Operating System-kernel
A virtual machine (VM) needs:
-
Its own full OS kernel
-
System libraries
-
Drivers
-
Boot process
A Docker container only needs:
-
Your application
-
Dependencies (libraries, Python packages, etc.)
-
A very small OS userland (Ubuntu-base, Alpine, etc.)
-
Uses host’s OS kernel instead of its own
So instead of 2–5 GB (VM), a container may be 10–100 MB.
✅ 2. Containers Share Kernel With the Host
No container contains a kernel.
-
Kernel is the heaviest part of an OS
-
All containers use the same Linux kernel
This reduces:
-
Memory usage
-
Startup time
-
CPU overhead
✅ 3. Copy-on-Write File System
Docker uses layered images and UnionFS.
π Meaning:
-
If 10 containers use the same base image (like Python 3.10), the base layer is stored once
-
Only the top writable layer is unique per container
So storage & memory are reused efficiently.
✅ 4. Low Overhead for Startup
VM: Boots a full OS → can take minutes
Docker: Just starts a process → starts in <1 second
Because:
-
No BIOS/bootloader
-
No OS boot
-
Only starts your application process
✅ 5. Namespaces & Cgroups
Linux gives Docker:
-
Isolation (namespaces)
-
Resource control (cgroups)
These are kernel features, not heavy virtualization technology.
No hypervisor → less overhead.
✅ 6. Smaller Images (Especially Alpine)
Example:
-
Ubuntu Base Image → 70–100 MB
-
Alpine Linux → 4–6 MB (!!)
So applications are small and fast to ship.
=============================================
π’ Docker Benefits (Simple Points)
1. Consistent environment everywhere
-
Same code runs the same way on any machine (dev, QA, prod).
2. Lightweight (compared to VMs)
-
Starts in seconds
-
Uses less CPU and RAM
3. Easy deployment
-
Build once → run anywhere
-
Faster releases
4. Isolation
-
Each container has its own dependencies
-
No version conflicts
5. Easy scaling
-
Run multiple containers from one image
-
Good for stream jobs, ETL parallelism
6. Multi-service setup using Compose
-
Run Airflow + Postgres + Kafka + Redis + Spark together
-
One command:
docker-compose up
7. Cleaner development
-
No need to install databases, Spark, Kafka manually
-
Everything runs inside containers
8. Better CI/CD
-
Code + dependencies packaged into one image
-
Consistent builds
9. Secure
-
Apps isolated from host system
10. Cloud-native
-
Works with Kubernetes, AWS ECS, EKS, GCP GKE, Azure AKS
-
Industry standard
-
================================================
π§± Components of Docker
Docker has 5 major components:
-
Docker Client
-
Docker Daemon (dockerd)
-
Docker Images
-
Docker Containers
-
Docker Registry
Below is a deep but simple breakdown π
1️⃣ Docker Client (CLI)
The client is what you interact with.
The Docker Client (docker CLI) communicates with the daemon using a REST API. It provides the execution environment where Docker Images are instantiated into live containers.
When you run:
You are using the Docker Client.
π It sends commands to the Docker Daemon.
The interface through which users interact with Docker. Users issue commands like docker run or docker build via the Docker CLI, which translates these into API calls to the Docker daemon.docker builddocker rundocker pull
2️⃣ Docker Daemon (dockerd)
Daemon = background service that does the heavy work.
A background service that runs on the host machine and manages Docker objects such as images, containers, networks, and volumes. It listens for API requests from the Docker client and executes container lifecycle operations like starting, stopping, and monitoring containers.
The Docker Engine Daemon (dockerd) runs in the background, listening to API requests and managing objects like images, containers, networks, and volumes.
It is responsible for:
-
Building images
-
Running containers
-
Managing images
-
Managing networks
-
Managing storage
The Docker Client talks to the Daemon using a REST API.
3️⃣ Docker Images
python:3.10-slim is an image.A docker image is a:
-
Blueprint
-
Read-only template
-
Layered package
It contains:
-
Application code
-
Dependencies
-
Runtime
-
OS libraries
-
Configurations
Images are created using docker build.
A Docker Image is a file made up of multiple layers that contains the instructions to build and run a Docker container. t acts as an executable package that includes everything needed to run an application — code, runtime, libraries, environment variables, and configurations.
How it Works:
- The image defines how a container should be created.
- Specifies which software components will run and how they are configured.
- Once an image is run, it becomes a Docker Container.
4️⃣ Docker Containers
A container is a running instance of an image.
Running instances of Docker images with a writable layer on top, enabling users to execute applications within isolated environments. Containers are lightweight and start quickly compared to traditional virtual machines.
When you run:docker run python:3.10-slim
Container =
-
Lightweight
-
Portable
-
Isolated process
Created using:
Multiple containers can run from the same image.
5️⃣ Docker Registry
A registry stores images.(Docker Hub / ECR / GCR)
Examples:
-
Docker Hub
-
AWS ECR
-
GitHub Container Registry
-
GCR
-
Azure ACR
Inside a registry we have repositories, and inside repositories we have tags.
π§© Additional Components (Advanced)
πΉ 6️⃣ Dockerfile
A file containing instructions to build an image.
The Dockerfile uses DSL (Domain Specific Language) and contains instructions for generating a Docker image. Dockerfile will define the processes to quickly produce an image. While creating your application, you should create a Dockerfile in order since the Docker daemon runs all of the instructions from top to bottom.
πΉ 7️⃣ Docker Engine
The Docker Engine is the core component that enables Docker to run containers on a system. It follows a client-server architecture and is responsible for building, running, and managing Docker containers.
Core part of Docker containing:
-
Client
-
REST API
-
Daemon
πΉ 8️⃣ Docker Compose
Tool to run multi-container apps.
Example:
-
app container
-
db container
-
redis container
All defined in docker-compose.yml.
πΉ 9️⃣ Docker Network
Provides:
-
Bridge network
-
Host network
-
Overlay network (for Swarm)
-
Container-to-container communication
πΉ π Docker Volumes
volumes:- dbdata:/var/lib/postgresql/dataUsed for persistent storage.
Examples:
-
Databases
-
Logs
-
App data
================================================
Containerization vs Virtual Machines
π₯️ 1. What is a VM (Virtual Machine)?
A Virtual Machine (VM) is a computer inside a computer.
It behaves like a real machine:
-
It has its own Operating System (Windows / Linux / macOS)
-
Its own virtual CPU, RAM, disk, network
Example:
You install Ubuntu Linux on your Windows laptop using VirtualBox.
That Ubuntu runs as a VM.
✔ How it works
A VM includes:
-
BIOS
-
Bootloader
-
Kernel
-
User space
-
Applications
So VMs are heavy and use more resources.
π 2. What is a Hypervisor?
A Hypervisor is the manager that creates and runs Virtual Machines.
It lies between:
-
Hardware (CPU, RAM)
-
VMs
It gives resources to each VM.
Two Types of Hypervisors
Type-1 (Bare Metal)
Runs directly on hardware → faster
Examples:
-
VMware ESXi
-
Microsoft Hyper-V
-
Xen
-
KVM
Type-2 (Hosted)
Runs on top of an operating system → slower
Examples:
-
VirtualBox
-
VMware Workstation
π§ 3. What is a Kernel?
The kernel is the core part of an operating system.
It controls:
-
CPU
-
RAM
-
Disk
-
Network
-
Processes
-
Services
Every OS has a kernel:
-
Linux kernel
-
Windows NT kernel
-
macOS XNU kernel
✔ What kernel does
Kernel manages:
| Kernel Function | Meaning |
|---|---|
| Process management | Runs programs |
| Memory management | Allocates RAM |
| Device drivers | Talks to hardware |
| Networking | Manages internet connections |
| File systems | Reads/writes files |
The kernel is what makes an operating system an operating system.
================================================
π’ What is a Docker Image?
-
A Docker Image is a read-only ,immutable file that contains everything your application needs to run:
-
Code (Python scripts, ETL jobs, DAGs)
-
Libraries / dependencies (pandas, PySpark, boto3, Airflow)
-
OS-level tools and environment variables
configuration files
-
It acts as a blueprint for creating Docker containers.
-
Think of it as a blueprint or snapshot of your environment.
πΉ Key Features of a Docker Image
-
Immutable: Once built, the image doesn’t change.
-
Versioned: Can tag different versions (
my-etl:1.0,my-etl:2.0). -
Portable: Can be run anywhere with Docker installed (local, cloud, CI/CD).
-
Layered: Each command in the Dockerfile creates a new layer, allowing caching and faster builds.
πΉ Analogy
-
Image = Cake Recipe → contains instructions and ingredients.
-
Container = Baked Cake → running instance you can interact with.
πΉ How to Create a Docker Image
Step 1: Create a Dockerfile
Step 2: Build the image: Building an image means generating a complete packaged environment for your application, based on the instructions in a Dockerfile.
-
-t my-etl-image:1.0→ gives a name and version tag to the image -
The image now contains Python + dependencies + your ETL code
Step 3: Verify the image
-
Lists all images on your machine
π₯ Simple Analogy
Dockerfile = Recipe
docker build = Cooking the dish
Docker image = Finished food
Container = Serving & eating the food
πΉ Practical Use Case for Data Engineers
-
ETL pipelines: Package Python / Spark scripts and dependencies → run anywhere
-
Airflow DAGs: Build an image containing DAGs + plugins → use DockerOperator to run tasks
-
Testing pipelines: Share image with team → exact same environment
================================================
π¦ Dockerfile (Simple Explanation)
A Dockerfile is a text file containing step-by-step instructions to build a Docker image.
You tell Docker how to create the image:
what OS to use, what packages to install, what code to copy, what command to run.
Think of it as a recipe for creating your application's environment. The Docker engine reads this file and executes the commands in order, layer by layer, to assemble a final, runnable image.
π© Most Important Instructions
| Instruction | Meaning |
|---|---|
| FROM | Base image |
| WORKDIR | Set working directory |
| COPY | Copy files into image |
| RUN | Execute commands during build |
| CMD | Default command when container runs |
| ENTRYPOINT | Fixed command; CMD becomes args |
| EXPOSE | Document port |
| ENV | Set environment variables |
| ARG | Build-time variable |
| VOLUME | Create mount point |
π¨ Basic Dockerfile Example
What it does:
-
Uses Python 3.10 base
-
Sets
/appas working folder -
Installs requirements
-
Copies your code
-
Runs main.py by default
π§ Build & Run Image
Build
Run
π️ 1. BUILD = Create the Image
Build means you are constructing the Docker image from a Dockerfile.
Command:
What happens during build:
-
Docker reads the Dockerfile
-
Downloads base image
-
Installs dependencies (RUN commands)
-
Copies your code (COPY)
-
Creates layers
-
Produces a final image
π Output of build = Docker Image (a blueprint)
π 2. RUN = Start a Container
Run means you are starting a container from that image.
Command:
What happens during run:
-
Docker takes the image
-
Creates a live running instance (container)
-
Executes the CMD/ENTRYPOINT
-
Runs your application
π Output of run = Container (a running process)
π₯ Simple Analogy
| Concept | Analogy |
|---|---|
| Dockerfile | Recipe |
| docker build | Cooking the dish using the recipe |
| Image | Finished, packed food |
| docker run | Serving/eating the food |
================================================
π’ What is a Docker Container?
-
A Docker Container is a running instance of a Docker Image.
-
It is isolated, lightweight, and contains everything defined in the image: your code, libraries, and environment.
-
Unlike an image, a container can run, execute, generate logs, and store temporary data.
Analogy:
Image = Recipe
Container = Cake baked from that recipe
πΉ Key Features of Containers
-
Ephemeral / Mutable
-
Containers can run, stop, restart, or be deleted.
-
Changes inside a container don’t affect the original image unless you commit it.
-
-
Isolated Environment
-
Each container has its own filesystem, processes, and network stack.
-
Prevents conflicts between different projects or dependencies.
-
-
Lightweight & Fast
-
Shares the host OS kernel → much faster than a VM.
-
Starts in seconds.
-
-
Multiple Instances
-
You can run multiple containers from the same image → efficient resource usage.
-
πΉ Practical Commands
-
Run a container
-
-it→ interactive terminal -
--name→ container name -
my-etl-image:1.0→ image to run
-
List running containers
-
Stop a container
-
Remove a container
-
Run in detached mode (background)
πΉ Containers in Data Engineering
-
ETL Jobs: Each pipeline can run in a separate container → isolation and reproducibility.
-
Airflow Tasks: DockerOperator spins up a container per task → consistent environment for Python/Spark jobs.
-
Local Testing: Run full pipeline with dependencies (Spark + Postgres + Minio) without affecting host system.
-
Scalable Pipelines: Multiple containers can run simultaneously, useful for batch jobs or streaming tasks.
Image
-
Read-only template
-
Created from Dockerfile
-
Example: Python + libs + your ETL script
Container
-
Running instance of an image
-
Can be started/stopped
-
Temporary, isolated environment
Dockerfile
-
Instructions to build an image
================================================
Docker Hub = Online platform where Docker images are stored, shared, and downloaded.
Docker Hub is the most popular public Docker registry, provided by Docker Inc.
A repository is a place where multiple versions (tags) of a Docker image are stored.
You use it to:
-
Pull images
-
Push images
-
Share images
-
Discover official images
-
Host private images
Website: hub.docker.com
(You don’t need to visit it—Docker CLI can interact directly.)
π§± What You Can Do with Docker Hub
✔ 1. Pull images
Download ready-made images:
✔ 2. Push your own images
Upload your images:
✔ 3. Use official, verified images
Examples:
-
library/nginx -
library/ubuntu -
library/mysql
These are secure, maintained by Docker or companies.
✔ 4. Create public or private repositories
-
Public repo → anyone can access
-
Private repo → only you/team can access
✔ 5. Automate builds (CI/CD integration)
π 1. Public Repository (Free-Docker Hub)
✔ Definition
A public repo can be viewed and pulled by anyone.
Anyone can run:
No login required.
✔ Use Cases
-
Open-source images
-
Sharing tools with the community
-
Demo applications
-
Training material
✔ Pros
-
Free
-
Easy to share
-
Good for open-source
✔ Cons
-
Code/image contents are visible to the world
-
Cannot store sensitive applications
π 2. Private Repository (Restricted)
✔ Definition
A private repo can be accessed only by you and people you give permission to.
A user must log in:
If they don't have access → they cannot pull.
✔ Use Cases
-
Internal enterprise apps
-
Proprietary code
-
Databases / internal pipelines
-
Anything sensitive or confidential
✔ Pros
-
Secure
-
Access-controlled
-
Good for companies
✔ Cons
-
Limited free private repos on free plan
-
Need Docker Hub account login
Docker commands to pull an image from a repository and run it.
π 1. Pull the image from a repo
Example (public repo):
Example (private repo):
π 2. Run the container
Example:
With port mapping:
π₯ Pull + Run in one command (No need to pull manually)
Docker will automatically pull the image if it doesn't exist locally.
π¦ Full Example: Private Repo
Step 1: Login
Step 2: Pull the image
Step 3: Run the container
π§© Optional: Run in background
Add -d:
================================================
A registry is a server where Docker images are stored, uploaded, downloaded, shared , it can be private or public.
Types:
-
Public Registry: Open to anyone (e.g., Docker Hub).
-
Private Registry: Restricted access, can be self-hosted or cloud-hosted (e.g., AWS ECR, Azure Container Registry, GitHub Container Registry).
-
-
Key Points:
-
You can host your own registry to control access to images.
-
Used in CI/CD pipelines to store images built from your projects.
-
Access can be controlled with authentication and authorization.
-
Examples:
-
Docker Hub (public)
-
Amazon ECR (private)
-
Google Container Registry (GCR)
-
Azure Container Registry (ACR)
-
GitHub Container Registry
-
Harbor (self-hosted)
-
Nexus (self-hosted)
- π₯ What You Can Do With a Registry
-
✔ Push images
Upload your built image to a registry:
✔ Pull images
Download an image from a registry:
A registry is the entire system/server that stores Docker images.
Examples of registries:
-
Docker Hub
-
Amazon ECR
-
GitHub Container Registry
-
Google Container Registry
-
Harbor
Think of registry = big storage platform.
A repository is a collection of related images (usually different versions of the same app).
Example repository inside Docker Hub:
This repository contains multiple versions (tags):
-
nginx:1.21
-
nginx:1.23
-
nginx:latest
-
nginx:stable
Think of repository = folder inside registry.
================================================
Docker Compose is a tool that lets you run multiple containers together using one YAML file.
Instead of running individual docker run commands, you define everything in:
Then start all services with one command: docker-compose up
π£ Why do we use Docker Compose? (Very Important)
Run multiple services together (e.g., Airflow + Postgres + Redis)
Handles networking automatically
Creates shared volumes
Starts containers in the right order
Perfect for data engineering pipelines
Docker Compose Architecture
A Compose file has 3 main parts:
Version → YAML schema version
Services → Containers to run
Volumes → Persistent storage
Networks → Optional custom networks
Example structure:
π’ Basic Example (docker-compose.yml)
Example for Python app + Postgres DB:
Highlights
Two services:
dbandappappwaits fordb(depends_on)Networking is automatic →
appconnects todbusing hostnamedb
π£ Most Important Docker Compose Commands
| Purpose | Command |
|---|---|
| Start all services | docker-compose up |
| Start in background | docker-compose up -d |
| Stop all services | docker-compose down |
| View running services | docker-compose ps |
| View service logs | docker-compose logs app |
| Rebuild + run | docker-compose up --build |
| Run a command inside container | docker-compose exec app bash |
π’ Networking in Compose
All services automatically join the same network
Containers talk using service names
Example:
No need for IP address.
π£ Volumes in Compose
Used for saving persistent data:
Example:
πΉ Why Data Engineers Use Docker Compose
-
Run Airflow scheduler + webserver + database locally.
-
Test ETL pipelines with Spark, Postgres, Kafka, or Minio (S3) together.
-
Manage dependencies, networking, and volumes easily.
-
Create reproducible environments for interviews and portfolio projects.
πΉ Basic Docker Compose Example (Airflow + Postgres)
Explanation:
-
Postgres → metadata database for Airflow
-
Airflow-webserver → runs DAGs, connected to Postgres
-
Volumes → persist database and logs
-
Ports → expose Airflow UI locally
πΉ Basic Docker Compose Commands
-
Build & start services
-
Run in detached mode (background)
-
Stop all containers
-
View logs
-
Rebuild after changes
πΉ Advanced Use Cases for Data Engineers
-
Local ETL testing
-
Spark + Minio (S3) + Kafka + Postgres → run all together.
-
-
Airflow development environment
-
Scheduler + Webserver + Worker + Postgres + Redis.
-
-
Team collaboration
-
Share
docker-compose.yml→ everyone runs the same environment.
MinIO is an open-source, high-performance object storage system that works just like Amazon S3.
π Simple Definition
MinIO = Your own S3 storage, but on your local machine or your company's servers.
You can store:
-
Files (images, videos, PDFs)
-
Backups
-
Logs
-
Data lake files (Parquet, CSV, JSON)
-
ML model files
It exposes an S3-compatible API, so tools that work with AWS S3 also work with MinIO.
MinIO is heavily used by:
-
Data engineers
-
Big data pipelines
-
Machine Learning teams
-
Kubernetes ecosystems
-
On-prem companies needing S3-like storage
Common use cases:
-
Storage for Airflow, Spark, Kafka, ML models
-
Data lake storage (like S3)
-
Backup system
-
File storage for microservices
πΉ Tips
-
Use
.envfile for sensitive credentials (AWS keys, DB passwords). -
Use depends_on for proper startup order.
-
Combine Dockerfile + Docker Compose to build custom images and run multi-service pipelines.
-
Use networks to let containers communicate (
service_name:port).
---------------------------------------------------------------------
In a Dockerfile, commands are executed in two different phases:
π 1. Build-time commands
Executed while building the image using:
These commands modify the image, install software, copy files, etc.
⭐ Build-time instructions:
| Instruction | Meaning |
|---|---|
| FROM | Base image |
| COPY | Copies files into image |
| ADD | Similar to COPY with extra features |
| RUN | Executes commands during image build |
| ENV | Sets environment variables for image |
| WORKDIR | Sets working directory |
| EXPOSE | Metadata only |
| USER | Sets default user |
| ENTRYPOINT | Sets startup program |
| CMD | Default arguments to ENTRYPOINT |
✔ Example Build-Time (RUN)
⏩ These run inside the image build, produce new layers.
π 2. Runtime commands
Executed when container starts, not during build.
This is when you run:
⭐ Runtime instructions:
| Instruction | Meaning |
|---|---|
| CMD | Runs when container starts |
| ENTRYPOINT | Main container command |
| ENV | Available at runtime |
| VOLUME | Declares storage |
| EXPOSE | Helps runtime port mapping |
✔ Example Runtime (CMD)
⏩ This runs when the container starts, not during build.
π₯ Major Difference (VERY IMPORTANT)
| Feature | Build Time | Runtime |
|---|---|---|
| Executed during | docker build | docker run |
| Command used | RUN | CMD, ENTRYPOINT |
| Creates layers? | Yes | No |
| Installs packages | ✔ Allowed | ❌ Not allowed |
| Runs application | ❌ No | ✔ Yes |
| Changes image? | ✔ Yes | ❌ No |
π§ Most Common Confusion
❗ Why not use RUN to start a server?
Example WRONG:
This will start app during build → build will hang forever.
You should use CMD or ENTRYPOINT:
π― Simple Example Dockerfile (Build-time vs Runtime)
================================================
Basic Commands
| Purpose | Command | Meaning |
|---|---|---|
| Check Docker version | docker --version |
Verify installation |
| List images | docker images |
Shows all images |
| List running containers | docker ps |
Only active containers |
| List all containers | docker ps -a |
Active + stopped containers |
| Build image | docker build -t <name> . |
Build image from Dockerfile |
| Run container | docker run <image> |
Start container |
| Run interactive shell | docker run -it <image> bash |
Enter container terminal |
| Run container in background | docker run -d <image> |
Detached mode |
| Assign name to container | docker run --name myapp <image> |
Run container with name |
| Stop container | docker stop <id> |
Gracefully stop |
| Force stop | docker kill <id> |
Hard stop |
| Remove container | docker rm <id> |
Delete container |
| Remove image | docker rmi <image> |
Delete image |
| View container logs | docker logs <id> |
Show logs |
| Execute command inside container | docker exec -it <id> bash |
Open shell inside running container |
| Copy file from container | docker cp <id>:/path/file . |
Copy from container to host |
| Show container stats | docker stats |
CPU/RAM usage |
| Pull image from Docker Hub | docker pull <image> |
Download image |
| Push image to registry | docker push <image> |
Upload image |
| Inspect container details | docker inspect <id> |
Low-level info |
| Show container logs | docker logs <id> |
View output |
---------------------------------------------------------------------
---------------------------------------------------------------------
docker exec is used to run a command inside a running container.
Think of it as opening a terminal inside a container.
✅ Syntax
π₯ Most Common Usage
⭐ 1️⃣ Open an interactive shell inside container
(Like SSH into the container)
or if bash is not available:
What this does:
-
-i→ interactive -
-t→ allocate a terminal (TTY) -
You get inside the container's environment
-
You can explore filesystem, logs, configs, etc.
⭐ 2️⃣ Run a single command inside container
Example: list files
Example: check Redis keys
⭐ 3️⃣ Check environment variables
⭐ 4️⃣ Verify process running inside container
⭐ 5️⃣ Run SQL client inside PostgreSQL container
π§ When to Use docker exec?
✔ To debug inside a container
✔ To explore container file system
✔ To check logs that applications write to files
✔ To run app-specific commands (redis-cli, psql, etc.)
✔ To verify configs
✔ To run admin commands
❗ Important Notes
πΈ The container must be running
If container is stopped:
will give error:
Use:
---------------------------------------------------------------------
π₯ Useful Flags
1️⃣ Follow logs (live streaming logs)
This is like tail -f, continuously showing new log lines.
2️⃣ Show last N lines
3️⃣ Include timestamps
4️⃣ Combine flags
Shows last 100 lines + timestamps + live updates.
---------------------------------------------------------------------
✅ 1. docker network ls
This command lists all Docker networks on your system.
You will see something like:
| NETWORK ID | NAME | DRIVER | SCOPE |
|---|---|---|---|
| 934d... | bridge | bridge | local |
| a23b... | host | host | local |
| 7dfe... | none | null | local |
✅ 2. Create a Docker network
To create your own custom network:
Why create a custom network?
Containers on the same network can communicate with each other by container name.
Example:
Mongo container can be accessed by name mongo inside Mongo Express.
✅ 3. Run MongoDB container on that network
What this does:
-
Starts MongoDB in background (
-d) -
Assigns container name
mongo -
Connects it to
mynetwork -
Sets username/password
✅ 4. Run Mongo Express (UI) on same network
Important points:
-
Connected to same network → can reach Mongo
-
Mongo server is given as:
Because Docker resolves container names automatically on a shared network.
-
Port mapping
-p 8081:8081
→ You can open Mongo Express in browser at:
---------------------------------------------------------------------
✅ 1. docker pull redis
This command downloads the Redis image from Docker Hub.
What happens:
-
Docker checks if
redis:latestexists locally -
If not, it downloads all required image layers
-
Stores it in your local image cache
✅ 2. docker images
Shows all images available locally.
You will see output like:
| REPOSITORY | TAG | IMAGE ID | CREATED | SIZE |
|---|---|---|---|---|
| redis | latest | abc123 | 2 days ago | 110MB |
✅ 3. docker run redis
Runs the Redis image in the foreground.
Result:
-
It starts Redis in your terminal
-
You can see logs continuously
-
Your terminal gets “attached” to the container
-
Press
CTRL + Cto stop
Not recommended for production.
✅ 4. docker ps
Shows running containers.
You will see columns:
| CONTAINER ID | IMAGE | STATUS | PORTS | NAMES |
✅ 5. docker run -d redis
Runs Redis in background (detached mode).
What happens:
-
Starts Redis container
-
Returns only the container ID
-
Your terminal is free to use
-
Container keeps running in the background
✅ 6. docker stop <container_id>
Stops the running Redis container.
What happens:
-
Sends graceful shutdown signal
-
Redis safely shuts down
-
Container becomes stopped, but not removed
✅ 7. docker start <container_id / name>
Starts a stopped container again.
or
Important:
It starts the same stopped container—not a new one.
✅ 8. docker ps -a
Shows all containers — running + stopped.
Useful to check old/stopped containers.
✅ 9. docker run redis:4.0
Runs a specific version of Redis.
What happens:
-
If version 4.0 image does NOT exist locally → Docker pulls it
-
A container is created using Redis v4.0
-
If you use
-d, it runs in background
================================================
π΅ What is Docker Caching?
Docker caching means Docker reuses previously built layers instead of rebuilding everything every time.
This makes builds:
-
Faster
-
Cheaper
-
More efficient
π΅ How Docker Caching Works
A Docker image is made of layers.
Each Dockerfile instruction creates one layer.
Example:
If nothing changes in a layer, Docker reuses it from cache.
π΅ Why Caching Matters (Interview Points)
-
Speeds up builds (5 minutes → 10 seconds)
-
Reduces duplicate work
-
Prevents reinstalling dependencies
-
Saves cloud build costs (GitHub Actions, AWS, GCP)
π΅ What Breaks the Cache?
A cache is invalidated (rebuild happens) if:
-
The instruction changes (example: change a RUN command)
-
Any file copied in that layer changes
-
Any previous layer changes
Example:
If requirements.txt changes, Docker will rebuild:
-
Layer for COPY requirements.txt
-
Layer for RUN pip install
-
All layers after them
But earlier layers (FROM, WORKDIR) are still cached.
π΅ Best Practice: ORDER YOUR DOCKERFILE
To get the maximum caching, put the steps that change least often first.
❌ Bad (slow builds every time):
✔ Good (better caching):
This way:
-
Pip install runs only if
requirements.txtchanges -
App code changes won’t break pip install cache
π΅ Cache Example in Real Life
First build:
Second build with no code change:
Because all layers are reused.
π΅ Skipping Cache (Forced Rebuild)
Sometimes you want a full rebuild:
π΅ Multi-Stage Build + Caching (Advanced)
Multi-stage builds let you cache dependency installation separately:
This dramatically speeds up builds.
π₯ Short Summary (One Line Answers)
-
Docker caching = reusing previous build layers
-
Each Dockerfile instruction = one layer
-
Layers only rebuild if something changes
-
Correct ordering = fast builds
-
--no-cachedisables caching
================================================
π¦ Variables in Docker
Docker supports two types of variables:
✅ 1. ENV (Environment Variables)
πΉ Available inside the running container
πΉ Used by applications at runtime
πΉ Can be set in Dockerfile, Compose, or at run time
Dockerfile
docker run
docker-compose.yml
π Use case:
Database URLs, passwords, app settings.
✅ 2. ARG (Build-time Variables)
πΉ Used only during image build
πΉ NOT available inside running container unless passed to ENV
πΉ Must be defined before use
Dockerfile
Build:
π Use case:
Build metadata, versioning, optional settings.
π¨ ENV vs ARG (Interview Question)
| Feature | ARG | ENV |
|---|---|---|
| Available at runtime? | ❌ No | ✔ Yes |
| Available during build? | ✔ Yes | ✔ Yes |
Passed using docker run? | ❌ No | ✔ Yes |
| Stored inside final image? | ❌ No | ✔ Yes |
π© 3. Variables in docker-compose with .env file
You can store environment variables in a file named .env.
.env:
docker-compose.yml:
π§ 4. Using variables inside Dockerfile
Example:
π₯ 5. Why variables are important in Docker?
-
Avoid hardcoding secrets
-
Make Dockerfiles reusable
-
Dynamic config (ports, environment, versions)
-
Different environments: dev, test, prod
π¦ Docker Registry — What It Is & Why It Matters
✅ What Is a Docker Registry?
A Docker Registry is a storage + distribution system for Docker images.
A Docker registry is a centralized storage and distribution system for Docker images. It acts as a repository where Docker images—packages containing everything needed to run an application—are stored, managed, versioned, and shared across different environments.
It is where Docker images are:
-
Stored
-
Versioned
-
Pulled from
-
Pushed to
Similar to GitHub, but for container images instead of code.
π§ Key Concepts
π 1. Registry
The whole server that stores repositories → e.g., Docker Hub, AWS ECR.
π 2. Repository
A collection of versions (tags) of an image.
Example:
π 3. Image Tag
Label used to version an image.
Example:
π© Public vs Private Registries
| Type | Examples | Features |
|---|---|---|
| Public | Docker Hub, GitHub Container Registry | Anyone can pull |
| Private | AWS ECR, Azure ACR, GCP GCR, Harbor | Secure, enterprise use |
π¦ Why Do We Need a Docker Registry?
Because:
-
You build an image locally
-
Push it to a registry
-
Your production server / CI/CD pulls the image and runs it
Without a registry → no easy way to share or deploy images.
π£ Common Docker Registry Commands
✅ Login
✅ Tag an Image
✅ Push to Registry
✅ Pull from Registry
π€ Examples of Docker Registries
π 1. Docker Hub (Most Common)
-
Free public repositories
-
Paid private repos
π 2. AWS ECR (Enterprise)
-
Most used in production
-
Private registry
-
Integrated with ECS, EKS, Lambda
π 3. GitHub Container Registry
-
Images stored inside GitHub
-
Good for CI/CD workflows
π 4. Google GCR / Artifact Registry
π 5. Self-hosted Registry
Example: Harbor, JFrog Artifactory
π₯ Advanced Concepts (Interview-Level)
πΉ Digest-based pulling
Instead of tag:
Guarantees exact version.
πΉ Immutable tags
Some registries enforce that v1 cannot be overwritten.
πΉ Retention Policies
Automatically delete old images in ECR/GCR.
πΉ Scan for vulnerabilities
Registries like:
-
AWS ECR
-
GHCR
-
Docker Hub (Pro)
can scan images for security issues.
================================================
Docker networking allows containers to communicate with:
each other
the host machine
external internet
Each container gets its own virtual network interface + IP address.
Docker networking allows containers to communicate with:
each other
the host machine
external internet
Each container gets its own virtual network interface + IP address.
πΆ Types of Docker Networks
Docker provides 5 main network types:
π¦ 1. Bridge Network (Default)
-
Most commonly used
-
Containers on the same bridge network can talk to each other using container name
Example:
Use Case:
Local development
Microservices communication
π© 2. Host Network
Container shares the same network as host.
❌ No isolation
⚡ Fastest network performance
π§ No port mapping needed
Run:
Use Case:
-
High-performance applications
-
Network-heavy workloads
π§ 3. None Network
Container has no network.
Use Case:
Security
Sandbox jobs
Batch processing
πͺ 4. Overlay Network (Swarm / Kubernetes)
Used in multi-node swarm clusters.
Allows containers on different machines to communicate.
Use Case:
Distributed apps
Microservices in Docker Swarm
π« 5. Macvlan Network
Gives container its own IP address in LAN like a real device.
Use Case:
Legacy systems
Need direct connection to network
Running containers like physical machines
π· Key Networking Commands
| Command | Description |
|---|---|
docker network ls | List networks |
docker network inspect <name> | Inspect network |
docker network create <name> | Create network |
docker network rm <name> | Remove network |
docker network connect <net> <container> | Add container to network |
docker network disconnect <net> <container> | Remove container |
π· How Containers Communicate
π¦ 1. Same Bridge Network
✔ Can ping each other by container name
✔ DNS built-in
Example:
π₯ 2. Different Networks
❌ Cannot communicate
➡ Must connect to the same network
π© 3. With Host Machine
Host can access container via:
Example:
Access: → http://localhost:8080
π§ 4. Container to Internet
Enabled by default via NAT.
πΆ Port Mapping
If container port = 80
Host port = 8080
π Host can access container
π “Port forwarding”
π¦ Docker DNS
On the same custom network:
-
Container names act like hostnames
-
Docker automatically manages DNS
================================================
Docker Volumes are the official way to store data outside a container.
Docker volumes are a dedicated, persistent storage mechanism managed by Docker for storing data generated and used by containers.
Unlike container writable layers, volumes exist independently of the container lifecycle, meaning data in volumes remains intact even if the container is stopped, removed, or recreated.
They reside outside the container filesystem on the host, typically under Docker's control directories, providing efficient I/O and storage management.
Because containers are ephemeral:
→ When container stops/deletes → data is lost
→ Volumes solve that.
πΆ Why Do We Need Docker Volumes?
✔ Containers are temporary
✔ Data must persist
✔ Multiple containers may need same data
✔ Upgrading/Deleting containers should NOT delete data
π¦ Types of Docker Storage
Docker offers 3 types:
1️⃣ Named Volume (Recommended)
Managed by Docker itself
Stored under:
Use Cases:
-
Databases (MySQL, PostgreSQL)
-
Persistent app data
Example:
2️⃣ Bind Mount
Maps specific host directory into container
Uses host machine's folder.
Use Cases:
-
Local development
-
When you want full control of host path
3️⃣ tmpfs (Linux Only)
Data stored in RAM only.
Use Cases:
-
Sensitive data
-
Ultra-fast temporary storage
π© Volume Commands (Most Important)
| Command | Description |
|---|---|
docker volume create myvol | Create volume |
docker volume ls | List volumes |
docker volume inspect myvol | Inspect volume |
docker volume rm myvol | Delete volume |
docker volume prune | Remove unused volumes |
π§ Using Volumes in Docker Run
Syntax:
Example:
π£ Using Bind Mounts
Example:
π΅ Volumes in Docker Compose
Very important for real projects.
docker-compose.yml
π₯ Example Use Case (DB Persistence)
If you run:
Delete container → data gone.
But with volume:
Stop container → data still exists (in volume).
π₯ Where Are Volumes Stored?
On Linux:
On Windows/Mac → managed internally through Docker Desktop.
-------------------------------------------------------------------------------------------------------------------
1️⃣ Why each DB has a different location
-
Each database engine stores data differently:
-
MySQL → /var/lib/mysql
-
PostgreSQL → /var/lib/postgresql/data
-
MongoDB → /data/db
-
Redis → /data (sometimes configurable)
-
This path inside the container is where the database stores its actual files (tables, indexes, logs, etc.).
-
If you stop or remove the container without a volume, all data is lost because containers are ephemeral.
Each database engine stores data differently:
-
MySQL →
/var/lib/mysql -
PostgreSQL →
/var/lib/postgresql/data -
MongoDB →
/data/db -
Redis →
/data(sometimes configurable)
This path inside the container is where the database stores its actual files (tables, indexes, logs, etc.).
If you stop or remove the container without a volume, all data is lost because containers are ephemeral.
2️⃣ Using Docker volumes for persistence
-
Volumes are Docker-managed storage that lives outside the container filesystem.
-
You can map container paths to host paths or let Docker manage them.
Syntax:
Examples:
MySQL:
Volumes are Docker-managed storage that lives outside the container filesystem.
You can map container paths to host paths or let Docker manage them.
3️⃣ Key points
-
Each DB container has its own default data directory — you must map that path for persistence.
-
You can use:
-
Host directory mapping (
/host/path:/container/path) → data visible on host. -
Named volumes (
-v myvolume:/container/path) → Docker manages storage.
-
-
Using different volumes/paths per DB avoids conflicts and keeps data safe.
-
This also allows backup, restore, and migration easily by copying the volume.
π¨ Interview Questions (Short Answers)
1️⃣ What is a Docker Volume?
A persistent storage mechanism managed by Docker.
2️⃣ Difference: Volume vs Bind Mount?
| Volume | Bind Mount |
|---|---|
| Managed by Docker | Controlled by host user |
| More secure | Direct host access |
| Best for production | Best for local development |
3️⃣ Does deleting container delete volume?
❌ No.
Volumes must be deleted manually.
4️⃣ What happens if volume doesn't exist?
Docker automatically creates it.
5️⃣ Can two containers share one volume?
✔ Yes → used in DB replicas, logs, shared storage.
================================================
ENTRYPOINT defines the main command that will always run when a container starts.
Think of it as the default executable of the container.
π¦ Why ENTRYPOINT is used?
✔ Makes the container behave like a single-purpose program
✔ Forces a command to always run
✔ Can't be easily overridden (compared to CMD)
✔ Best for production containers
πΆ ENTRYPOINT Syntax
Two forms exist:
1️⃣ Exec Form (Recommended)
✔ Doesn’t use shell
✔ More secure
✔ Handles signals properly
2️⃣ Shell Form
⚠ Runs inside /bin/sh -c
⚠ Harder to handle signals
π£ Example ENTRYPOINT Dockerfile
Dockerfile
Run:
This will always run:
π© ENTRYPOINT + CMD (Very Important)
ENTRYPOINT = fixed command
CMD = default arguments
Example:
Container will run:
You can override CMD:
But ENTRYPOINT cannot be replaced unless you use --entrypoint.
π₯ Override ENTRYPOINT (Rare)
π₯ ENTRYPOINT vs CMD (Very Important Table)
| Feature | ENTRYPOINT | CMD |
|---|---|---|
| Main purpose | Main command | Default args |
| Overrides allowed? | ❌ Hard | ✔ Easy |
| Best use | Permanent command | Arguments |
| Runs as | Program | Command/Args |
πΆ Common Interview Questions
1. Why use ENTRYPOINT instead of CMD?
To ensure the main command always runs and cannot be overridden.
2. What happens if both ENTRYPOINT and CMD exist?
CMD becomes arguments to ENTRYPOINT.
3. How do you override ENTRYPOINT?
Using --entrypoint.
================================================
π΅ Docker Daemon & Docker Client
Docker works using a client–server architecture.
π¦ 1. Docker Daemon (dockerd)
This is the brain of Docker.
✔ What it Does:
-
Runs in the background
-
Manages containers
-
Manages images
-
Manages networks
-
Manages volumes
-
Executes all Docker operations
✔ It Listens On:
-
Unix socket:
/var/run/docker.sock -
Sometimes TCP port (for remote Docker hosts)
✔ Daemon = Server Side
π© 2. Docker Client (docker)
This is the command-line tool you use.
When you type:
The client DOES NOT run containers.
Instead, it sends API requests to the Docker Daemon, which performs the real operations.
✔ Client = Frontend
✔ Daemon = Backend
π§ How They Work Together (Simple Flow)
You run:
Flow:
-
Client sends request → Daemon
-
Daemon pulls image
-
Daemon creates container
-
Daemon starts container
-
You see output on terminal
π΅ COPY vs ADD in Dockerfile
Both are used to copy files into the image, but COPY is preferred.
π¦ 1. COPY (Recommended)
✔ What it does:
Copies local files/folders into the container.
✔ Safe
✔ Predictable
✔ No extra features (simple only)
Example:
Use COPY when:
-
You want to copy source code
-
You want clean builds
-
You don’t need extraction or downloading
π§ 2. ADD (Avoid unless needed)
✔ What it does:
Does everything COPY does plus two extra features:
Extra Features:
1️⃣ Can download URLs
2️⃣ Automatically extracts tar files
⚠ Because of these extras → can create security issues
So Docker recommends: use COPY unless ADD is needed.
πͺ COPY vs ADD Table (Interview-Friendly)
| Feature | COPY | ADD |
|---|---|---|
| Copy local files | ✔ Yes | ✔ Yes |
| Copy remote URL | ❌ No | ✔ Yes |
Auto extract .tar.gz | ❌ No | ✔ Yes |
| Simpler | ✔ Yes | ❌ No |
| More secure | ✔ Yes | ❌ No |
| Recommended? | ✔ Yes | ❌ Use only when required |
π© When to Use ADD? (Rare)
Use ADD only for:
✔ Auto-unpacking tar files into image
✔ Downloading files from a URL
Otherwise → COPY is always better.
================================================
π΅ What are Multi-Stage Builds?
Multi-stage builds allow you to use multiple FROM statements in a single Dockerfile.
✔ Build in one stage
✔ Copy only the required output into the final stage
✔ Final image becomes much smaller
✔ No build dependencies inside final image
π¦ Why Multi-Stage Builds Are Needed?
Problem (without multi-stage):
-
Build tools (Maven, Go compiler, Node modules, pip, etc.) stay inside the final image
-
Makes image heavy
-
Security issues
-
Slow deployment
Multi-stage solution:
-
Build tools exist only in the build stage
-
Final stage contains just the application
-
Clean, lightweight image
π© Simple Example – Python / Node / Java / Go (All follow same logic)
Here is a general multi-stage pattern:
What happens?
-
Node image builds the app
-
Only the final compiled output is copied to nginx
-
Result = super small production image
πΆ Another Example – Python App
π· Another Example – Java (Very Popular)
✔ No Maven in final image
✔ Final image is tiny
π§ Key Features of Multi-Stage Builds
✔ Multiple FROM instructions
Each FROM = new stage
✔ You can name stages
✔ Copy artifacts from stage to stage
✔ Final image only contains last stage
All previous stages = removed
Image is clean + small
πͺ Benefits (Interview Ready)
| Benefit | Explanation |
|---|---|
| ✔ Smaller images | No build tools in final image |
| ✔ Faster builds | Layer caching for each stage |
| ✔ Better security | No compilers / secrets left behind |
| ✔ Cleaner Dockerfiles | Each stage has a clear job |
| ✔ Reproducible builds | Same environment every time |
================================================
π΅ What is .dockerignore?
.dockerignore is a file that tells Docker which files/folders to EXCLUDE when building an image.
It works similar to .gitignore.
π¦ Why do we use .dockerignore?
✔ Faster Docker builds
(Removes unnecessary files → smaller build context)
✔ Smaller images
(Don’t copy unwanted files)
✔ Better security
(Keep secrets, logs, configs out of image)
✔ Cleaner caching
(Prevents rebuilds when irrelevant files change)
π© Common Items in .dockerignore
π§ How it works?
When you run:
Docker first copies the “build context” → (current directory)
Without dockerignore, everything is copied.
.dockerignore tells Docker:
π« Don’t send these files to the build context.
πͺ Example
.dockerignore
Dockerfile
Only allowed files will be copied.
π₯ Performance Impact (Very Important)
Without .dockerignore:
-
Docker copies huge directories (node_modules, logs)
-
Slow build
-
Cache invalidates unnecessarily
With .dockerignore:
-
Build context is very small
-
Build is faster
-
Cache stays valid → faster incremental builds
π¨ Interview Questions (Short Answers)
1. What is the purpose of .dockerignore?
To exclude unnecessary files from the Docker build context.
2. What happens if .dockerignore is missing?
Docker sends all files to the build context → slow builds, large images.
3. Does .dockerignore reduce image size?
Yes, because it prevents unnecessary files from being copied.
4. Does .dockerignore improve caching?
Yes → fewer files → fewer cache invalidations.
5. Is .dockerignore mandatory?
No, but highly recommended.
================================================
π΅ Docker Container Lifecycle (Step-by-Step)
A Docker container goes through the following major stages:
π¦ 1. Created
The container is created from an image but not started yet.
Command:
π© 2. Running
Container is active and executing processes.
Command:
docker run= create + start
π§ 3. Paused
All processes inside the container are temporarily frozen.
Command:
πͺ 4. Unpaused
Resumes the paused container.
Command:
π₯ 5. Stopped / Exited
Container stops running its main process (app has exited or manually stopped).
Command:
π¨ 6. Restarted
Container is stopped and then started again.
Command:
π« 7. Removed (Deleted)
The container is permanently removed from Docker.
Command:
You cannot remove a running container—must stop it first.
π Lifecycle Diagram (Simple)
| Action | Command Example |
|---|---|
| Create | docker create nginx |
| Run (create+start) | docker run nginx |
| Start | docker start cont_id |
| Stop | docker stop cont_id |
| Pause | docker pause cont_id |
| Unpause | docker unpause cont_id |
| Restart | docker restart cont_id |
| Remove | docker rm cont_id |
| Remove all | docker rm $(docker ps -aq) |
================================================
π΅ What is a Docker HEALTHCHECK?
A HEALTHCHECK is a way to tell Docker how to test whether a container is healthy.
Docker runs this command periodically and updates the container's status:
-
healthy
-
unhealthy
-
starting
It helps in:
-
auto-restarts
-
load balancers
-
orchestrators (Kubernetes, ECS, Swarm)
π¦ Syntax (Dockerfile)
π© Options
| Option | Meaning |
|---|---|
--interval=30s | Check frequency |
--timeout=3s | How long to wait before failing |
--start-period=5s | Grace period before checks start |
--retries=3 | Fail after X failed attempts |
π§ Example 1: Simple HTTP Healthcheck
-
If
curl -fworks → healthy -
If fails → unhealthy
πͺ Example 2: Healthcheck Script
health.sh:
List containers with health status:
Detailed inspection:
You will see:
| Status | Meaning |
|---|---|
| starting | Startup period (start-period) |
| healthy | App is functioning |
| unhealthy | Check failed repeatedly |
If you use restart policies:
→ Docker auto-restarts an unhealthy container.
π Important Notes
-
HEALTHCHECK runs inside the container.
-
Should be lightweight (avoid heavy scripts).
-
Uses exit codes:
-
0 = success (healthy)
-
1 = unhealthy
-
2 = reserved
-
================================================
π΅ What is docker inspect?
docker inspect is used to view detailed information about Docker containers, images, networks, or volumes in JSON format.
It shows everything about a container:
-
Network info
-
Mounts / volumes
-
IP address
-
Ports
-
Environment variables
-
Health status
-
Entry point, CMD
-
Resource usage config
-
Labels
-
Container state (running, stopped, etc.)
This is the most powerful debugging command.
π¦ Basic Command
π© Example Output (Simplified)
You will see JSON fields like:
π§ Most Useful Inspect Filters (Important!)
π 1. Get container IP address
π 2. Get just the environment variables
π 3. Get container’s running status
π 4. Get container entrypoint
π 5. Get exposed ports
π§ Inspecting Images
Useful to see:
-
layers
-
build parameters
-
environment variables
-
entrypoint
πͺ Inspecting Networks
You can find:
-
connected containers
-
IP ranges (subnet)
-
gateway
-
driver type
π« Inspecting Volumes
Shows:
-
mount point
-
driver
-
usage
✨ Real Use Cases (Important for Interviews)
| Use Case | Command |
|---|---|
| Debug network issues | Get IP, ports |
| Debug ENV variables | extract .Config.Env |
| Verify mounted volumes | check .Mounts |
| Check health status | check .State.Health.Status |
| Know why a container exited | check .State.ExitCode |
π© Check Container Logs (Related Command)
================================================
π΅ What is Port Mapping in Docker?
Port mapping connects a container’s internal port to a port on your host machine so that applications inside the container can be accessed from outside.
Every container has own internal ports.
Multiple container run on same host but host has limited port.
If 2 container expose same internal port , u must map them to different host ports to avoid conflict.
Example:
A container running a web server on port 80 → accessible on host via port 8080
This is called port forwarding.
π¦ Syntax
Example:
Meaning:
-
Inside container, Nginx listens on 80
-
On your laptop/server, you hit http://localhost:8080
π© Types of Port Mapping
1. Host → Container (most common)
2. Bind to specific IP (e.g., localhost only)
Meaning:
Only local machine can access it.
3. Automatic host port assignment
Docker assigns random free ports.
π§ Check Mapped Ports
You will see:
πͺ Why Port Mapping Is Needed (Interview Points)
-
Containers run in isolated networks
-
Container ports aren’t accessible from host by default
-
Port mapping exposes them
-
Allows multiple instances to run on different host ports
-
Helps in local development and testing
π« Real Examples
1️⃣ Expose Postgres
2️⃣ Expose Airflow Webserver
3️⃣ Expose FastAPI on 8000
π₯ Port Mapping in Docker Compose
Same meaning: host 8080 → container 80
π₯ Docker Pull vs Docker Run — Simple Difference
Only downloads the image from Docker Hub into your system.
It does NOT create or start a container.
Example:
Result:
-
Redis image is downloaded
-
No container is created
-
No process runs
✅ docker run
Creates a container and runs it.
If the image does NOT exist locally, it will automatically pull it first.
Example:
Result:
-
Docker checks if image exists
-
If missing → pulls automatically
-
Creates a new container
-
Starts the container (runs Redis)
Comments
Post a Comment