docker-compose networking
default network
docker compose creates a bridge network by default.
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:
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:
driver
: network driver (bridge, overlay, host, macvlan)driver_opts
: driver-specific optionsipam
: ip address management settings
host network
use the host’s network stack:
services: web: image: nginx network_mode: host
port exposure
expose ports to the host:
services: web: image: nginx ports: - "8080:80" expose: - "8000"
ports
: publish container ports to hostexpose
: expose ports without publishing to host
external networks
join an existing network:
networks: existing_net: external: true name: actual_network_name
services: web: image: nginx networks: - existing_net
network aliases
create service aliases:
services: db: image: postgres networks: backend: aliases: - database
networks: backend: driver: bridge
default network configuration
configure the default network:
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:
services: isolated: image: alpine network_mode: none
custom dns
specify custom dns servers:
networks: custom_dns: driver: bridge dns: - 8.8.8.8 - 8.8.4.4