1

I am writing a docker-compose.yml and have several containers that require certain environment variables set to the same value (ie CONTACT_EMAIL).

Currently my docker-compose.yml looks something like this:

version: '2.0'
    services:
        service1:
            ...
            environment:
                CONTACT_EMAIL: webmaster@example.com
            ...
        service2:
            ...
            environment:
                CONTACT_EMAIL: webmaster@example.com
            ...
        service3:
            ...
            environment:
                CONTACT_EMAIL: webmaster@example.com
            ...

Is there a way to define a variable/ constant WEBMASTER within the yaml file and assign the value to the CONTACT_EMAIL environment variables?

Or is it possible to define an environment for all services (within the yaml file)?

Benj
  • 864
  • 1
  • 12
  • 27

2 Answers2

1

You can use env file, create env file where you add all your values and refer the same file in all services in docker-compose. Check this: https://docs.docker.com/compose/environment-variables/

Learner
  • 67
  • 8
1

You can do something like this:

version: "2.0"

x-common-env: &common_env
  CONTACT_EMAIL: webmaster@example.com

services:
  service1:
    ...
    environment:
      <<: *common_env

  service2:
    ...
    environment:
      <<: *common_env
      ANOTHER_ENV: abc
leo
  • 56
  • 2
  • Can you please elaborate a bit on how that works? – Benj Jun 23 '21 at 07:30
  • As you can see above: - First, you create a reusable definition named `common_env` or whatever you like, containing all the settings that you could reuse later. - When using it, use syntax `<<: config="" definition.="" everything="" have="" inside="" print="" syntax="" test="" that="" the="" to="" using:="" you=""> – leo Jun 23 '21 at 07:43
  • Interesting. And the x-common-env label serves no practical purpose? – Benj Jun 23 '21 at 08:20
  • yeah, just make sure it is unique, and start with `x-`. It is called "extension" if you curious. – leo Jun 23 '21 at 08:21
  • @Benj Some more details on YAML anchors: https://stackoverflow.com/q/41063361/1108305, https://stackoverflow.com/q/6651275/1108305. – M. Justin Apr 15 '22 at 15:44