How to pass arguments within docker-compose?

DockerDockerfileDocker Compose

Docker Problem Overview


Docker 1.9 allows to pass arguments to a dockerfile. See link: https://docs.docker.com/engine/reference/builder/#arg

How can I pass the same arguments within docker-compose.yml?
Please provide an example too, if possible.

Docker Solutions


Solution 1 - Docker

Now docker-compose supports variable substitution.

Compose uses the variable values from the shell environment in which docker-compose is run. For example, suppose the shell contains POSTGRES_VERSION=9.3 and you supply this configuration in your docker-compose.yml file:

db:
  image: "postgres:${POSTGRES_VERSION}"

When you run docker-compose up with this configuration, Compose looks for the POSTGRES_VERSION environment variable in the shell and substitutes its value in. For this example, Compose resolves the image to postgres:9.3 before running the configuration.

Solution 2 - Docker

This can now be done as of docker-compose v2+ as part of the build object;

> docker-compose.yml

version: '2'
services:
    my_image_name:
        build:
            context: . #current dir as build context
            args:
                var1: 1
                var2: c

See the docker compose docs.

In the above example "var1" and "var2" will be sent to the build environment.

Note: any env variables (specified by using the environment block) which have the same name as args variable(s) will override that variable.

Solution 3 - Docker

This feature was added in Compose file format 1.6.

Reference: https://docs.docker.com/compose/compose-file/#args

services:
  web:
    build:
      context: .
      args:
        FOO: foo

Solution 4 - Docker

Something to add to these answers that the args are picked up only when using docker-compose up --build and not when using docker-compose build. If you want to build and run in separate steps, you need use docker-compose build --build-arg YOUR_ENV_VAR=${YOUR_ENV_VAR}or docker build --build-arg YOUR_ENV_VAR=${YOUR_ENV_VAR}

Solution 5 - Docker

  1. Create a variable environment on Linux shell:

    export TAG=0.1.2
    
  2. Set variable inside docker-compose.yml

    db:
      image: "redis:${TAG}"
    
  3. Verify if value was replaced

    docker-compose config
    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmeallhourView Question on Stackoverflow
Solution 1 - DockerHemerson VarelaView Answer on Stackoverflow
Solution 2 - DockertgallacherView Answer on Stackoverflow
Solution 3 - DockerdnephinView Answer on Stackoverflow
Solution 4 - DockerAndyFaizanView Answer on Stackoverflow
Solution 5 - DockerJhonny Ramirez ZeballosView Answer on Stackoverflow