[英]How to pass env variable to a json file when executing the docker run command
I'm executing below docker run command to run my nodejs based docker container我正在执行 docker 运行命令以运行基于 nodejs 的 docker 容器
docker run -p 8080:7000 --env db_url=10.155.30.13 automation:v1.0.3
And i'm trying to access this env variable by using separate config file from my container.我正在尝试通过使用我的容器中的单独配置文件来访问这个环境变量。 config file is in json format as below.配置文件为 json 格式,如下所示。
{
"db_host": "${process.env.db_url}",
}
And in my nodejs code, i'm accessing this db_host value to add the host IP to the listener.在我的 nodejs 代码中,我正在访问这个 db_host 值以将主机 IP 添加到侦听器。 But when the above code executed, the docker container is brings down as soon as it brought up.但是当执行上述代码时,docker 容器一启动就被关闭。 But if i replace the json file value as below, it is working fine and my container is listening as below.但是,如果我替换 json 文件值如下,它工作正常并且我的容器正在监听如下。 Could someone please help me to pass the value and to access it within my json file?有人可以帮我传递值并在我的 json 文件中访问它吗?
{
"db_host": "10.155.30.13",
}
You can get value in app您可以在应用程序中获得价值
const db_host = process.env.db_url || "10.155.30.13"
instead of reading it from json file.而不是从 json 文件中读取它。
You can not substitute environment variable in JSON file, you can use dotenv or config that will help to have some default value in the config file and override these value from environment variables.您不能在 JSON 文件中替换环境变量,您可以使用dotenv或config在配置文件中设置一些默认值并从环境变量中覆盖这些值。
create default config vi config/default.json
创建默认配置vi config/default.json
{
"db_host": "10.155.30.13"
}
now read from ENV first, else pick the default value from config app.js现在首先从 ENV 读取,否则从 config app.js 中选择默认值
const config = require('config');
const dbConfig = process.env.DB_HOST || config.get('db_host');
console.log(dbConfig)
Now run the docker container现在运行 docker 容器
build the container构建容器
docker build -t app .
run the container运行容器
docker run -it app
console output控制台 output
10.155.30.13
Now we want to override this default values现在我们要覆盖这个默认值
docker run -e DB_HOST=192.168.0.1 -it app
console output控制台 output
192.168.0.1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.