Home > OS >  Inherit volumes with extension fields
Inherit volumes with extension fields

Time:04-11


I would like to share host `/etc/timezone` file with all docker services from single `docker-compose.yml` file.

I thought, that using extension fields would be good idea. I've found similar topic where extension fields are used to inherit environment variables.

So, I've tried it with docker-compose.yml like below:

x-timezone-volumes:
  &timezone-volumes
  volumes:
    - "/etc/localtime:/etc/localtime:ro"
    - "/etc/timezone:/etc/timezone:ro"

services:
  postgres-database:
    image: "postgres:12-alpine"
    hostname: PostgresContainer
    networks:
      backend-network:
    env_file:
      - backups/.env.db
    volumes:
      <<: *timezone-volumes
      - ./postgres-data:/var/lib/postgresql/data

and I've this error:

ERROR: The Compose file './docker-compose.yml' is invalid because:
services.postgres-database.volumes contains an invalid type, it should be an array

As i understood from this topic, it is because merge key is outdated.

Does it mean that I can't use it anymore?
Is there any other solution to inherit volumes?

CodePudding user response:

Seems like currently there is no way to use extension fields to inherit items (see upper comment from @David Maze). Therefore, I simply copied the volumes manually to each service separately.

CodePudding user response:

Yaml merge <<: is only supported for mappings. Which is also somewhat indicted by its syntax as its contains a colon.

If you have such an object:

x-timezone-volumes:
  &timezone-volumes
  volumes:
    - "/etc/localtime:/etc/localtime:ro"
    - "/etc/timezone:/etc/timezone:ro"

You can reference it like this:

services:
  app:
    <<: *timezone-volumes

In your case you want to append another item to the volumes array though. So it is not helpful. At max you can reference the individual strings.

x-timezone-volumes:
  &timezone-volumes
  volumes:
    - &tz1 "/etc/localtime:/etc/localtime:ro"
    - &tz2 "/etc/timezone:/etc/timezone:ro"

And then use it like this:

services:
  app:
    volumes:
      - ./foo:/bar
      - *tz1
      - *tz2

You can also mix and match those. Use the first version where there is no additional volume and the second version where you need to add more volumes. For that you could set an anchor name of the entire object and on the array elements.


That said, there is the environment variable TZ which you also can use to control the time zone of containers.

services:
  app:
    environment:
      TZ: UTC
  • Related