Search code examples
dockerdockerfileenvironment-variables

How can I export env variables to a Dockerfile?


Objective

I have an env variable script file that looks like:

#!/bin/sh
export FOO="public"
export BAR="private"

I would like to source the env variables to be available when a docker image is being built. I am aware that I can use ARG and ENV with build args, but I have too many Env Variables, and I am afraid that will be a lengthy list.

It's worth mentioning that I only need the env variables to install a specific step in my docker file (will highlight in the Dockerfile below), and do not necessarily want them to be available in the built image after that.

What I have tried so far

I have tried having a script (envs.sh) that export env vars like:

#!/bin/sh
export DOG="woof"
export CAT="meow"

My Docker file looks like:

FROM fishtownanalytics/dbt:0.18.1
# Define working directory
# Load ENV Vars
COPY envs.sh envs.sh
CMD ["sh", "envs.sh"]
# Install packages required
CMD ["sh", "-c", "envs.sh"]
RUN dbt deps # I need to env variables to be available for this step

# Exposing DBT Port
EXPOSE 8081

But that did not seem to work. How can I export env variables as a script to the docker file?


Solution

  • In the general case, you can't set environment variables in a RUN command: each RUN command runs a new shell in a new container, and any environment variables you set there will get lost at the end of that RUN step.

    However, you say you only need the variables at one specific step in your Dockerfile. In that special case, you can run the setup script and the actual command in the same RUN step:

    FROM fishtownanalytics/dbt:0.18.1
    COPY envs.sh envs.sh
    RUN . ./envs.sh \
     && dbt deps
    # Anything that envs.sh `export`ed is lost _after_ the RUN step
    

    (CMD is irrelevant here: it only provides the default command that gets run when you launch a container from the built image, and doesn't have any effect on RUN steps. It also looks like the image declares an ENTRYPOINT so that you can only run dbt subcommands as CMD, not normal shell commands. I also use the standard . to read in a script file instead of source, since not every container has a shell that provides that non-standard extension.)