如何从容器访问外部数据库?在连接字符串中硬编码是最好的方法吗?
# Dockerfile
ENV DATABASE_URL amazon:rds/connection?string
如何从容器访问外部数据库?在连接字符串中硬编码是最好的方法吗?
# Dockerfile
ENV DATABASE_URL amazon:rds/connection?string
当前回答
如果你使用“Docker -compose”作为旋转容器的方法,实际上有一种有用的方法可以将服务器上定义的环境变量传递给Docker容器。
在你码头式的写作中。Yml文件,让我们说你正在旋转一个基本的happi -js容器,代码看起来像:
hapi_server:
container_name: hapi_server
image: node_image
expose:
- "3000"
假设你的docker项目所在的本地服务器有一个名为“NODE_DB_CONNECT”的环境变量,你想把它传递给你的hapi-js容器,你想让它的新名称为“HAPI_DB_CONNECT”。然后在docker-compose。Yml文件中,你可以将本地环境变量传递给容器,并像这样重命名它:
hapi_server:
container_name: hapi_server
image: node_image
environment:
- HAPI_DB_CONNECT=${NODE_DB_CONNECT}
expose:
- "3000"
我希望这能帮助您避免在容器中的任何文件中硬编码数据库连接字符串!
其他回答
为了通过docker-compose传递多个环境变量,一个环境文件也可以用在docker-compose文件中。
web:
env_file:
- web-variables.env
https://docs.docker.com/compose/environment-variables/#the-env_file-configuration-option
对于Amazon AWS ECS/ECR,您应该通过私有S3桶管理您的环境变量(特别是秘密变量)。请参阅如何使用Amazon S3和Docker管理基于Amazon EC2容器服务的应用程序的机密。
使用jq将环境转换为JSON:
env_as_json=`jq -c -n env`
docker run -e HOST_ENV="$env_as_json" <image>
这需要jq 1.6或更新版本。
这将主机环境作为一个JSON文件,本质上就像Dockerfile中的那样:
ENV HOST_ENV (all environment from the host as JSON)
使用docker-compose,你可以在docker-compose中继承env变量。yml和docker-compose调用的任何Dockerfile来构建映像。当Dockerfile RUN命令应该执行特定于环境的命令时,这很有用。
(您的shell已经在环境中存在RAILS_ENV=development)
docker-compose.yml:
version: '3.1'
services:
my-service:
build:
#$RAILS_ENV is referencing the shell environment RAILS_ENV variable
#and passing it to the Dockerfile ARG RAILS_ENV
#the syntax below ensures that the RAILS_ENV arg will default to
#production if empty.
#note that is dockerfile: is not specified it assumes file name: Dockerfile
context: .
args:
- RAILS_ENV=${RAILS_ENV:-production}
environment:
- RAILS_ENV=${RAILS_ENV:-production}
Dockerfile:
FROM ruby:2.3.4
#give ARG RAILS_ENV a default value = production
ARG RAILS_ENV=production
#assign the $RAILS_ENV arg to the RAILS_ENV ENV so that it can be accessed
#by the subsequent RUN call within the container
ENV RAILS_ENV $RAILS_ENV
#the subsequent RUN call accesses the RAILS_ENV ENV variable within the container
RUN if [ "$RAILS_ENV" = "production" ] ; then echo "production env"; else echo "non-production env: $RAILS_ENV"; fi
这样,我就不需要在文件或docker-compose build/up命令中指定环境变量:
docker-compose build
docker-compose up
有一个很好的方法可以将主机环境变量输送到Docker容器中:
env > env_file && docker run --env-file env_file image_name
要非常小心地使用这种技术,因为env > env_file会将所有主机env变量转储到env_file中,并使它们在运行的容器中可访问。