Loading a .env file into a PM2 ecosystem config fails or gives undefined values
Error: 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.
Fix it fast
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 02Match what you see, then jump to its fix
- 1
Error: Cannot find module 'dotenv' printed by PM2 when it loads the ecosystem filedotenv is not installed where the config file runsFix - 2
The .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
The variable exists but holds an old value, not the one in .envA value already set in the shell wins over the .env fileFix - 4
You 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
- 1
What does the error look like?
Error: Cannot find module 'dotenv'[PM2][ERROR] File ecosystem.config.js malformatedprocess.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 dotenv2Fix
Install dotenv in the project that holds the ecosystem file.
npm install dotenv --save3Verify
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
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 0Confirmed by github.com
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_URL2Fix
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_URLConfirmed by github.com
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 --nostreamConfirmed by nodejs.org
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:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
Related fixes
Back end
PM2 keeps the old environment variables after restart --update-env
the app still prints the old value after pm2 restart
A plain pm2 restart reuses the environment stored at first start.
4 causes, each with a fixBack end
Node.js cannot start because the port is already taken
Error: listen EADDRINUSE: address already in use 127.0.0.1:8080
EADDRINUSE means another socket already listens on that port, so Node's listen() was refused.
4 causes, each with a fixBack end
process.env.NODE_ENV is undefined in a Node.js app
console.log(process.env.NODE_ENV) prints undefined
Node.js does not set NODE_ENV for you.
5 causes, each with a fixBack end
PM2 does not restart my Node.js app after it crashes
status stopped in pm2 list
PM2 restarts a crashed process on its own, so a process that stays down has a reason.
3 causes, each with a fixBack end
PM2 says the ecosystem file is malformated and refuses to start
Error [ERR_REQUIRE_ASYNC_MODULE]
PM2 prints 'malformated' whenever loading the config file throws.
3 causes, each with a fixBack end
Application Load Balancer returns 502 for a Node.js target
HTTPCode_ELB_502_Count
An ALB returns 502 when the target gives it something it cannot use: a refused or reset connection, a connection closed mid-request, a bad response, or a header over 32 K.
4 causes, each with a fix