SoFunction
Updated on 2025-04-07

How to customize network with docker-compose

docker-compose custom network

In Docker Compose, you can passnetworksConfigure to define and use bridge networks.

Docker creates an isolated network for each service by default, but you can also explicitly connect multiple services to the same network.

Here is how to specify the use in the Docker Compose filebridgeExample of the network.

First, you need toDefine the network in the file.

For example, create a name calledmy-bridge-networkBridged network:

version: '3.9'
services:
  web:
    image: nginx:latest
    networks:
      - my-bridge-network

  db:
    image: postgres:latest
    networks:
      - my-bridge-network

networks:
  my-bridge-network:
    driver: bridge

In this example, we define two services:webanddb

Both services are connected to the namemy-bridge-networkon the bridge network. This allows them to communicate with each other.

Things to note

  1. Driver: driver: bridgeSpecifies that this network is based on bridge. This is the default value, so it can usually be omitted.
  2. Communication between services: Services in the same network can be directly accessed by the service name, for examplewebServices can be by namedbCome and visitdbServe.
  3. IP address: If you need to assign a specific IP address to a service, you cannetworksUsed in configurationipv4_addressOptions.

If you want to use the default bridge network instead of a custom bridge network, you can simply delete itnetworksand allows Docker Compose to automatically create default networks for each service.

For example:

version: '3.9'
services:
  web:
    image: nginx:latest

  db:
    image: postgres:latest

In this case, each service will be connected to a default bridged network.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.