如何从容器访问外部数据库?在连接字符串中硬编码是最好的方法吗?

# Dockerfile
ENV DATABASE_URL amazon:rds/connection?string

当前回答

你可以在docker run ..这里提到的和勘误表中提到的命令。

然而,这种方法可能存在的缺点是,您的凭据将显示在您运行它的进程列表中。

为了让它更安全,你可以把你的凭证写在一个配置文件中,并像这里提到的那样使用——env-file运行docker。然后,您可以控制对该配置文件的访问,以便其他有权访问该机器的人不会看到您的凭据。

其他回答

我们也可以使用-e标志和$来使用主机环境变量:

在执行以下命令之前,需要导出(即设置)本地环境变量。

docker run -it -e MG_HOST=$MG_HOST \
    -e MG_USER=$MG_USER \
    -e MG_PASS=$MG_PASS \
    -e MG_AUTH=$MG_AUTH \
    -e MG_DB=$MG_DB \
    -t image_tag_name_and_version

通过使用此方法,您可以使用给定的名称自动设置环境变量。在我的例子中,MG_HOST和MG_USER。

另外:

如果你正在使用Python,你可以通过以下方式访问Docker内部的这些环境变量:

import os

host = os.environ.get('MG_HOST')
username = os.environ.get('MG_USER')
password = os.environ.get('MG_PASS')
auth = os.environ.get('MG_AUTH')
database = os.environ.get('MG_DB')

你可以在docker run ..这里提到的和勘误表中提到的命令。

然而,这种方法可能存在的缺点是,您的凭据将显示在您运行它的进程列表中。

为了让它更安全,你可以把你的凭证写在一个配置文件中,并像这里提到的那样使用——env-file运行docker。然后,您可以控制对该配置文件的访问,以便其他有权访问该机器的人不会看到您的凭据。

使用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

运行——rm -it——env-file <(bash -c 'env | grep <你的env数据>') 是一种grep存储在.env中的数据并将它们传递给Docker的方法,没有任何不安全的存储(所以你不能只查看Docker历史并获取密钥)。

假设你的。env中有很多AWS的东西,就像这样:

AWS_ACCESS_KEY: xxxxxxx
AWS_SECRET: xxxxxx
AWS_REGION: xxxxxx

使用docker run——rm -it——env-file <(bash -c 'env | grep AWS_')将抓取所有文件并安全地传递给容器内的用户。

您可以使用-e或——env作为参数,后面跟着键-值格式。

例如:

docker build -f file_name -e MYSQL_ROOT_PASSWORD=root