node dotenv won't work with pm2

dotenv will read .env file located in the current directory.

When you call pm2 start myapp/app.js it won't search for myapp/.env.

.env // It will try to load this, which doesn't exist
myapp/
   app.js

So you have two solutions

use path option:

const path = require('path'); 
require('dotenv').config({ path: path.join(__dirname, '.env') });

Or call your script from inside myapp/

pm2 start app.js

A good pattern here is to remove dotenv from your code and "require" it on the command line. This makes your code nicely transportable between any environment (including cloud-based) - which is one of the main features of environment variables.

Note: you will still need to install dotenv in your project via npm when running it on a server.

a) code up your .env file alongside your script (e.g. app.js)

b) to run your script without pm2:

node -r dotenv/config app.js

c) in pm2.config.js:

module.exports = {
  apps : [{
    name      : 'My Application',
    script    : 'app.js',
    node_args : '-r dotenv/config',
    ...
  }],
}

and then pm2 start pm2.config.js

note: the use of dotenv/config on the command line is one of the best practices recommended by dotenv themselves


you have kill you pm2 process first

try

pm2 kill

then restart pm2 using

pm2 start app.js