Extend service in docker-compose 3

You can extract common environment variables to a env file.

Thereafter you can use the env_file configuration option in your compose file.

-> cat common.env
      VAR2=val2
      VAR3=val3

You can still pass/overwrite environment variables other than those specified in common.env using the environment configuration option.

myotherservice:
  build:
    context: ./myservice
  command: ./somethingelse
  env_file: ./common.env
  environment:
    VAR1: "val1-bis"

Reference

  • https://docs.docker.com/compose/environment-variables/#the-env-file

This is very easy with YAML:

version: "3"

services:
  myservice: &myservice
    build:
      context: ./myservice
    command: ./something
    environment: &myservice_environment
      VAR1: "val1"
      VAR2: "val2"
      VAR3: "val3"

myotherservice:
    <<: *myservice
    environment:
      <<: *myservice_environment
      VAR1: "val1-bis"

See the doc regarding extension-fields