且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将环境变量传递给 Docker 容器?

更新时间:2022-10-31 08:06:03

您可以使用 -e 标志将环境变量传递给您的容器.

来自启动脚本的示例:

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 容器名称 dockerhub_id/image_name

或者,如果您不想在命令行中将值显示在 ps 等处,-e 可以拉入如果你只是在没有 = 的情况下给它当前环境的值:

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

如果你有很多环境变量,特别是如果它们是秘密的,你可以使用环境文件:

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

--env-file 标志将文件名作为参数,并期望每一行采用 VAR=VAL 格式,模仿传递给 --env 的参数.注释行只需要以 #

为前缀

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

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 #