如何将环境变量传递给Docker容器? [英] How do I pass environment variables to Docker containers?
问题描述
我是Docker的新手,目前还不清楚如何从容器访问外部数据库。是连接字符串中最好的硬编码方式吗?
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
或者,如果您不想在命令行上具有该值它将由 ps
显示等等, -e
可以从当前环境中提取值,如果您只是在没有 =
的情况下提供该值:
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
--env-file标志将一个文件名作为参数,并期望每行都是VAR = VAL格式,模仿参数传递给--env。评论行只需要加上#
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 #
这篇关于如何将环境变量传递给Docker容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!