Docker Networking
Overview
Docker networking allows containers to communicate with each other and with the host system. This guide covers different network types, container communication, and best practices.
Network Types
Bridge Network (Default)
The default network type for standalone containers.
bash
# Create custom bridge network
docker network create my-network
# Connect container to network
docker run -d --network my-network --name web nginx
# Connect existing container
docker network connect my-network container-idHost Network
Container uses the host's network stack.
bash
docker run -d --network host nginxOverlay Network
For swarm and Kubernetes - enables multi-host networking.
bash
docker network create --driver overlay my-overlay-networkContainer Communication
DNS Service Discovery
Containers can communicate using service names as hostnames:
bash
# In docker-compose.yml
services:
web:
image: nginx
api:
image: myapi
# Access web via: http://web:80Exposing Ports
bash
# Expose port to host
docker run -d -p 8080:80 nginx
# Expose port to specific IP
docker run -d -p 127.0.0.1:8080:80 nginxBest Practices
✅ Docker Networking Best Practices
✅ DO
Use custom bridge networks
For container-to-container communication with DNS resolution
✅ DO
Use host network sparingly
Only for performance-critical applications that need direct host access
✅ DO
Use overlay networks
For distributed applications across multiple hosts
❌ DON'T
Use host network carelessly
Avoid with multiple containers on same port - causes conflicts
❌ DON'T
Rely on default bridge
Don't use auto-generated default bridge - create custom networks instead