Container Communication: Configuring Docker Networks
Docker containers are isolated by default. To allow containers to communicate with each other securely, Docker uses Networks.
1. Network Drivers Reference
- Bridge (Default): Creates a private internal network on your host machine. Containers on the same bridge network can communicate, while remaining isolated from external networks.
- Host: Removes isolation between the container and the host machine. The container shares the host's network namespace directly.
- None: Disables all networking for the container.
2. Setting Up Container Communication
To connect a web application container to a database container:
Step 1: Create a Custom Bridge Network
Do not use the default bridge network, as it does not support automatic container name resolution (DNS):
# Create network named 'app-net'
docker network create app-netStep 2: Run the Database Container
Run your database container on the custom network:
docker run -d --name database-server --network app-net postgresStep 3: Run the Web Application Container
Run your application container on the same network:
docker run -d --name api-server --network app-net -p 3000:3000 my-api-imageBecause both containers are on app-net, the application container can connect to the database container using its name as the hostname: database-server (for example, postgres://database-server:5432).
3. Managing Networks via CLI
Use these commands to manage networks:
# List all active networks
docker network ls
# Inspect network configurations and connected containers
docker network inspect app-net
# Disconnect a container from a network
docker network disconnect app-net api-serverPublished on Last updated: