Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker environmental variables from a file

I am trying to use one Dockerfile for both my production and development. The only difference between the production and development are the environment variables I set. Therefore I would like someway import the environment variables from a file. Before using Docker I would simply do the following

. ./setvars
./main.py

However if change ./main.py with the Docker equivalent

. ./setvars
docker run .... ./main.py

then the variables will be on the host and not accessible from the Docker instance. Of course a quick and dirty hack would be to make a file with

#!/bin/bash
. ./setvars
./main.py

and run that in the instance. That would however be really annoying, since I got lots of scripts I would like to run (with the same environment variables), and would then have to create a extra script for everyone of those.

Are there any other solution to get my environment variables inside docker without using a different Dockerfile and the method I described above?

like image 464
Smarties89 Avatar asked May 13 '16 10:05

Smarties89


People also ask

Can Dockerfile access environment variables?

Dockerfile provides a dedicated variable type ENV to create an environment variable. We can access ENV values during the build, as well as once the container runs.

How do I pass an environment variable in Dockerfile?

If you want to pass variables through the docker-compose process into any of the Dockerfiles present within docker-compose. yml , use the --build-arg parameter for each argument to flow into all of the Dockerfiles.

Where are docker environment variables stored?

It's not stored (in a file) anywhere. It's passed from Docker to the process running in the container.

Does docker use .env file?

The .env file feature only works when you use the docker-compose up command and does not work with docker stack deploy . Both $VARIABLE and ${VARIABLE} syntax are supported.


1 Answers

Your best options is to use either the -e flag, or the --env-file of the docker run command.

  • The -e flag allows you to specify key/value pairs of env variable,
    for example:

    docker run -e ENVIRONMENT=PROD
    

    You can use several time the -e flag to define multiple env
    variables. For example, the docker registry itself is configurable with -e flags, see: https://docs.docker.com/registry/deploying/#running-a-domain-registry

  • The --env-file allow you to specify a file. But each line of the file must be of type VAR=VAL

Full documentation:

https://docs.docker.com/engine/reference/commandline/run/#set-environment-variables-e-env-env-file

like image 174
Christophe Schmitz Avatar answered Oct 19 '22 14:10

Christophe Schmitz