Smarties89
Smarties89

Reputation: 561

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?

Upvotes: 12

Views: 4769

Answers (1)

Christophe Schmitz
Christophe Schmitz

Reputation: 2996

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

Upvotes: 17

Related Questions