Docker Network Types
Docker provides several network drivers to control how containers communicate with each other and with the outside world.
Network Drivers
- bridge: Default network — containers on the same bridge can communicate
- host: Container uses the host's network directly (no isolation)
- none: No networking — fully isolated container
- overlay: Multi-host networking for Docker Swarm
Managing Networks
# List all networks
docker network ls
# Create a custom network
docker network create my-network
# Create with specific subnet
docker network create --subnet=172.20.0.0/16 my-network
# Inspect a network
docker network inspect my-network
# Remove a network
docker network rm my-network
# Remove all unused networks
docker network prune
Connecting Containers
Containers on the same user-defined bridge network can reach each other by container name — Docker provides built-in DNS resolution.
# Create a network for our app
docker network create app-network
# Run a database on the network
docker run -d \
--name db \
--network app-network \
-e POSTGRES_PASSWORD=secret \
postgres:16
# Run the app on the same network
docker run -d \
--name api \
--network app-network \
-e DATABASE_URL=postgres://postgres:secret@db:5432/postgres \
-p 3000:3000 \
myapi:latest
# The api container can reach db by name "db"!
Port Mapping
# Map host port to container port
docker run -d -p 8080:80 nginx # host:container
# Map multiple ports
docker run -d -p 80:80 -p 443:443 nginx
# Map to specific host interface
docker run -d -p 127.0.0.1:8080:80 nginx
# Map a range of ports
docker run -d -p 8000-8010:8000-8010 myapp
# Let Docker choose a random host port
docker run -d -p 80 nginx
docker port # See assigned port
Practical Example: Full Stack App
# Create a shared network
docker network create fullstack
# Database
docker run -d \
--name postgres \
--network fullstack \
-v pgdata:/var/lib/postgresql/data \
-e POSTGRES_PASSWORD=secret \
-e POSTGRES_DB=myapp \
postgres:16
# Redis (for caching/sessions)
docker run -d \
--name redis \
--network fullstack \
redis:7-alpine
# Backend API
docker run -d \
--name api \
--network fullstack \
-e DATABASE_URL=postgres://postgres:secret@postgres:5432/myapp \
-e REDIS_URL=redis://redis:6379 \
-p 4000:4000 \
myapi:latest
# Frontend
docker run -d \
--name frontend \
--network fullstack \
-e API_URL=http://api:4000 \
-p 3000:3000 \
myfrontend:latest
Connect/Disconnect from Networks
# Connect a running container to a network
docker network connect app-network my-container
# Disconnect from a network
docker network disconnect app-network my-container
# A container can be on multiple networks
docker network connect frontend-network api
docker network connect backend-network api
Key Takeaways
- ✅ Always create custom networks — don't rely on the default bridge
- ✅ Containers on the same network communicate by name (DNS)
- ✅ Only expose ports to the host when external access is needed
- ✅ Use
127.0.0.1binding for ports you want to keep local