0
0
DockerHow-ToBeginner · 3 min read

How to Use Custom Network in Docker Compose

To use a custom network in Docker Compose, define the network under the networks section in your docker-compose.yml file and assign it to your services using the networks key. This lets containers communicate on a user-defined network instead of the default one.
📐

Syntax

In docker-compose.yml, you define custom networks under the networks key at the root level. Then, under each service, you specify which network(s) it should connect to using the networks key.

This setup controls how containers communicate and isolates them from other networks.

yaml
version: '3.8'
services:
  service_name:
    image: your_image
    networks:
      - custom_network

networks:
  custom_network:
    driver: bridge
💻

Example

This example shows two services connected to a custom bridge network named my_custom_net. They can communicate with each other using service names.

yaml
version: '3.8'
services:
  web:
    image: nginx:alpine
    networks:
      - my_custom_net
  app:
    image: busybox
    command: ping -c 4 web
    networks:
      - my_custom_net

networks:
  my_custom_net:
    driver: bridge
Output
PING web (172.18.0.2): 56 data bytes 64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.123 ms 64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.110 ms 64 bytes from 172.18.0.2: seq=2 ttl=64 time=0.105 ms 64 bytes from 172.18.0.2: seq=3 ttl=64 time=0.102 ms --- web ping statistics --- 4 packets transmitted, 4 packets received, 0% packet loss
⚠️

Common Pitfalls

  • Forgetting to define the custom network under the networks section causes errors.
  • Not assigning services to the custom network means they use the default network and may not communicate as expected.
  • Using the wrong network driver can cause connectivity issues; bridge is the most common for local setups.
yaml
version: '3.8'
services:
  web:
    image: nginx:alpine
    # Missing networks key here

networks:
  my_custom_net:
    driver: bridge

# Correct way:
# services:
#   web:
#     image: nginx:alpine
#     networks:
#       - my_custom_net
📊

Quick Reference

Use this quick guide to remember how to set up custom networks in Docker Compose:

StepDescriptionExample
1Define custom network under networksmy_network: driver: bridge
2Assign network to services under networksservices: app: networks: - my_network
3Use service names to communicate between containersping app
4Use docker-compose up to start with custom networkdocker-compose up -d

Key Takeaways

Define custom networks under the 'networks' section in docker-compose.yml.
Assign services to the custom network using the 'networks' key inside each service.
Use the 'bridge' driver for common local network setups.
Containers on the same custom network can communicate using service names.
Always verify network definitions to avoid connectivity issues.