Passing environment variables to node.js using pm2

I am trying to pass some arguments to my Express application which is run by pm2. There wasn’t any hint in their documentation to do so, but apparently it’s possible to pass some EV to your node application like SOME_STUFF=xxx pm2 start app.js.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Note – after updating environment variables in your environment, you must do the following:

pm2 restart all --update-env

ask me how I know…

Edit: also look for a .env file in the node source directory…

Solution 2

It’s actually possible and I’m pretty sure it was in PM2’s documentation some time ago.

Anyways, that’s what you need to do:

pm2 start app.js -- -some_stuff xxx

Basically, add -- and then you can add your own app parameters.

Managed to find the source, it was hidden quite well: http://pm2.keymetrics.io/docs/usage/quick-start/#42-ways-of-starting-processes

Solution 3

I was having issues passing parameters using pm2 start app.js -- -some_stuff xxx so I opted to do this instead: SOME_STUFF=xxx OTHER_STUFF=abc pm2 start app.js.

Then when I ran pm2 logs I was able to see that my app successfully started and that the environment variables were set correctly where as before I was seeing errors around these variables when I ran pm2 logs.

Solution 4

The environment variables don’t always update unless you force them to.

SOME_STUFF=xxx pm2 start app.js --update-env

Solution 5

You should pass ENV in ecosystem.config.js

ecosystem.config.js (in the root)

module.exports = {
  apps: [
    {
      name: "project-name",
      exec_mode: "cluster",
      instances: "1",
      script: "./server/index.js", // your script
      args: "start",
      env: {
        NODE_ENV: "production", 
        SOME_ENV: "some_value"...
      },
    },
  ],
};

In the console:

pm2 run ecosystem.config.js

There is information about configuration of ENV in PM2 official documentation

Solution 6

My node app (sveltekit build) starts in my ubuntu server when I use

node build/index.js

and includes enviroment variables

so with pm2 I found that my app starts with envs starting it:

pm2 "node build/index.js"

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply