Lesson 14: Docker Networking Fundamentals
Containers need to communicate with the outside world and, more importantly, with each other (e.g., a web app talking to a database).
Isolation through Network Drivers
Docker uses Network Drivers to create isolated networks for containers. The three main drivers are:
- Bridge (Default): The most common network. Containers attached to the same bridge network can communicate with each other using their internal IP addresses or container names.
- Host: Removes network isolation; the container shares the host machine's network stack directly (use with caution).
- None: Disables networking completely for the container.
1. Inspecting Default Networks
Check the default networks available on your machine:
bash docker network ls
You will typically see bridge, host, and none.
2. Creating Custom Bridge Networks
While containers automatically attach to the default bridge network, containers on the default bridge can only communicate by IP, which is cumbersome. For better service discovery (using container names), we create a custom bridge network.
bash docker network create my_custom_network
Inspect the newly created network
docker network inspect my_custom_network
3. Connecting Containers to the Network
Use the --network flag when running containers to attach them to your custom network.
Example: Running two containers on the custom network
Container 1 (Database):
bash docker run -d --name db_service --network my_custom_network postgres:15
Container 2 (Application):
bash docker run -d --name app_service --network my_custom_network python:3
Containers in my_custom_network can now reach each other simply by using the container name as the hostname (e.g., app_service can ping db_service). This is the foundation of multi-container applications.