Docker Community Forums

Share and learn in the Docker community.

Is it possible to set global settings for services in a docker compose file?

Is it possible to specify global settings for services in a Docker compose file?

For example, take this Docker Compose file:

version: "3.9"

services:
  test1:
    env_file: /path/to/env/file
    image: test
    container_name: test1
    ports:
      - "1234:22"
    networks:
      - dmz
    restart: always
  test2:
    env_file: /path/to/env/file
    image: test
    container_name: test2
    ports:
      - "2345:22"
    networks:
      - trust
    restart: always

networks:
  dmz:
    driver: bridge
  trust:
    driver: bridge

I don’t want to have env_file: /path/to/env/file for every service and would like to make it apply to all services. I know I can pass it in the docker-compose command line but I’m hoping to do it from within the Docker compose file.

You could declare one or more placeholders between version and services and use yaml anchors to “reuse” its/their content, see this blog post for example usage: https://nickjanetakis.com/blog/docker-tip-82-using-yaml-anchors-and-x-properties-in-docker-compose

The first control questions would be: why would you want global environment variables for your services? Wouldn’t you leak environment variables into containers that don’t necessarily need them?

1 Like

Not just for environmental variables but for any setting. What you linked works great cause I can create different global templates and apply them to containers as needed. Thanks!