Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PM2 environment variables caching

I am running PM2 on Ubuntu 16.04 and it seems that environment variables are being cached somehow. Is there an way of seeing which environment variables PM2 are using. The environment variables it can somehow see are not available in my terminal session anymore echo $VAR_NAME.

I created the environment variables like this:

export VAR_NAME=value

Removing the environment variable using:

unset VAR_NAME

doesn't work PM2 is stubbornly holding on to the environment variable - even after various restart & ssh sessions. Render me confused :-/

Is there a way of flushing the environment variables PM2 is using? Or at least seeing which environment variables it knows about?

like image 944
André Vermeulen Avatar asked Sep 29 '16 20:09

André Vermeulen


1 Answers

Update to the original answer:

If the environment variables' values are preset, as in the case of having different env variables for development, staging, and production, there is an option using a process.json file.

The below is a sample for a node.js app:

{
  "apps" : [{
    "env": { 
     // in this section you would list variables that you 
     // want available in all cases
      "NODE_PATH": "..."
    },
    "env_development": {
      "CONFIG": "dev.conf.json",
      "NODE_ENV": "development"
    },
    "env_production" : {
       "CONFIG": "conf.json",
       "NODE_ENV": "production"
    },
    "exec_mode": "fork", // or cluster if that's what you want
    "name"        : "my_app",
    "script"      : "/var/my_app/app.js", //srcipt's path
    "watch"       : false // don't restart on file changes
  }]
}

Having this file defined, with the possible values for env, you can switch environment by restarting the app as follows:

  1. Start the app normally: pm2 start process.json --env development

  2. When you want to switch to a different env: pm2 restart process.json --env production

For more about process.json and the possible options: PM2 - Process File


Original answer:

You have to kill pm2 first.

pm2 kill

pm2 start app.js

PM2 preserves the environment variables it read upon starting, it does not reread their values every time.

I searched for it quickly, and found this issue on github: https://github.com/Unitech/pm2/issues/83, and Unitech's answers confirm this.

In this particular comment: https://github.com/Unitech/pm2/issues/83#issuecomment-29837221

Unitech says:

Yep this is normal in "cluster_mode". As pm2 wrap your code to his own context (and own variables) you get what was already there when launching pm2.

like image 57
Omar A Avatar answered Oct 20 '22 11:10

Omar A