Skip to content
Docker

5. Docker Volumes Networking Hindi – Data Persist कैसे करें

May 30, 2026 28 min read

नमस्ते दोस्तों!

स्वागत है 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:

  1. आपने docker run -d --name my-postgres postgres चलाया।
  2. Database mein table banayi, data insert kiya।
  3. docker stop my-postgres aur docker rm my-postgres चलाया।
  4. 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:

FeatureContainer Writable LayerDocker Volume
PersistenceContainer delete = data deleteContainer delete = data safe
LocationContainer filesystem ke andarHost filesystem mein (Docker-managed)
BackupManualEasy (docker run --rm -v volume:/data alpine tar czf ...)
SharingMultiple containers share nahi kar sakteMultiple 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

TypeHow it worksWhen to use
Named VolumeDocker-managed, specified by name (my-data-volume)Production databases, application data
Anonymous VolumeDocker automatically generates random IDTemporary data, testing
Bind MountHost path mapped directly (/home/user/data:/app/data)Development hot reload, config files
tmpfs MountRAM में stored, non-persistentSession 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

AspectNamed VolumeBind Mount
ManagementDocker fully manages (location, permissions)You manage path and permissions
BackupEasier (use Docker commands)Manual (tar, rsync)
PerformanceBetter for databases (native filesystem)Same, but depends on host OS
PortabilityHigh – works on any Docker hostLow – path-specific
Use caseProduction databases, application dataDevelopment 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):

Code
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

Code
docker run -d \
  -v "$(pwd)":/app \
  -v /app/node_modules \
  -p 3000:3000 \
  --name node-dev \
  node:20-alpine \
  npx nodemon server.js

Second -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

Code
docker run -d \
  --tmpfs /tmp \
  --name temp-container \
  nginx

Or using --mount syntax:

Code
docker run -d \
  --mount type=tmpfs,destination=/app/cache,tmpfs-size=100M \
  my-app

Limitations:

  • 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

NeedSolution
Database data that must survive container deletionNamed Volume
Configuration files you want to edit on hostBind Mount
Temporary session data that can be losttmpfs
Secrets that shouldn’t be written to disktmpfs
Code during development (hot reload)Bind Mount
Production application logsNamed Volume or Bind Mount to central location
Cache that regenerates quicklytmpfs

5. Volume Management Commands – Cheat Sheet

TaskCommand
List all volumesdocker volume ls
Create a named volumedocker volume create mydata
Inspect volume detailsdocker volume inspect mydata
Remove a specific volumedocker volume rm mydata
Remove all unused volumesdocker 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 syntaxdocker run --mount source=mydata,target=/data alpine
Backup a volumedocker run --rm -v mydata:/source -v $(pwd):/backup alpine tar czf /backup/backup.tar.gz -C /source .
Restore a volumedocker 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:

Code
# 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_dump for 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

Code
docker volume create mysql-data

Verify volume create hua:

Code
docker volume ls

Step 2: Run MySQL Container with Volume

Code
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

Code
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

Code
docker stop mysql-demo
docker rm mysql-demo

Container delete ho gaya.

Step 5: Create New Container with Same Volume

Code
docker run -d \
  --name mysql-demo-new \
  -e MYSQL_ROOT_PASSWORD=root123 \
  -v mysql-data:/var/lib/mysql \
  mysql:8.0

Step 6: Verify Data Still Exists

Code
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

Code
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

Code
mkdir my-website
cd my-website
echo '<h1>Namaste Docker Bind Mount!</h1>' > index.html

Step 2: Run Nginx with Bind Mount

Bash
docker run -d \
  --name web-dev \
  -p 8080:80 \
  -v "$(pwd)":/usr/share/nginx/html \
  nginx

Browser mein http://localhost:8080 खोलो – “Namaste Docker Bind Mount!” dikhna chahiye.

Step 3: Edit File and See Changes

Code
echo '<h1>Updated! Bind mount is awesome</h1>' > index.html

Refresh browser – changes automatically reflect. No container restart needed.

Step 4: Clean Up

Code
docker stop web-dev
docker rm web-dev

Bind mount data host par already hai, kuch delete nahi hoga।

💡 Pro Tip: For development, combine bind mounts with live reload tools like nodemon in Node.js, --reload in 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:

  1. Sandbox – Container ka isolated network stack (network interfaces, routing tables, DNS)
  2. Endpoint – Network interface jo container ko network se connect karta hai
  3. 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

DriverDescriptionUse Case
bridgeDefault driver when no driver specified. Creates private internal network on hostSingle-host container communication, default for most applications
hostRemoves network isolation between container and Docker host; uses host’s network directlyPerformance-critical services needing low latency; bypasses network translation
overlayConnects multiple Docker daemons together (multi-host communication)Docker Swarm, multi-node clusters
macvlanAssigns a MAC address to container making it appear as physical device on networkLegacy applications expecting direct physical network access
noneDisables all networking for containerHighly isolated batch jobs, security sandboxes
ipvlanProvides full control over IPv4 and IPv6 addressingAdvanced 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

TaskCommand
List all networksdocker network ls
Create a networkdocker network create my-network
Create network with specific driverdocker network create --driver bridge my-network
Inspect network detailsdocker network inspect my-network
Connect running container to networkdocker network connect my-network my-container
Disconnect container from networkdocker network disconnect my-network my-container
Remove a networkdocker network rm my-network
Remove all unused networksdocker 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:

Code
# List networks
docker network ls

# Create custom network
docker network create --driver bridge my-app-network

# Inspect
docker network inspect my-app-network

11. Hands-On #3 – Custom Bridge Network Banayein

Step 1: Create Custom Bridge Network

Code
docker network create --driver bridge my-custom-net

Step 2: Verify Network Created

Code
docker network ls

Aapko my-custom-net dikhega with driver bridge।

Step 3: Run Two Containers on Same Network

Container 1:

Code
docker run -d --name container1 --network my-custom-net alpine sleep 3600

Container 2:

Code
docker run -d --name container2 --network my-custom-net alpine sleep 3600

Step 4: Test Communication Between Containers

Container 1 se container 2 ping karein using container name:

Code
docker exec -it container1 ping container2

Successful 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

Code
docker network inspect my-custom-net

Connected containers ki list dikhegi.

Step 6: Clean Up

Code
docker stop container1 container2
docker rm container1 container2
docker network rm my-custom-net

12. 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

Code
docker network create app-network

Step 2: Run MySQL Container on the Network

Code
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.0

Step 3: Create Simple Node.js App

Create app.js:

Code
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

Code
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

Code
docker build -t my-node-app .
docker run -d --name node-app --network app-network -p 3000:3000 my-node-app

Browser mein http://localhost:3000 – message dikhna chahiye.

Step 6: Verify Network

Code
docker network inspect app-network

Both mysql-db and node-app containers should appear in "Containers" section.

Step 7: Clean Up

Code
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

Code
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: bridge

What Compose does automatically:

  • Creates wordpress-network bridge network
  • Adds both services to this network
  • Services can reach each other using service names (wordpress can connect to hostname db)
  • Creates named volumes wordpress_data and db_data

Run with:

Code
docker compose up -d

Volumes 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

Code
wordpress-project/
├── compose.yaml
└── .env

compose.yaml

Code
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)

Code
DB_USER=wpuser
DB_PASSWORD=secure_password_here
DB_NAME=wordpress_db
ROOT_PASSWORD=root_password_here

Run the Project

Code
docker compose up -d

Wait for both containers to be healthy, then access http://localhost:8080 to complete WordPress installation.

Backup Volumes (Production Best Practice)

Code
# 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.sql

Restore from Backup

Code
# 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_db

15. 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!)

MistakeKyun Galat Hai?Solution
Bind mount for database in productionPerformance issues, permission problems, no volume management featuresUse named volumes for all production databases
Forgetting volume when container recreatedData loss occurs every time container is recreatedAlways define volumes in compose file
Using default bridge networkNo DNS resolution, containers must use IP addresses, which change on restartCreate user-defined bridge networks for inter-container communication
Not using healthchecks with depends_onContainer starts before dependency is ready, causing errorsAdd healthcheck to dependencies and use condition: service_healthy
Hardcoding secrets in compose fileSecrets exposed in version controlUse .env files and add to .gitignore
Not backing up volumesData loss if host fails or volume corruptsRegular automated backups (scheduled with crond in a utility container)
Using :latest tag for imagesUnpredictable behavior across environmentsPin specific image versions (e.g., mysql:8.0.41 not mysql:latest)
Not setting restart policiesContainer doesn’t auto-recover after crash or host rebootSet restart: unless-stopped in compose services
Exposing all portsIncreased attack surface and potential conflictsOnly 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

TaskCommand
Create named volumedocker volume create my-data
Run container with volumedocker run -v my-data:/data alpine
List volumesdocker volume ls
Inspect volumedocker volume inspect my-data
Remove volumedocker volume rm my-data
Remove unused volumesdocker volume prune
Backup volumedocker run --rm -v my-data:/source -v $(pwd):/backup alpine tar czf /backup/backup.tar.gz -C /source .
Restore volumedocker run --rm -v my-data:/target -v $(pwd):/backup alpine tar xzf /backup/backup.tar.gz -C /target

Networking Cheat Sheet

TaskCommand
List networksdocker network ls
Create bridge networkdocker network create my-net
Run container on networkdocker run --network my-net alpine
Connect container to networkdocker network connect my-net my-container
Inspect networkdocker network inspect my-net
Remove networkdocker network rm my-net
Remove unused networksdocker network prune

Docker Compose Cheat Sheet

Code
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: bridge

Practice 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

Additional Resources

Views: 359

TheEasyMaster

Author at The Easy Master.

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *