Rpj
Rpj

Reputation: 6080

How to customize network name in docker-compose file

    version: '3.8'
    
    services:
      foo:
        ...
        networks:
          - $FOO_NETWORK

networks:
  foo_network:

I am unable to use $FOO_NETWORK under networks, i.e. it allows only to enter a value and not an ENV variable. How do I customize the network name to be taken from the environment variable instead

Upvotes: 4

Views: 8383

Answers (1)

anemyte
anemyte

Reputation: 20176

Environment variables are for values, you want to use it for a key. As far as i know this isn't supported yet and I'm not sure if it'll ever be.

One way you can customise this is to use multiple docker-compose files. Create three files:

one.yml:

version: "3.0"

services:
  test:
    image: nginx

two.yml:

version: "3.0"

services:
  test:
    networks:
      foo: {}

networks:
  foo: {}

three.yml:

version: "3.0"

services:
  test:
    networks:
      bar: {}

networks:
  bar: {}

Now you if you run it like this:

docker-compose -f one.yml -f two.yml up

or like this:

docker-compose -f one.yml -f three.yml up

You'll see that the files are merged:

Creating network "network_foo" with the default driver
Recreating network_test_1 ... done
...
Creating network "network_bar" with the default driver
Recreating network_test_1 ... done

You can even spin all three at once:

docker-compose -f one.yml -f two.yml -f three.yml up
Creating network "network_foo" with the default driver
Creating network "network_bar" with the default driver
Creating network_test_1 ... done
Attaching to network_test_1
test_1  | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration

Check out documentation for more: https://docs.docker.com/compose/extends/

Also there is another way, which actually involves using variables to select a network. The way is to use existing networks. You'll need an .env file for this:

network=my_network

and in compose file you do like this:

version: "3.8"

services:
  test:
    networks:
      mynet: {}

networks:
  mynet:
    external: true
    name: $network

As you see there is an option to provide name when using an external network. The network with the name must exist when you start your containers or you'll get an error. You can use a separate file to create networks on a node or just create using CLI. Note that the compose version changed, the feature isn't supported in "3.0".

Upvotes: 5

Related Questions