Docker Networking Explained
Understanding Docker networking lets you connect containers together, expose services, and isolate applications.
Default Network Modes
- bridge (default): Each container gets its own IP in a private subnet. Containers communicate by IP or container name (on user-defined networks).
- host: Container shares the host's network stack directly. No port mapping needed, but less isolation.
- none: No network. Fully isolated.
List Networks
docker network ls
Create a Custom Network
docker network create mynet
Connect Containers on a Custom Network
docker run -d --name db --network mynet mysql:8
docker run -d --name app --network mynet myapp:latest
Containers on the same network can reach each other by name: app connects to db:3306.
Port Mapping
docker run -d -p 80:80 nginx # Host port 80 -> container port 80
docker run -d -p 127.0.0.1:3306:3306 mysql # Bind only to localhost
In Docker Compose (Automatic Network)
Compose creates a default network for all services in a file. Services can reference each other by service name:
services:
app:
image: myapp
depends_on:
- db
db:
image: mysql:8
app connects to MySQL at hostname db, port 3306.
Inspect a Network
docker network inspect mynet