Docker Networking - Understanding Default, Custom, and Host Networks
There are 3 main docker networks are often used in docker: default-bridge, custom-bridge and host as shown below.
eric:~/ $ sudo docker network ls
NETWORK ID NAME DRIVER SCOPE
d24be9f53feb eric-custom_default bridge local
c30973bff868 bridge bridge local
3a59a9c37489 host host local
33c951c94419 none null local
When running
ip address show
command, you will be seeing all networks includingdocker0
andbr-<network_id>
.
1. Default Bridge Network (Name: bridge
)β
When using docker run
without specifying a network, Docker assigns the container to the default bridge network.
π Source: NetworkChuck on YouTube
β οΈ This default network does not support container name resolution, meaning containers cannot communicate using service names. It is generally not recommended for production use.
2. Custom Bridge Network (e.g., eric-custom
)β
Custom bridge networks behave similarly to the default bridge but support DNS-based container name resolution. This allows containers to talk to each other using their service names, which is essential for many applications.
π‘ When using
docker-compose up
ordocker compose up
, Docker automatically creates a custom bridge network named<project_name>_default
. Theproject_name
defaults to the name of the directory containing thedocker-compose.yml
file.
3. Host Network (Name: host
)β
The host network mode allows containers to share the host's network stack. The container will not get its own IP but instead use the host's IP address and port space.
This offers better performance (due to no NAT layer) but increases the risk of security vulnerabilities, as the container can directly access the host's network interfaces and services.
π Use Case: Cloudflare Tunnel with Host Networkβ
Use case: Cloudflare Tunnel
A practical example of using the host network is running aCloudflare Tunnel
container. By sharing the hostβs network stack, the container behaves like a native background process. This makes it easier to expose services running on the host machine to the internet via Cloudflare's secure tunneling service.
π§ Extra Tips: Advanced Networking with Dockerβ
π How to Create a Custom Networkβ
You can manually create a custom network using:
docker network create my-custom-network
You can also add options like --subnet
and --gateway
for custom IP settings.
π Sharing a Network Across Multiple Docker Compose Projectsβ
- First, create a shared external network:
docker network create shared-net
- In each
docker-compose.yml
, specify the external network:
networks:
default:
external:
name: shared-net
This allows containers from different Compose projects to communicate with each other.
π Inspecting Docker Networksβ
You can inspect a networkβs details using:
docker network inspect <network_name>
This provides useful information such as connected containers, subnet, gateway, etc.βhandy for debugging.