docker-compose networking

default network

docker compose creates a bridge network by default.

default-network.yaml
services:
web:
image: nginx
db:
image: postgres

services can communicate using service names as hostnames.

custom bridge network

create a custom bridge network with specific configurations:

custom-bridge.yaml
networks:
custom_net:
driver: bridge
driver_opts:
com.docker.network.bridge.name: my-bridge0
ipam:
driver: default
config:
- subnet: 172.28.0.0/16
ip_range: 172.28.5.0/24
gateway: 172.28.5.254
services:
web:
image: nginx
networks:
- custom_net

key properties:

host network

use the host’s network stack:

host-network.yaml
services:
web:
image: nginx
network_mode: host

port exposure

expose ports to the host:

port-exposure.yaml
services:
web:
image: nginx
ports:
- "8080:80"
expose:
- "8000"

external networks

join an existing network:

external-network.yaml
networks:
existing_net:
external: true
name: actual_network_name
services:
web:
image: nginx
networks:
- existing_net

network aliases

create service aliases:

network-aliases.yaml
services:
db:
image: postgres
networks:
backend:
aliases:
- database
networks:
backend:
driver: bridge

default network configuration

configure the default network:

default-network-config.yaml
networks:
default:
driver: bridge
driver_opts:
com.docker.network.driver.mtu: 1400
ipam:
driver: default
config:
- subnet: 172.28.0.0/16

disable networking

isolate a service:

disable-networking.yaml
services:
isolated:
image: alpine
network_mode: none

custom dns

specify custom dns servers:

custom-dns.yaml
networks:
custom_dns:
driver: bridge
dns:
- 8.8.8.8
- 8.8.4.4