gpt4 book ai didi

node.js - Docker Node.js 环境变量

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:39 29 4
gpt4 key购买 nike

我正在尝试在 docker 上使用仅命令所需的环境变量。在 Mac/Linux 上,我可以简单地运行 token=1234 node command.js 并且 token 可以作为环境变量使用。但是当我使用 docker docker exec $CONTAINER nenv token=123 node command.js 执行此操作时,我得到 unknown command token=123

最佳答案

我不使用 Node 环境,我建议执行以下操作:

创建config文件夹

将其放入config/index.js

var
nconf = require('nconf'),
path = require('path');

nconf.env().argv();

nconf.file('local', path.join(__dirname, 'config.local.json'));
nconf.file(path.join(__dirname, 'config.json'));

module.exports = nconf;

创建文件:config/config.json(配置模板)和config/config.local.json(具有真实配置的模板副本)

例如:

{
"app": {
"useCluster": false,
"http": {
"enabled": true,
"port": 8000,
"host": "0.0.0.0"
},
"https": {
"enabled": false,
"port": 443,
"host": "0.0.0.0",
"certificate": {
"key": "server.key",
"cert": "server.crt"
}
},
"env": "production",
"profiler": false
},
"db": {
"driver": "mysql",
"host": "address here",
"port": 3306,
"user": "username here",
"pass": "password here",
"name": "database name here"
},
}

在应用程序开头使用:var config = require('./config');

并在需要时使用config对象:

var config = require('./config'),
cluster = require('./components/cluster'),
http = require('http'),
...
...
https = require('https');

cluster.start(function() {
if (config.get('app:http:enabled')) {
var httpServer = http.createServer(app);
httpServer.listen(config.get('app:http:port'), config.get('app:http:host'),
function () {
winston.info('App listening at http://%s:%s', config.get('app:http:host'), config.get('app:http:port'));
});
}

if (config.get('app:https:enabled')) {
var httpsServer = https.createServer({
key: fs.readFileSync(path.join(__dirname, 'certificates', config.get('app:https:certificate:key'))),
cert: fs.readFileSync(path.join(__dirname, 'certificates', config.get('app:https:certificate:cert')))
}, app);
httpsServer.listen(config.get('app:https:port'), config.get('app:https:host'),
function () {
winston.info('App listening at https://%s:%s', config.get('app:https:host'), config.get('app:https:port'));
});
}
});

此示例是基于环境的配置的更准确方法。例如: config.local.json 配置将添加到 .gitignore 等等...

关于node.js - Docker Node.js 环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36427231/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com