Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Loading a .env file into a PM2 ecosystem config fails or gives undefined values

ErrorError: Cannot find module 'dotenv'

Short answer

PM2 only passes the env block of the config to your app. A .env file reaches it if the config loads it, and that fails for four reasons: dotenv is not installed, it looks in the wrong folder, an older value wins, or the file is read by the wrong process.

  • Applies to PM2 6, Node.js 22, dotenv 16, Ubuntu 24.04
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    See which variables PM2 really gave the process. If your keys are missing here, the problem is in the config file, not in the app.

    pm2 env 0
  2. 2Match what you see, then jump to its fix

    1. 1Error: Cannot find module 'dotenv' printed by PM2 when it loads the ecosystem filedotenv is not installed where the config file runsFix
    2. 2The .env file exists, but the parsed result is empty or has an error key when PM2 is started from another directorydotenv looks in the wrong folderFix
    3. 3The variable exists but holds an old value, not the one in .envA value already set in the shell wins over the .env fileFix
    4. 4You would rather not load dotenv in the ecosystem file at all, or the app already runs fine with node --env-file=.envLet Node.js read the file with --env-file insteadFix

What does the error look like?

  • Error: Cannot find module 'dotenv'
  • [PM2][ERROR] File ecosystem.config.js malformated
  • process.env.DB_URL is undefined only when started by PM2

Cause 1 of 4

dotenv is not installed where the config file runs

1Check

The ecosystem file is loaded by PM2 from the folder it lives in, so dotenv must be installable from there. Check that the package is in that project.

npm ls dotenv

2Fix

Install dotenv in the project that holds the ecosystem file.

npm install dotenv --save

3Verify

Loading the config prints your variables instead of an error.

node -e "console.log(require('./ecosystem.config.js').apps[0].env)"

Confirmed by github.com

Did this fix it?

Cause 2 of 4

dotenv looks in the wrong folder

1Check

By default dotenv reads .env from the current working directory, which is wherever you ran pm2, not where the ecosystem file sits.

pwd
node -e "console.log(require('dotenv').config())"

2Fix

Give dotenv the path of the file explicitly, built from the ecosystem file's own folder, and pass the parsed values into env.

const path = require("path");
const result = require("dotenv").config({ path: path.join(__dirname, ".env") });
if (result.error) throw result.error;

module.exports = {
  apps: [{
    name: "my-app",
    script: "./server.js",
    env: { ...result.parsed },
  }],
};

3Verify

Start from a different folder and list the environment PM2 stored.

cd / && pm2 start /srv/my-app/ecosystem.config.js
pm2 env 0

Confirmed by github.com

Did this fix it?

Cause 3 of 4

A value already set in the shell wins over the .env file

1Check

dotenv never changes a variable that is already set. PM2 also starts the app with the environment of the shell that ran the PM2 command, and the env block is applied on top of it.

env | grep DB_URL

2Fix

Either unset the stale variable in the shell, or tell dotenv to overwrite it.

require("dotenv").config({ override: true });

3Verify

The value printed by PM2 now matches the .env file.

pm2 env 0 | grep DB_URL

Confirmed by github.com

Did this fix it?

Cause 4 of 4

Let Node.js read the file with --env-file instead

1Check

Node.js 22 can load a .env file itself with the --env-file flag. PM2 passes extra Node.js flags through the node_args field. Node.js throws an error if the file does not exist, so a wrong path is easy to spot.

node --env-file=.env -e "console.log(process.env.DB_URL)"

2Fix

Add the flag to node_args with an absolute path built from the ecosystem file's folder, so it does not depend on where PM2 was started.

const path = require("path");
module.exports = {
  apps: [{
    name: "my-app",
    script: "./server.js",
    node_args: `--env-file=${path.join(__dirname, ".env")}`,
  }],
};

3Verify

Delete and start the app again, so the new Node.js flag takes effect, then read the log.

pm2 delete my-app
pm2 start ecosystem.config.js
pm2 logs my-app --lines 20 --nostream

Confirmed by nodejs.org

Did this fix it?

How do I stop it coming back?

  • Keep one way of loading secrets (dotenv in the ecosystem file, or --env-file), not both.
  • Never commit the .env file; commit a .env.example with the key names only.
  • Use an absolute path built from __dirname, so the result does not depend on the folder you start PM2 from.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.