Jan Tajovsky
Jan Tajovsky

Reputation: 1211

Docker-compose env var not working

I am trying to set env var in my docker compose file but the var does not seems to propagate to my docker.

my docker-compose:

test:
  build: ./
  environment:
    TESTVAR: "YOU ARE BEST"

my dockerfile:

FROM alpine

RUN echo test variable is: $TESTVAR

outputs:

Step 1/2 : FROM alpine
 ---> 3fd9065eaf02
Step 2/2 : RUN echo test variable is $TESTVAR
 ---> Running in d5f5505b26db
test variable is
Removing intermediate container d5f5505b26db
 ---> a9c019ac7eff
Successfully built a9c019ac7eff
Successfully tagged phpfpm_test:latest
Recreating phpfpm_test_1 ... done
Attaching to phpfpm_test_1

Am I missing something?

Upvotes: 2

Views: 4239

Answers (2)

Sami Fakhfakh
Sami Fakhfakh

Reputation: 125

You can use .env file in the same directory of docker-compose file , works for me

Upvotes: -2

Sebastian Brosch
Sebastian Brosch

Reputation: 43574

Note: If your service specifies a build option, variables defined in environment are not automatically visible during the build. Use the args sub-option of build to define build-time environment variables. - from docker docs

So you can use arguments (args) instead of environment (environment):

Docker Compose (v2 or v3):

version: '2'  # or 3
services:
  test:
    build: 
      context: ./
    args:
      TESTVAR: 'YOU ARE BEST'

Dockerfile:

FROM alpine
ARG TESTVAR

RUN echo "test variable is: $TESTVAR"

Requirements:

  • Docker Compose: 1.6.0+
  • Docker Engine: 1.10.0+

Note: You need to define the argument (ARG TESTVAR) after the FROM to use the value specified on docker-compose file (more info on StackOverflow).

Upvotes: 5

Related Questions