Docker Node.js环境variables

我试图在Docker上使用环境variables,只需要on命令。 在Mac / Linux上,我可以简单地运行token=1234 node command.js ,令牌可用作环境variables。 但是,当我这样做与docker泊docker exec $CONTAINER nenv token=123 node command.js我得到unknown command token=123

我不使用节点env,我build议如下:

创buildconfiguration文件夹

把它放在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; 

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

例如:

 { "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');

并在任何时候使用configuration对象您需要:

 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')); }); } }); 

这个例子是更准确的方式来进行基于环境的configuration。 例如:将被添加到.gitignoreconfig.local.jsonconfiguration…

编辑造成的我的愚蠢!

您不能在现有泊坞窗上使用docker设置新的env var。 当你build立它(使用Dockerfile或者docker-compose)或者运行时(使用docker run $CONTAINER -e "name=value" command ),你必须这样做。

即使您只需要从命令中检索某些configuration(在docker run时),也可以简单地通过从节点env( process.env )切换到argv用法来完成。
这样的案例并不less见( docker-compose ),可以用非常简单的方式完成。

npm install yargs --save

docker run或者docker exec运行代码:

docker exec $CONTAINER node command.j --token 123

然后在代码中:

 const argv = require('yargs').argv; ... let boo = do.something(argv.token);