Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define local variable in docker-compose.yml?

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?

like image 405
IMB Avatar asked Jan 07 '19 17:01

IMB


People also ask

Can you use variables in Docker compose file?

In Docker Compose, IT admins can use environment variables to generalize configurations for different situations, deployment environments and security contexts without editing the main project file(s) manually. Variables can either be passed as command-line arguments -- suitable for only a few parameters -- or via a .

How do I set an environment variable in Docker?

Use -e or --env value to set environment variables (default []). If you want to use multiple environments from the command line then before every environment variable use the -e flag. Note: Make sure put the container name after the environment variable, not before that.

How do I pass a variable in Docker?

When we launch our Docker container, we can pass environment variables as key-value pairs directly into the command line using the parameter –env (or its short form -e). As can be seen, the Docker container correctly interprets the variable VARIABLE1.


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
like image 119
Siyu Avatar answered Nov 15 '22 04:11

Siyu