如何从容器访问外部数据库?在连接字符串中硬编码是最好的方法吗?
# Dockerfile
ENV DATABASE_URL amazon:rds/connection?string
如何从容器访问外部数据库?在连接字符串中硬编码是最好的方法吗?
# Dockerfile
ENV DATABASE_URL amazon:rds/connection?string
当前回答
有一个很好的方法可以将主机环境变量输送到Docker容器中:
env > env_file && docker run --env-file env_file image_name
要非常小心地使用这种技术,因为env > env_file会将所有主机env变量转储到env_file中,并使它们在运行的容器中可访问。
其他回答
您可以使用-e或——env作为参数,后面跟着键-值格式。
例如:
docker build -f file_name -e MYSQL_ROOT_PASSWORD=root
要将环境导入到容器中,可以使用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")
}
运行——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_')将抓取所有文件并安全地传递给容器内的用户。
如果您在本地的env.sh中有环境变量,并且希望在容器启动时设置它,您可以尝试
COPY env.sh /env.sh
COPY <filename>.jar /<filename>.jar
ENTRYPOINT ["/bin/bash" , "-c", "source /env.sh && printenv && java -jar /<filename>.jar"]
该命令将使用bash shell启动容器(我想使用bash shell,因为source是bash命令),获取env.sh文件(设置环境变量)并执行jar文件。
env.sh是这样的,
#!/bin/bash
export FOO="BAR"
export DB_NAME="DATABASE_NAME"
我添加printenv命令只是为了测试实际的源命令是否有效。您应该在确认源命令正常工作时删除它,否则环境变量将出现在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