🌐 Containers Talk to Each Other
Multiple containers need to communicate. Docker Compose networking makes it easy. Use service names as hostnames.
📝 Docker Compose Networking
version: '3.8'
services:
web:
build: .
ports:
- "8080:8080"
environment:
- DB_HOST=postgres
- REDIS_HOST=redis
postgres:
image: postgres:15
environment:
POSTGRES_PASSWORD: secret
redis:
image: redis:alpine
# Inside web container:
# ping postgres → resolves to postgres container IP
# ping redis → resolves to redis container IP
🎯 Custom Networks
version: '3.8'
services:
web:
networks:
- frontend
- backend
api:
networks:
- backend
database:
networks:
- backend
nginx:
networks:
- frontend
networks:
frontend:
driver: bridge
backend:
driver: bridge
# web can talk to nginx and api
# api can talk to web and database
# nginx can only talk to web
# database can only talk to api
💡 Commands
- docker-compose up (creates default network)
- docker-compose up -d (detached mode)
- docker network ls (list networks)
- docker network inspect (inspect network)
- Service names resolve to container IPs
“Web couldn’t connect to DB. Used service name ‘postgres’ as hostname. Fixed. Docker Compose networking is simple and powerful.”
