What is Docker Networking?
Docker Networking allows containers to communicate with each other and with the outside world. By default, each container is isolated, but Docker provides several network drivers to connect them.
Docker Network Types
| Network Driver | Description |
|---|---|
| bridge | Default network. Containers on same bridge can communicate. |
| host | Container shares host network (no isolation). |
| none | No networking. Fully isolated container. |
| overlay | Used in Docker Swarm for multi-host networking. |
| macvlan | Assigns a real MAC address to container. |
Network Commands
| Command | Description |
|---|---|
docker network ls | List all networks |
docker network create <name> | Create a custom network |
docker network inspect <name> | View network details |
docker network connect <net> <container> | Connect container to network |
docker network disconnect <net> <container> | Disconnect container from network |
docker network rm <name> | Remove a network |
Example 1: Default Bridge Network
# Run two containers on default bridge
docker run -d --name container1 nginx
docker run -d --name container2 ubuntu sleep 3600
# Inspect default bridge network
docker network inspect bridge
Example 2: Create Custom Network & Connect Containers
# Create custom bridge network
docker network create my-network
# Run containers connected to custom network
docker run -d --name web --network my-network nginx
docker run -d --name app --network my-network ubuntu sleep 3600
# From app container, ping web container by name
docker exec -it app bash
ping web
On a custom bridge network, containers can resolve each other by container name (DNS).
Example 3: Host Network
# Container shares host network stack
docker run -d --network host nginx
Nginx will be accessible on port 80 of the host directly without port mapping.
Example 4: Connect PHP App to MySQL Container
# Create shared network
docker network create app-network
# Start MySQL
docker run -d --name mysql --network app-network -e MYSQL_ROOT_PASSWORD=secret mysql:8.0
# Start PHP app on same network
docker run -d --name php-app --network app-network -p 8080:80 my-php-image
Inside the PHP app, connect to MySQL using hostname mysql (container name):
$pdo = new PDO("mysql:host=mysql;dbname=mydb", "root", "secret");
Summary
- Docker networking allows containers to communicate with each other.
- The bridge network is the default; containers on the same bridge can talk.
- Use custom networks so containers can resolve each other by name (DNS).
- Connect a PHP app to MySQL by putting them on the same Docker network.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
