Introduction
Docker networking enables container communication, while volumes provide persistent data storage. Understanding both is essential for production deployments.
Docker Networks
# List networks
docker network ls
# Create a custom network
docker network create mynet
# Run container on specific network
docker run -d --name app --network mynet nginx
# Connect running container to network
docker network connect mynet mycontainer
# Inspect network
docker network inspect mynet
Network Types
# Bridge (default) - isolated network
docker run -d --network bridge nginx
# Host - use host network directly
docker run -d --network host nginx
# None - no networking
docker run -d --network none alpine
Volumes for Persistent Data
# Create a volume
docker volume create mydata
# Run with volume mount
docker run -d -v mydata:/app/data postgres
# Bind mount (host path)
docker run -d -v /host/path:/container/path nginx
# List volumes
docker volume ls
# Remove unused volumes
docker volume prune
Compose with Networks and Volumes
version: "3.8"
services:
app:
build: .
networks:
- frontend
- backend
volumes:
- ./data:/app/data
db:
image: postgres:15
networks:
- backend
volumes:
- dbdata:/var/lib/postgresql/data
networks:
frontend:
backend:
volumes:
dbdata:
Summary
Use custom networks for container isolation and communication. Use named volumes for persistent data and bind mounts for development. Compose ties them together elegantly.
YouTip