Set default network name for compose

Using compose to create a few containers, I see that it creates a default network called “docker_default”.

  • Is there a way to customize this network’s name without manually creating an external network ahead of time?

  • What happens if there is already another network already called “docker_default” created by some other unrelated compose?

I want to make sure my compose always ends up with the same network name.

1 Like

The name of the network depends on the directory where the “docker-compose.yml” file is in. e.g., if the directory is named “app1” the network will be “app1_default”.

The only way I found to change the name of the network was defining an entry under “networks”:

version: '3'

services:
  app:
    image: whatever
    networks:
      - my-network-name

networks:
  my-network-name:

If you have the same network name in different compose files (or the same directory name), when you run docker-compose start it sometimes will start the wrong container from other of the compose files with the same network name.

With the latest release of Docker-Compose (1.18) they added the possibility to achieve exactly this - i.e. setting a global unique name for networks from a docker-compose.yml. Although it is not terribly well documented, you can read the docs for this change -> https://docs.docker.com/compose/compose-file/#name-1

You need at least Docker Engine 17.06.0 for this to work. If you have both - recent Docker Engine and a still hot docker-compose 1.18 you can achieve it with:

# you need to use the latest version of docker-compose yml
version: '3.5'

services:
  app:
    image: nginx
    networks:
      - my-network-name

networks:
  my-network-name:
   name: my-global-net

This will create the global net my-network-name. Seems like setting the same global network from different docker-compose.yml does not have any effects (nor an error is displayed); although I presume that then all services will obviously in the same overlay network.

N.B. docker-compose down will try to remove the global network.

2 Likes

what output will shown if define name in networks?

You can customize the default network’s name, using:

networks:
  default:
    name: my-awesome-app-network
1 Like
networks:
  default:
    name: my-awesome-app-network

I tried this and got:

…is invalid because: networks.default value Additional properties are not allowed (‘name’ was unexpected)

I’m using docker-compose 3.3. Is that too old?

UPDATE: Changed to 3.6 and it worked.

1 Like