नमस्ते दोस्तों!
स्वागत है The Easy Master पर!
आपने Docker container run karna seekh liya. Dockerfile bana li. Docker Compose se multiple containers chalana bhi aa gaya. Lekin ab ek important question – data kahan store hoga?
आपने अपना MongoDB container चलाया। Notes save kiye। फिर docker compose down चलाया – और सारा data delete! क्यों? क्योंकि container stop होते ही uski writable layer bhi delete ho जाती है।
Maine bhi yahi mistake ki thi. College project ke liye database container chalaya, 2 weeks की मेहनत, ek docker system prune और सब खत्म। Us din samajh aaya – data persistence kitna important hai!
Aur ek problem – containers ko aapas mein baat karna kaise hai? Node.js container ko DB container se connect karna hai – kaise?
Is Docker volumes networking Hindi article mein main aapko dono topics practical examples ke saath samjhaunga:
✅ Data Persistence – Docker volumes, bind mounts, tmpfs (kaise choose karein)
✅ Volume commands – create, inspect, backup, restore, prune
✅ Networking basics – Container Network Model (CNM)
✅ Network drivers – bridge (default aur user-defined), host, overlay, none, macvlan
✅ Network commands – create, inspect, connect, disconnect
✅ hands-on examples – MySQL data persist karo, custom network banake containers connect karo
✅ Docker Compose mein volumes aur networks ka use
✅ Best practices aur common mistakes
Chaliye, data persist karna aur containers ko connect karna seekhte hain! 🐳
Table of Contents
1. Container Data Problem – क्यों Data Delete हो जाता है?
Docker containers ephemeral (short-lived) nature ke liye design kiye gaye hain. Means by default, container ke andar jo bhi data store hota hai, wo sirf container ke life cycle tak rehta hai.
By default all files created inside a container are stored on a writable container layer. This means the data doesn’t persist when that container no longer exists.
Scenario samjho:
- आपने
docker run -d --name my-postgres postgresचलाया। - Database mein table banayi, data insert kiya।
docker stop my-postgresaurdocker rm my-postgresचलाया।- Dobara नया container run kiya – data गायब!
Docker provides three different ways to persist data beyond container lifecycle: Volumes, Bind Mounts, and tmpfs mounts.
Visual (words mein):
- Container writeable layer: Temporary, container delete हुआ तो data bhi delete।
- Volume: Docker-managed persistent storage, container delete होने पर भी data safe।
- Bind Mount: Host system की directory directly container mein map, data permanent।
- tmpfs: RAM में store, fast but temporary.
Data persistence aur networking dono Docker ecosystem ke most important pillars hain – inke bina production-ready application impossible hai.
2. Docker Volumes – Persistent Storage Ka Solution
2.1 Volume Kya Hai?
Volume ek storage mechanism hai jo container lifecycle se independent hota hai. Data volume mein store hota hai aur container delete/ recreate hone ke baad bhi safe rehta hai.
Volume vs Container Storage:
| Feature | Container Writable Layer | Docker Volume |
|---|---|---|
| Persistence | Container delete = data delete | Container delete = data safe |
| Location | Container filesystem ke andar | Host filesystem mein (Docker-managed) |
| Backup | Manual | Easy (docker run --rm -v volume:/data alpine tar czf ...) |
| Sharing | Multiple containers share nahi kar sakte | Multiple containers share kar sakte hain |
Volumes are stored in the host filesystem that is managed by Docker. Bind mounts are stored anywhere on the host system, and tmpfs mounts are stored in host memory only.
2.2 Types of Volumes
| Type | How it works | When to use |
|---|---|---|
| Named Volume | Docker-managed, specified by name (my-data-volume) | Production databases, application data |
| Anonymous Volume | Docker automatically generates random ID | Temporary data, testing |
| Bind Mount | Host path mapped directly (/home/user/data:/app/data) | Development hot reload, config files |
| tmpfs Mount | RAM में stored, non-persistent | Session data, cache, temporary files |
Recommendation: Production databases, persistent application data, and configuration that should survive container deletion all strongly favor named Docker volumes. For development hot reload or sharing large host files, bind mounts are convenient.
2.3 Named Volume vs Bind Mount – Detailed Comparison
| Aspect | Named Volume | Bind Mount |
|---|---|---|
| Management | Docker fully manages (location, permissions) | You manage path and permissions |
| Backup | Easier (use Docker commands) | Manual (tar, rsync) |
| Performance | Better for databases (native filesystem) | Same, but depends on host OS |
| Portability | High – works on any Docker host | Low – path-specific |
| Use case | Production databases, application data | Development code, config files |
Bind mounts can point to any location on the host, while volumes point to a specific area managed by Docker (where volumes are stored).
💡 Golden Rule: For databases and application data in production → use Named Volumes. For code and configuration during development → use Bind Mounts.
3. Bind Mounts – Host Directory Direct Map
Bind mount host system ki specific directory ko container ke andar mount karta hai. Bind mounts are stored anywhere on the host system (not limited to Docker’s storage area).
When to Use Bind Mounts
✅ Development hot reload – Code changes instantly reflect in container
✅ Configuration files – Nginx config, SSH keys
✅ Log files – Debugging ke liye
✅ Large files – Avoid copying into image
Syntax Difference: -v vs --mount
Docker has two flags for mounting: -v (or --volume) and --mount (more explicit, recommended for scripts).
Bind mount for development (recommended):
docker run -d \
-v "$(pwd)":/app \
--name dev-container \
node:20-alpine \
npm run dev$(pwd)– current directory (host) map kar raha hai to/app(container)- Changes in host instantly visible in container
Important note: On Windows, use absolute paths with drive letters: -v "C:\Users\me\data:/app/data"
Permission Considerations
Bind mount mein host directory ki permissions container ke user ke liye apply hoti hain. For example, if container runs as node user (UID 1000), ensure the host files are readable by UID 1000.
Use Case: Development with nodemon
docker run -d \
-v "$(pwd)":/app \
-v /app/node_modules \
-p 3000:3000 \
--name node-dev \
node:20-alpine \
npx nodemon server.jsSecond -v /app/node_modules prevents host’s node_modules from overriding container’s dependencies.
4. tmpfs Mounts – Ephemeral Storage (In-Memory)
tmpfs mounts store data directly in host system’s RAM (memory). Data is not written to disk and is deleted when container stops.
When to Use tmpfs Mounts
✅ Session data – User sessions (redis alternative for simple cases)
✅ Cache – Temporary cached data
✅ Secrets – Sensitive data that shouldn’t be written to disk
✅ Performance-critical temporary files
Syntax Example
docker run -d \
--tmpfs /tmp \
--name temp-container \
nginxOr using --mount syntax:
docker run -d \
--mount type=tmpfs,destination=/app/cache,tmpfs-size=100M \
my-appLimitations:
- Linux hosts only (not on Docker Desktop for Mac/Windows? Actually it works on Docker Desktop for Linux containers)
- Cannot be shared between containers
- Data lost on container stop
Choosing Between Volume, Bind Mount, tmpfs
| Need | Solution |
|---|---|
| Database data that must survive container deletion | Named Volume |
| Configuration files you want to edit on host | Bind Mount |
| Temporary session data that can be lost | tmpfs |
| Secrets that shouldn’t be written to disk | tmpfs |
| Code during development (hot reload) | Bind Mount |
| Production application logs | Named Volume or Bind Mount to central location |
| Cache that regenerates quickly | tmpfs |
5. Volume Management Commands – Cheat Sheet
| Task | Command |
|---|---|
| List all volumes | docker volume ls |
| Create a named volume | docker volume create mydata |
| Inspect volume details | docker volume inspect mydata |
| Remove a specific volume | docker volume rm mydata |
| Remove all unused volumes | docker volume prune |
| Force remove all unused volumes (no prompt) | docker volume prune -f |
| Use volume in container (named) | docker run -v mydata:/data alpine |
Use volume with --mount syntax | docker run --mount source=mydata,target=/data alpine |
| Backup a volume | docker run --rm -v mydata:/source -v $(pwd):/backup alpine tar czf /backup/backup.tar.gz -C /source . |
| Restore a volume | docker run --rm -v mydata:/target -v $(pwd):/backup alpine tar xzf /backup/backup.tar.gz -C /target |
Important Commands Explained
docker volume inspect: Display detailed information on one or more volumes – their mount point on host, driver options, labels, etc.
docker volume prune: Removes all volumes not used by at least one container, freeing up disk space. Docker will ask for confirmation before deleting.
Backup a volume using a temporary container:
# Backup
docker run --rm -v mydata:/source -v $(pwd):/backup alpine tar czf /backup/mydata-backup.tar.gz -C /source .
# Restore
docker run --rm -v mydata:/target -v $(pwd):/backup alpine tar xzf /backup/mydata-backup.tar.gz -C /target💡 Pro Tip: Never try to copy active database files directly from a running container’s host filesystem. This almost always leads to partial writes and corrupted restoration files. Always stop the container first or use database-specific backup tools (e.g.,
pg_dumpfor PostgreSQL).
6. Hands-On #1 – MySQL Container Mein Data Persist Karna (Volume)
Practical example: MySQL container mein volume attach karte hain taaki data persist rahe.
Step 1: Create a Named Volume
docker volume create mysql-dataVerify volume create hua:
docker volume lsStep 2: Run MySQL Container with Volume
docker run -d \
--name mysql-demo \
-e MYSQL_ROOT_PASSWORD=root123 \
-e MYSQL_DATABASE=testdb \
-v mysql-data:/var/lib/mysql \
mysql:8.0/var/lib/mysql is MySQL’s default data directory. By attaching the volume here, all database files are stored persistently.
Step 3: Connect to MySQL and Create Data
docker exec -it mysql-demo mysql -uroot -proot123 -e "CREATE TABLE testdb.users (id INT, name VARCHAR(50)); INSERT INTO testdb.users VALUES (1, 'Rahul'); SELECT * FROM testdb.users;"Step 4: Stop and Remove the Container
docker stop mysql-demo
docker rm mysql-demoContainer delete ho gaya.
Step 5: Create New Container with Same Volume
docker run -d \
--name mysql-demo-new \
-e MYSQL_ROOT_PASSWORD=root123 \
-v mysql-data:/var/lib/mysql \
mysql:8.0Step 6: Verify Data Still Exists
docker exec -it mysql-demo-new mysql -uroot -proot123 -e "SELECT * FROM testdb.users;"Output: 1 Rahul – data abhi bhi safe hai!
Step 7: Clean Up
docker stop mysql-demo-new
docker rm mysql-demo-new
docker volume rm mysql-data💡 Personal Experience: Maine college project mein yehi approach use ki thi. Database volume alag rakha, project ke multiple microservices alag containers mein chalaye. Jab koi service crash hoti thi, sirf us container ko restart karna padta tha – database data safe. Bahut time bacha.
7. Hands-On #2 – Website Files Ke Liye Bind Mount
Bind mount ka use development mein hot reload enable karne ke liye hota hai.
Step 1: Create a Simple HTML File
mkdir my-website
cd my-website
echo '<h1>Namaste Docker Bind Mount!</h1>' > index.htmlStep 2: Run Nginx with Bind Mount
docker run -d \
--name web-dev \
-p 8080:80 \
-v "$(pwd)":/usr/share/nginx/html \
nginxBrowser mein http://localhost:8080 खोलो – “Namaste Docker Bind Mount!” dikhna chahiye.
Step 3: Edit File and See Changes
echo '<h1>Updated! Bind mount is awesome</h1>' > index.htmlRefresh browser – changes automatically reflect. No container restart needed.
Step 4: Clean Up
docker stop web-dev
docker rm web-devBind mount data host par already hai, kuch delete nahi hoga।
💡 Pro Tip: For development, combine bind mounts with live reload tools like
nodemonin Node.js,--reloadin Flask, etc. Your entire development workflow becomes seamless.
8. Docker Networking – Containers Ke Beech Communication
Docker network subsystem is pluggable, using drivers. Network drivers provide core networking functionality.
8.1 Container Network Model (CNM) – Basic Concepts
CNM ke 3 main building blocks hain:
- Sandbox – Container ka isolated network stack (network interfaces, routing tables, DNS)
- Endpoint – Network interface jo container ko network se connect karta hai
- Network – Endpoints ka collection jo aapas mein communicate kar sakte hain
Docker networking ensures: Each container has a virtual network adapter that connects it to a private virtual network with a NAT firewall on the host. All containers on the same virtual network can talk to each other without port mapping.
8.2 How Containers Communicate Without Port Mapping
Default bridge network mein containers IP addresses use karte hain, jo dynamic hoti hain (container restart par change ho sakti hain). User-defined bridge network mein containers DNS resolution support karte hain – aap service name se container ko access kar sakte ho. The default bridge network lacks DNS resolution and permits unrestricted container-to-container communication, which is why custom user-defined networks are strongly preferred.
Example: Agar aap custom network mein do containers web aur db run karte ho, toh web container db hostname use karke db container tak pahunch sakta hai – IP address yaad rakhne ki zaroorat nahi।
9. Network Drivers – Bridge, Host, Overlay, None, Macvlan
Docker provides multiple network drivers. Default drivers exist and provide core networking functionality.
9.1 Default Network Drivers
| Driver | Description | Use Case |
|---|---|---|
| bridge | Default driver when no driver specified. Creates private internal network on host | Single-host container communication, default for most applications |
| host | Removes network isolation between container and Docker host; uses host’s network directly | Performance-critical services needing low latency; bypasses network translation |
| overlay | Connects multiple Docker daemons together (multi-host communication) | Docker Swarm, multi-node clusters |
| macvlan | Assigns a MAC address to container making it appear as physical device on network | Legacy applications expecting direct physical network access |
| none | Disables all networking for container | Highly isolated batch jobs, security sandboxes |
| ipvlan | Provides full control over IPv4 and IPv6 addressing | Advanced networking scenarios |
9.2 Detailed Comparison
Bridge Driver (Default and User-Defined):
- How it works: Creates a private internal network on the Docker host. Containers on the same bridge network can communicate with each other.
- Default bridge: Created automatically, limited features (no automatic DNS discovery)
- User-defined bridge: Recommended for production – provides automatic DNS resolution, better isolation, and can be connected/disconnected dynamically
Host Driver:
- How it works: Container uses host’s network stack directly (no network namespace isolation)
- Pros: Best performance, no port mapping needed
- Cons: Security risk (container can access all host network interfaces), no network isolation
- Uses: Low-latency services, network monitoring tools
Overlay Driver:
- How it works: Creates a distributed network across multiple Docker hosts using VXLAN encapsulation
- Best when: Containers running on different Docker hosts need to communicate, or multiple applications work together using Swarm services
- Uses: Docker Swarm, multi-node clusters
Macvlan Driver:
- How it works: Assigns a MAC address to a container, making it appear as a physical device on your network. The Docker daemon routes traffic to containers by their MAC addresses
- Best when: Handling legacy applications that want to connect directly to the physical network, rather than being routed through Docker host’s network stack
- Uses: Legacy applications, network monitoring, VoIP
None Driver:
- How it works: Disables all networking for the container (only loopback interface)
- Uses: Highly isolated batch jobs, security sandboxes, offline processing
9.3 Production Selection Recommendations
To help choose the right driver for each scenario:
- Use user-defined bridge networks for most microservices on a single host – provides automatic DNS resolution and isolation.
- Use host driver for performance-critical services that need low latency and can accept the security trade-off.
- Use overlay networks when scaling beyond a single host (Docker Swarm or Kubernetes).
- Use none driver for offline batch processing containers that don’t need network access.
💡 Production Recommendation: Replace the default bridge network with custom user-defined networks for better security and isolation. When not required, disable inter-container communication within the bridge network.
10. Network Management Commands – Cheat Sheet
| Task | Command |
|---|---|
| List all networks | docker network ls |
| Create a network | docker network create my-network |
| Create network with specific driver | docker network create --driver bridge my-network |
| Inspect network details | docker network inspect my-network |
| Connect running container to network | docker network connect my-network my-container |
| Disconnect container from network | docker network disconnect my-network my-container |
| Remove a network | docker network rm my-network |
| Remove all unused networks | docker network prune |
Important Commands Explained
docker network create: When you create a network specifying only the network name, it automatically creates a bridge network.
docker network connect: Connects an already running container to an existing network. Useful for dynamically adding services.
docker network inspect: Shows detailed information including connected containers, subnet and gateway settings.
Example:
# List networks
docker network ls
# Create custom network
docker network create --driver bridge my-app-network
# Inspect
docker network inspect my-app-network11. Hands-On #3 – Custom Bridge Network Banayein
Step 1: Create Custom Bridge Network
docker network create --driver bridge my-custom-netStep 2: Verify Network Created
docker network lsAapko my-custom-net dikhega with driver bridge।
Step 3: Run Two Containers on Same Network
Container 1:
docker run -d --name container1 --network my-custom-net alpine sleep 3600Container 2:
docker run -d --name container2 --network my-custom-net alpine sleep 3600Step 4: Test Communication Between Containers
Container 1 se container 2 ping karein using container name:
docker exec -it container1 ping container2Successful ping dikhna chahiye – because user-defined networks provide automatic DNS resolution! This demonstrates why custom networks are superior to the default bridge (which doesn’t have automatic DNS).
Step 5: Inspect Network Details
docker network inspect my-custom-netConnected containers ki list dikhegi.
Step 6: Clean Up
docker stop container1 container2
docker rm container1 container2
docker network rm my-custom-net12. Hands-On #4 – Custom Network Mein Containers Connect Karein (Node.js + MySQL)
Real scenario: Node.js backend aur MySQL database ko custom network mein connect karte hain.
Step 1: Create Custom Network
docker network create app-networkStep 2: Run MySQL Container on the Network
docker run -d \
--name mysql-db \
--network app-network \
-e MYSQL_ROOT_PASSWORD=root123 \
-e MYSQL_DATABASE=myapp \
-v mysql-data:/var/lib/mysql \
mysql:8.0Step 3: Create Simple Node.js App
Create app.js:
const mysql = require('mysql2');
const express = require('express');
const app = express();
const connection = mysql.createConnection({
host: 'mysql-db', // container name as hostname!
user: 'root',
password: 'root123',
database: 'myapp'
});
app.get('/', (req, res) => {
connection.query('SELECT "Hello from Docker Network!" AS message', (err, results) => {
if (err) res.status(500).send(err);
else res.json(results[0]);
});
});
app.listen(3000, () => console.log('App running on port 3000'));Step 4: Create Dockerfile for Node.js
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install mysql2 express
COPY . .
CMD ["node", "app.js"]Step 5: Build and Run Node.js Container on Same Network
docker build -t my-node-app .
docker run -d --name node-app --network app-network -p 3000:3000 my-node-appBrowser mein http://localhost:3000 – message dikhna chahiye.
Step 6: Verify Network
docker network inspect app-networkBoth mysql-db and node-app containers should appear in "Containers" section.
Step 7: Clean Up
docker stop node-app mysql-db
docker rm node-app mysql-db
docker network rm app-network
docker volume rm mysql-data💡 Key Learning: Using custom user-defined networks, containers can communicate using their container names as hostnames. This eliminates IP address management and makes your setup portable across different environments.
13. Docker Compose Mein Volumes aur Networks
Docker Compose automatically creates networks and simplifies volume management.
Sample compose.yaml for WordPress + MySQL
services:
wordpress:
image: wordpress:latest
ports:
- "8080:80"
environment:
WORDPRESS_DB_HOST: db
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: wordpress
WORDPRESS_DB_NAME: wordpress
volumes:
- wordpress_data:/var/www/html
networks:
- wordpress-network
depends_on:
- db
restart: unless-stopped
db:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: root123
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: wordpress
volumes:
- db_data:/var/lib/mysql
networks:
- wordpress-network
restart: unless-stopped
volumes:
wordpress_data:
db_data:
networks:
wordpress-network:
driver: bridgeWhat Compose does automatically:
- Creates
wordpress-networkbridge network - Adds both services to this network
- Services can reach each other using service names (
wordpresscan connect to hostnamedb) - Creates named volumes
wordpress_dataanddb_data
Run with:
docker compose up -dVolumes and networks are key building blocks for robust multi-container applications. They allow data persistence and service discovery without hardcoded IP addresses.
14. Real Project – Complete WordPress + MySQL Setup
Let’s build a complete persistent WordPress site using volumes and custom networks.
Project Structure
wordpress-project/
├── compose.yaml
└── .envcompose.yaml
services:
wordpress:
image: wordpress:6.7
ports:
- "8080:80"
environment:
WORDPRESS_DB_HOST: db
WORDPRESS_DB_USER: ${DB_USER}
WORDPRESS_DB_PASSWORD: ${DB_PASSWORD}
WORDPRESS_DB_NAME: ${DB_NAME}
volumes:
- wordpress_data:/var/www/html
networks:
- wordpress-net
depends_on:
db:
condition: service_healthy
restart: unless-stopped
db:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: ${ROOT_PASSWORD}
MYSQL_DATABASE: ${DB_NAME}
MYSQL_USER: ${DB_USER}
MYSQL_PASSWORD: ${DB_PASSWORD}
volumes:
- db_data:/var/lib/mysql
networks:
- wordpress-net
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 10s
timeout: 5s
retries: 5
restart: unless-stopped
volumes:
wordpress_data:
db_data:
networks:
wordpress-net:
driver: bridge.env file (DO NOT COMMIT TO GIT)
DB_USER=wpuser
DB_PASSWORD=secure_password_here
DB_NAME=wordpress_db
ROOT_PASSWORD=root_password_hereRun the Project
docker compose up -dWait for both containers to be healthy, then access http://localhost:8080 to complete WordPress installation.
Backup Volumes (Production Best Practice)
# Backup WordPress files
docker run --rm -v wordpress_project_wordpress_data:/source -v $(pwd):/backup alpine tar czf /backup/wordpress_files_backup.tar.gz -C /source .
# Backup Database
docker exec wordpress-project-db-1 mysqldump -u wpuser -psecure_password_here wordpress_db > db_backup.sqlRestore from Backup
# Restore WordPress files
docker run --rm -v wordpress_project_wordpress_data:/target -v $(pwd):/backup alpine tar xzf /backup/wordpress_files_backup.tar.gz -C /target
# Restore Database
cat db_backup.sql | docker exec -i wordpress-project-db-1 mysql -u wpuser -psecure_password_here wordpress_db15. Best Practices – Production-Level Tips
For Data Persistence:
✅ Use named volumes for production databases – Never rely on bind mounts for database persistence in production; bind mounts are designed for development flexibility.
✅ Implement regular volume backups – Use temporary containers to tar your volume data and push it off-site. Never copy active database files directly from a running container’s host filesystem.
✅ Use .dockerignore – Prevent unnecessary files from being copied into images.
✅ Set resource limits for volumes – Monitor disk usage and set limits where possible.
✅ Enforce strict volume naming conventions – Use consistent naming patterns (e.g., project_service_data).
✅ Run regular volume cleanups – Use docker volume prune periodically to remove orphaned volumes.
✅ Maintain strict file permission boundaries – Between host and container users (e.g., ensure container UID matches host UID for bind mounts).
For Networking:
✅ Always use user-defined bridge networks for production – Never use the default bridge network; user-defined networks provide automatic DNS resolution, better isolation, and can be connected/disconnected dynamically.
✅ Only expose required ports – Minimize attack surface by publishing only necessary ports. If not required, disable inter-container communication between containers within the bridge network.
✅ Isolate sensitive containers – For highly sensitive workloads, use an internal-only network that has no external connectivity, combined with strict egress filtering.
✅ Use network aliases for easy discovery – Assign multiple aliases to containers for flexible service discovery.
✅ Implement network-level security – Force network traffic to be encrypted using mTLS for inter-service communication in production.
✅ Monitor network performance – Use docker network inspect and monitoring tools to track network metrics.
General Best Practices:
✅ Always version control compose files – Include compose.yaml in your repository (but exclude .env files).
✅ Use healthchecks – Ensure services only start when dependencies are truly ready.
✅ Set restart policies – Use restart: unless-stopped for production services.
✅ Separate environments – Use different compose files or environment variables for dev, staging, and production.
16. Common Mistakes (aur Unka Solution!)
| Mistake | Kyun Galat Hai? | Solution |
|---|---|---|
| Bind mount for database in production | Performance issues, permission problems, no volume management features | Use named volumes for all production databases |
| Forgetting volume when container recreated | Data loss occurs every time container is recreated | Always define volumes in compose file |
| Using default bridge network | No DNS resolution, containers must use IP addresses, which change on restart | Create user-defined bridge networks for inter-container communication |
| Not using healthchecks with depends_on | Container starts before dependency is ready, causing errors | Add healthcheck to dependencies and use condition: service_healthy |
| Hardcoding secrets in compose file | Secrets exposed in version control | Use .env files and add to .gitignore |
| Not backing up volumes | Data loss if host fails or volume corrupts | Regular automated backups (scheduled with crond in a utility container) |
Using :latest tag for images | Unpredictable behavior across environments | Pin specific image versions (e.g., mysql:8.0.41 not mysql:latest) |
| Not setting restart policies | Container doesn’t auto-recover after crash or host reboot | Set restart: unless-stopped in compose services |
| Exposing all ports | Increased attack surface and potential conflicts | Only publish ports that need external access |
💡 Personal Mistake: I once stored my production database data using a bind mount on my local development path,
/home/user/mysql-data. When migrating to a new server, the path didn’t exist, and I lost the data directory. Now I always use named volumes for any stateful service and keep my volume backups automated.
17. Resources – Cheat Sheet & Practice Prompts
Volumes Cheat Sheet
| Task | Command |
|---|---|
| Create named volume | docker volume create my-data |
| Run container with volume | docker run -v my-data:/data alpine |
| List volumes | docker volume ls |
| Inspect volume | docker volume inspect my-data |
| Remove volume | docker volume rm my-data |
| Remove unused volumes | docker volume prune |
| Backup volume | docker run --rm -v my-data:/source -v $(pwd):/backup alpine tar czf /backup/backup.tar.gz -C /source . |
| Restore volume | docker run --rm -v my-data:/target -v $(pwd):/backup alpine tar xzf /backup/backup.tar.gz -C /target |
Networking Cheat Sheet
| Task | Command |
|---|---|
| List networks | docker network ls |
| Create bridge network | docker network create my-net |
| Run container on network | docker run --network my-net alpine |
| Connect container to network | docker network connect my-net my-container |
| Inspect network | docker network inspect my-net |
| Remove network | docker network rm my-net |
| Remove unused networks | docker network prune |
Docker Compose Cheat Sheet
services:
app:
build: .
volumes:
- app_data:/data # Named volume
- ./config:/app/config # Bind mount (development)
networks:
- app-network
depends_on:
db:
condition: service_healthy
db:
image: postgres:15
volumes:
- db_data:/var/lib/postgresql/data
networks:
- app-network
healthcheck:
test: ["CMD", "pg_isready", "-U", "postgres"]
interval: 10s
timeout: 5s
retries: 5
volumes:
app_data:
db_data:
networks:
app-network:
driver: bridgePractice Prompts
Beginner:
- PostgreSQL container run karo with named volume. Create a test database, insert some data. Stop, remove, and recreate the container with the same volume. Verify data exists.
- Custom bridge network create karo, two alpine containers run karo on that network, and ping each other by container name.
Intermediate:
- Node.js + MongoDB app lo (previous article example). Modify compose.yaml to use named volumes for MongoDB and a bind mount for Node.js code. Verify data persists after
docker compose down. - Create a backup script that archives your production volume daily using a temporary alpine container.
Advanced:
- Multi-network architecture implement karo: frontend containers on a public network (exposed to host), backend and database on an internal-only network with no external access (for enhanced security).
- Implement a complete CI/CD pipeline with GitHub Actions that automatically builds, tags, and pushes images, and also backs up volumes before deployment.
18. FAQ – 7 Most Asked Questions
Q1: Volume aur bind mount mein main difference kya hai?
Named volumes Docker-managed होते हैं (Docker store location automatically), jabki bind mounts host directory direct map करते हैं (you specify the exact path). For production databases, always prefer named volumes; bind mounts are better suited for development hot reload.
Q2: Docker Compose automatically volume aur network create karta hai?
Yes – Docker Compose automatically creates networks and volumes defined in compose file. For networks, it creates a default network and adds all services to it unless you specify otherwise.
Q3: Multiple containers ek hi volume share kar sakte hain?
Yes – multiple containers can share the same volume, but ensure your application supports concurrent writes. Use appropriate locking mechanisms if writing from multiple containers.
Q4: Custom bridge network default bridge se better kyun hai?
Custom bridge networks provide automatic DNS resolution (containers can reach each other by service/container name), better isolation, and can be connected/disconnected dynamically. The default bridge lacks these features.
Q5: Volume backup best practice kya hai?
Use a temporary alpine container that mounts the volume and compresses its contents, then push the archive to cloud storage (S3, etc.). Database-specific dumps (like pg_dump) can also be used in coordination with volumes. Never directly copy database files from a running container’s host filesystem.
Q6: Host network driver kab use karna chahiye?
When you need maximum performance and low latency, and accept the security trade-off (container has no network isolation, uses host’s network stack directly).
Q7: Volume inspect command se kya information milti hai?
Volume’s mount point on host (location on your filesystem), driver used (local by default), labels attached, options, and creation timestamp. Useful for debugging storage issues.
Q8: Multiple networks mein container connect kaise karein?
A container can be connected to multiple networks using docker network connect. This is useful for scenarios like a proxy container connected to both a public network and an internal backend network.
Q9: Overlay network kyun use karein?
When you need to run multi-host container communication (Docker Swarm mode or multi-node Kubernetes). Overlay networks allow containers on different physical hosts to communicate securely.
Q10: macOS/Windows par bind mount performance slow kyun hoti hai?
Bind mounts on macOS and Windows use file sharing (virtiofs/VirtualBox) which has higher overhead compared to Linux native bind mounts. For performance-critical apps on these OSes, consider using named volumes or synchronize code into volumes.
19. Conclusion – Ab Aapki Baari!
Bahut badhiya! Aapne aaj Docker ke do most important pillars master kar liye:
✅ Docker volumes networking Hindi – Complete guide
✅ Data Persistence – Volumes, bind mounts, tmpfs – kab kaunsa use karna hai
✅ Volume Commands – Create, inspect, prune, backup, restore
✅ Networking – Bridge, host, overlay, macvlan, none drivers
✅ Network Commands – Create, inspect, connect, disconnect
✅ Custom Bridge Networks – DNS resolution, isolation, service discovery
✅ Docker Compose – Volumes aur networks ka practical use
✅ Production Best Practices – Security, backups, monitoring
Docker volumes aur networks aapki multi-container applications ko production-ready banate hain. Ab aap persistent data wali applications bana sakte ho, multiple containers ko efficiently connect kar sakte ho, aur industry-standard best practices follow kar sakte ho.
Aapki challenge: WordPress + MySQL setup implement karo with volumes and custom networks. Add a healthcheck for MySQL and ensure WordPress only starts when MySQL is fully ready. Backup and restore perform karo.
Next topic kya chahiye?
- Deploy Docker Containers to Cloud (AWS ECS, GCP Cloud Run, or Azure Container Instances)?
- Container Orchestration with Docker Swarm (Multi-node Clusters)?
- Setting Up a Local Kubernetes Cluster with Minikube?
Comment mein batao!
The Easy Master ke saath Docker mastery seekhte raho. Happy containerizing! 🐳🔗
Resources
- Docker Storage – Volumes Official Docs
- Docker Networking Overview
- Network Drivers – Bridge, Host, Overlay, Macvlan
- Manage Data in Docker – Official Guide
- Best Practices for Docker Volumes
- Docker Networking Best Practices (CyberPanel 2026)
Additional Resources
- MongoDB Setup – CRUD Operations समझे (Beginner Guide) 2026
- MongoDB Compass से GUI Database Manage करने का आसान तरीका | Beginner Tutorial 2026
- Node.js MongoDB Connection – Mongoose Setup समझे 2026
- MongoDB Data Modeling – Embedded Documents vs References 2026
- MongoDB Indexing – Query Speed बढ़ने करने का आसान तरीका
- MongoDB Aggregation Pipeline – Stages समझे | Practical Examples
- Express MongoDB CRUD – Complete REST API Example
- Mongoose ODM – Schema, Model, and Validation समझे 2026
- MongoDB Atlas – Cloud Database Free में Deploy करें 2026
- JWT Authentication MongoDB – User Login System कैसे बनाएं 2026
- Next.js App Router – Pages Router से क्या बदला? Complete Guide 2026
- Next.js Server Components – ‘use client’ कब और कहां Use करें
- Next.js Routing – Layouts, Dynamic Routes and Nested Routes 2026
- Next.js 16 New Features – Turbopack, Cache Components and proxy.ts
- Next.js Partial Prerendering – Static and Dynamic Content साथ में
- Next.js Authentication – JWT Session Management (App Router) 2026
- Next.js SEO – Metadata API and Image Optimization समझे 2026
- Next.js TypeScript – Full-Stack Type-Safe App कैसे बनाएं
- FastAPI Kya Hai? FastAPI Python Setup Aur Pehla API Hindi 2026
- FastAPI Path Parameters Hindi – शून्य से हीरो तक गाइड 2026
- Pydantic v2 Tutorial Hindi – Data Validation Master 2026
- FastAPI dependency injection Hindi – Code Reuse Ka Magic
- FastAPI Async Await Hindi – Non-Blocking Code 2026
- FastAPI PostgreSQL SQLModel Hindi – Async Guide 2026
- FastAPI JWT Authentication Hindi – Secure API Login
- FastAPI OpenAI Integration Hindi – AI Chatbot API 2026
- FastAPI Multi-Agent AI Hindi – LangGraph Zero to Hero
- FastAPI Deployment Hindi – Railway Zero to Hero 2026
- Docker Introduction in Hindi? Containers vs Virtual Machines
- Docker Images and Containers Hindi – Pehla Container
- Docker Compose Tutorial Hindi – Node.js + MongoDB
Views: 359