如何从容器访问外部数据库?在连接字符串中硬编码是最好的方法吗?
# Dockerfile
ENV DATABASE_URL amazon:rds/connection?string
如何从容器访问外部数据库?在连接字符串中硬编码是最好的方法吗?
# Dockerfile
ENV DATABASE_URL amazon:rds/connection?string
当前回答
使用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
其他回答
我们也可以使用-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-compose传递多个环境变量,一个环境文件也可以用在docker-compose文件中。
web:
env_file:
- web-variables.env
https://docs.docker.com/compose/environment-variables/#the-env_file-configuration-option
要将环境导入到容器中,可以使用docker-compose中的env_file:。Yaml文件,或者你可以复制。env文件到容器中,然后用扩展库读取。
Python项目
你可以使用python-dotenv包:
pip install python-dotenv
然后在代码中:
import os
from dotenv import load_dotenv
load_dotenv()
SECRET_KEY = os.getenv("MY_SECRET")
去项目
github.com/joho/godotenv包:
go get github.com/joho/godotenv
在你的代码中:
package main
import (
"github.com/joho/godotenv"
"log"
"os"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
secretKey := os.Getenv("MY_SECRET")
}
你可以在docker run ..这里提到的和勘误表中提到的命令。
然而,这种方法可能存在的缺点是,您的凭据将显示在您运行它的进程列表中。
为了让它更安全,你可以把你的凭证写在一个配置文件中,并像这里提到的那样使用——env-file运行docker。然后,您可以控制对该配置文件的访问,以便其他有权访问该机器的人不会看到您的凭据。
下面是我解决这个问题的方法:
docker run --rm -ti -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_SESSION_TOKEN -e AWS_SECURITY_TOKEN amazon/aws-cli s3 ls
再举一个例子:
export VAR1=value1
export VAR2=value2
docker run --env VAR1 --env VAR2 ubuntu env | grep VAR
输出:
VAR1=value1
VAR2=value2