Dockerfile: how to set env variable from file contents

前端 未结 2 744
遇见更好的自我
遇见更好的自我 2021-02-09 06:59

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,

2条回答
  •  猫巷女王i
    2021-02-09 07:44

    First, the error you're seeing. I suspect there's a "not found" error message not included in the question. If that's the case, then the first issue is that you tried to run an executable that is the full string since you enclosed it in quotes. Rather than trying to run the shell command "export", it is trying to find a binary that is the full string with spaces in it and all. So to work past that error, you'd need to unquote your RUN string:

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

    However, that won't solve your underlying problem. The result of a RUN command is that docker saves the changes to the filesystem as a new layer to the image. Only changes to the filesystem are saved. The shell command you are running changes the shell state, but then that shell exits, the run command returns, and the state of that shell, including environment variables, is gone.

    To solve this for your application, there are two options I can think of:

    Option A: inject build args into your build for all the .env values, and write a script that calls build with the proper --build-arg flag for each variable. Inside the Dockerfile, you'll have two lines for each variable:

    ARG FOO1=default value1
    ARG FOO2=default value2
    ENV FOO1=${FOO1} \
        FOO2=${FOO2}
    

    Option B: inject your .env file and process it with an entrypoint in your container. This entrypoint could run your export command before kicking off the actual application. You'll also need to do this for each RUN command during the build where you need these variables. One shorthand I use for pulling in the file contents to environment variables is:

    set -a && . .env && set +a
    

提交回复
热议问题