How to programmatically pass env variables
I want to start app programmatically and pass some env variables, how to do that ?
Sorry for asking question here but I have looked at the source and can't figure that out
Like this? What env variables are you talking about?
system environment variable
for example process.env.PORT
pm2.start('app.js', {PORT: 1337, NODE_ENV: 'production' ...}, function() {
});
This might work:
export NODE_ENV=production node my-app.js
But env variables are not part of the app and it's not supported by the programmatic api. You might also try to pass them to the application args:
pm2.start('app.js', {args: {PORT: 1337, NODE_ENV: 'production'}, instances: 'max'}, function() {
});
I'm gonna add the env attributes so you can set that.
For now you do:
process.env.NODE_ENV = 'production';
process.env.PORT = 6546;
pm2.connect(function() {
pm2.start('app.js', {}, function() {
pm2.disconnect(function() {});
});
});
Both approach are hacky but for now I will use @Unitech approach because I don't need to change existing application
Thanks
For the record, @Unitech solution is, IIUC, achieved in the startup JSON file using the "env" property:
{
"name" : ....,
"script" : .....,
"args" : ....,
"env" :
{
"PATH" : .....,
"NODE_PATH" : .....,
...
}
}
Indeed you should be able to start a json declaration programmatically with this like @ravi states.
You can now:
pm2.start('app.js', { env: {PORT: 1337, NODE_ENV: 'production'}, instances: 'max'}, function() {
});
via 0.10.2
Thanks @Unitech
It doesn't look like the underlying issue of not being able to pass the parent environment as-is to the worker processes (at least in clustered mode) has been resolved. While in main.js I can call pm2.start() with settings added to env, and those do show up in worker app.js, what if I have unset certain vars in the parent environment which I don't want in the worker?
For example, I define, by default, http_proxy in my .bash_profile, but I also have handy bash functions proxyon/proxyoff that set and unset that and all proxy related variables in my current environment. If I unset http_proxy, I expect that not to appear in the worker process, but that's not what I'm seeing. I can verify in main.js that process.env does not contain http_proxy, and I've even called pm2.start() with {env: process.env}, but, again, that seems only to have an additive effect.
The expected behavior in the worker is to inherit the parent environment exactly, plus any additional vars explicitly passed in the env hash to pm2.start(). I know pm2 litters the worker scope with tons of state data without adequate "pm2_" prefixes to avoid collision, but that's a separate issue.
PM2 docs can help you: http://pm2.keymetrics.io/docs/usage/pm2-doc-single-page/