Search code examples
shelldockerdocker-composeshposix

Dockerfile: how to set env variable from file contents


I want to set an environment variable in my Dockerfile.

I've got a .env file that looks like this: FOO=bar.

Inside my Dockerfile, I've got a command that parses the contents of that file and assigns it to FOO.

RUN 'export FOO=$(echo "$(cut -d'=' -f2 <<< $(grep FOO .env))")'

The problem I'm running into is that the script above doesn't return what I need it to. In fact, it doesn't return anything.

When I run docker-compose up --build, it fails with this error.

The command '/bin/sh -c 'export FOO=$(echo "$(cut -d'=' -f2 <<< $(grep FOO .env))")'' returned a non-zero code: 127

I know that the command /bin/sh -c 'echo "$(cut -d'=' -f2 <<< $(grep FOO .env))"' will generate the correct output, but I can't figure out how to assign that output to an environment variable.

Any suggestions on what I'm doing wrong?


Solution

  • Environment Variables

    If you want to set a number of environment variables into your docker image (to be used within the containers) you can simply use env_file configuration option in your docker-compose.yml file. With that option, all the entries in the .env file will be set as the environment variables in image and hence into containers.

    More Info about env_file


    Build ARGS

    If your requirement is to use some variables only within your Dockerfile then you specify them as below

    ARG FOO
    ARG FOO1
    ARG FOO2
    

    etc...

    And you have to specify these arguments under the build key in your docker-compose.yml

    build:
      context: .
      args:
        FOO: BAR
        FOO1: BAR1
        FOO2: BAR2
    

    More info about args


    Accessing .env values within the docker-compose.yml file

    If you are looking into passing some values into your docker-compose file from the .env then you can simply put your .env file same location as the docker-compose.yml file and you can set the configuration values as below;

    ports:
      - "${HOST_PORT}:80"
    

    So, as an example you can set the host port for the service by setting it in your .env file

    Please check this