Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass environment variables to Docker containers?

I'm new to Docker, and it's unclear how to access an external database from a container. Is the best way to hard-code in the connection string?

# Dockerfile ENV DATABASE_URL amazon:rds/connection?string 
like image 917
AJcodez Avatar asked May 27 '15 22:05

AJcodez


People also ask

Does docker have access to environment variables?

By default, the environment variables present on the host machine are not passed on to the Docker container. The reason is that the Docker container is supposed to be isolated from the host environment. So, if we want to use an environment within the Docker container, then we have to set it explicitly.

How do you pass an environment variable?

In the User variables section, select the environment variable you want to modify. Click Edit to open the Edit User Variable dialog box. Change the value of the variable and click OK. The variable is updated in the User variables section of the Environment Variables dialog box.

How do I set an environment variable on an existing container?

To set an environment variable you should use flag -e while using docker run or docker-compose command. Environment file - If the environment variable is not overridden by docker-compose. yml, shell environment the variable then the environment file will get the precedence.


1 Answers

You can pass environment variables to your containers with the -e flag.

An example from a startup script:

sudo docker run -d -t -i -e REDIS_NAMESPACE='staging' \  -e POSTGRES_ENV_POSTGRES_PASSWORD='foo' \ -e POSTGRES_ENV_POSTGRES_USER='bar' \ -e POSTGRES_ENV_DB_NAME='mysite_staging' \ -e POSTGRES_PORT_5432_TCP_ADDR='docker-db-1.hidden.us-east-1.rds.amazonaws.com' \ -e SITE_URL='staging.mysite.com' \ -p 80:80 \ --link redis:redis \   --name container_name dockerhub_id/image_name 

Or, if you don't want to have the value on the command-line where it will be displayed by ps, etc., -e can pull in the value from the current environment if you just give it without the =:

sudo PASSWORD='foo' docker run  [...] -e PASSWORD [...] 

If you have many environment variables and especially if they're meant to be secret, you can use an env-file:

$ docker run --env-file ./env.list ubuntu bash 

The --env-file flag takes a filename as an argument and expects each line to be in the VAR=VAL format, mimicking the argument passed to --env. Comment lines need only be prefixed with #

like image 90
errata Avatar answered Sep 19 '22 22:09

errata