2

Im looking for an elegant way to import env variables to container from a file, trying to avoid hardcoding them in Dockerfile.

#my_file.txt

VAR1=123
VAR2=345
...

I know that this is possible with:

docker run --env-file my_file.txt some_ubuntu_image

but I'm looking for a way to declare this in Dockerfile rather than in run command. Something like:

RUN export -r my_file.txt

or

ENV -r my_file.txt

this ofc does not work, but I hope it gives some image what Im looking for.

wiktor
  • 73
  • 2
  • 8
  • Does this answer your question? [How to use environment variables in docker compose](https://stackoverflow.com/questions/29377853/how-to-use-environment-variables-in-docker-compose) – Ken Y-N Jun 16 '21 at 08:02
  • @KenY-N not exactly, Im looking for a way to declare env's from Dockerfile, not docker-compose :/ – wiktor Jun 16 '21 at 08:04
  • Note that the accepted answer in the Dup is now out of date - please refer to [this answer instead](https://stackoverflow.com/a/50201232/1270789), for instance. – Ken Y-N Jun 16 '21 at 08:05

1 Answers1

0

I've found a way to do this:

CMD export $(xargs < my_file.txt)

Ofc this may be dangerous workaround, but it works!

wiktor
  • 73
  • 2
  • 8
  • That `CMD` will set all of the environment variables from the file, and then since it's complete the container will exit. Is there more that needs to be done to set the environment variables and then launch the main container process? – David Maze Jun 16 '21 at 10:46
  • 1
    just do `CMD export $(xargs < my_file.txt) && ` ex. for a python script in `script.py`: `CMD export $(xargs < my_file.txt) && python script.py` – wiktor Jun 16 '21 at 12:06