Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

docker - 如何将环境变量传递给Docker容器?(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.

(我是Docker的新手,目前尚不清楚如何从容器访问外部数据库。)

Is the best way to hard-code in the connection string?

(硬编码连接字符串的最佳方法是吗?)

# Dockerfile
ENV DATABASE_URL amazon:rds/connection?string
  ask by AJcodez translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(您可以使用-e标志将环境变量传递到您的容器。)

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 = :

(或者,如果您不想在命令行上使用ps等显示该值,那么-e可以从当前环境中提取该值,如果您不带=话就可以从当前环境中提取该值:)

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 :

(如果您有许多环境变量,尤其是要保密的话,可以使用env文件 :)

$ 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.

(--env-file标志将文件名作为参数,并期望每行采用VAR = VAL格式,模仿传递给--env的参数。)

Comment lines need only be prefixed with #

(注释行仅需加#前缀)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...