Docker is powerful not just because it runs apps, but because it gives you tight control over data persistence and inter-container communication. In this blog, we'll demystify Docker volumes and networks with clean examples and code you can run right away.
Volumes are Docker's way of storing persistent data outside your container's ephemeral layer. Even if your container dies, volume data survives.
Anonymous volumes: Created without a name. Harder to manage.
docker run -v /data busybox
Named volumes: Easier to reference, reuse, or delete.
docker volume create mydata
docker run -v mydata:/data busybox
This binds a local folder from your machine to a path inside the container โ ideal for development.
docker run -v $(pwd)/myapp:/usr/src/app node:18
Note: On Windows, use %cd% or provide full paths.
docker run --rm -v mydata:/data -v $(pwd):/backup alpine \
tar czf /backup/backup.tar.gz -C /data .
docker run --rm -v mydata:/data -v $(pwd):/backup alpine \
tar xzf /backup/backup.tar.gz -C /data
Every container has its own IP address. Docker helps them communicate using different types of networks.
Great for container-to-container networking with custom isolation.
docker network create my-bridge
Run two containers on the same network:
docker run -d --name db --network my-bridge mongo
docker run -it --network my-bridge mongo mongo --host db
Explanation: The app container can now use db as the hostname to connect to
MongoDB.
Shares the host's network stack. Useful for performance-heavy or system-level containers.
docker run --network host nginx
To access services from your host machine:
docker run -p 8080:80 nginx
-p 8080:80 maps port 80 inside the container to port 8080 on your hostLet's create a shared volume between a writer and reader container.
docker volume create sharedvol
docker run -d --name writer --mount source=sharedvol,target=/data busybox \
sh -c "echo 'Hello Docker' > /data/hello.txt && sleep 3600"
docker run --rm --mount source=sharedvol,target=/data busybox \
cat /data/hello.txt
๐ฅณ Yes, the reader container sees data written by another container!
Here's how to connect a Node.js app to a MongoDB container using Docker networking.
# Dockerfile
FROM node:18
WORKDIR /app
COPY . .
RUN npm install
CMD ["node", "index.js"]
const { MongoClient } = require("mongodb");
const url = "mongodb://db:27017";
MongoClient.connect(url).then(() => {
console.log("โ
Connected to MongoDB container");
});
docker network create app-net
docker run -d --name db --network app-net mongo
docker build -t my-node-app .
docker run --network app-net my-node-app
๐ฅ Your app is now talking to a database inside another container โ no IP addresses needed, just container names!
-v and -p to mount volumes and expose ports.You now have the core foundation to manage data and networking in Docker like a pro.
In our next post, we'll dive into ๐งฉ (Post 3): Docker Compose in Action: Building Multi-Container Apps!
โ Blog by Aelify (ML2AI.com)
๐ Documentation Index