Define local variable in docker-compose.yml?

Viewed 3964

Is it possible to define local variable in docker-compose.yml?

Something like this for example:

version: '3'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    image: $APP_NAME
    container_name: $APP_NAME

Can I define the value of $APP_NAME on this same docker-compose.yml file?

1 Answers

Starting from docker-compose file version 3.4, you can define a top level x- prefixed section in the compose file. It will be parsed as valid yml but ignored by compose when creating services, network, volumes, etc...

version: '3.4'

x-var: &APP_NAME
  myimage

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    image: *APP_NAME
    container_name: *APP_NAME

You can even use this feature to define "object", like:

x-common: &common
  image: ${REGISTRY_URL}img:latest

services:
  master:
    <<: *common
Related