Environment variables from .env are undefined when the app runs under PM2
process.env.DB_HOST is undefined (works with node app.js, not with pm2 start)Short answer
dotenv reads .env from the process's current directory, and it never overwrites a variable that already exists. Under PM2 either rule can go wrong: PM2 may start the app from another directory, the shell or ecosystem file may already set the name, or the env_production block was never selected with --env.
Fix it fast
1Find out which cause you have
Print where the process runs and what it sees. The directory shows whether dotenv can find the file, and the value shows who set it.
console.log(process.cwd(), process.env.DB_HOST);2Match what you see, then jump to its fix
- 1
process.cwd() is not your project folder, and DB_HOST is undefinedPM2 starts the app in a different directory than the one holding .envFix - 2
The value is not undefined, but it is not the one in .envThe variable already exists, so dotenv leaves it aloneFix - 3
Values defined under env_production are undefined; values under env appearThe env_production block exists, but --env was not passedFix
- 1
What does the error look like?
process.env.DB_HOST is undefined (works with node app.js, not with pm2 start)Wrong value in process.env: the .env value is ignored
Cause 1 of 3
PM2 starts the app in a different directory than the one holding .env
1Check
dotenv's default is the .env file in process.cwd(). PM2 launches the app from its cwd setting, so a config file stored elsewhere, or a start command run from another folder, moves it.
// top of app.js
console.log('cwd:', process.cwd());
// then
pm2 logs my-app --lines 5 --nostream2Fix
Set cwd in the ecosystem file, or give dotenv an absolute path so the working directory stops mattering. On Node.js 20.6 and later you can also let Node.js load the file with node_args.
// ecosystem.config.js
module.exports = {
apps: [{
name: 'my-app',
script: './app.js',
cwd: '/srv/my-app',
node_args: '--env-file=.env',
}],
};
// or in app.js
require('dotenv').config({ path: require('path').resolve(__dirname, '.env') });3Verify
Restart from the file and read the log line again.
pm2 start ecosystem.config.js
pm2 logs my-app --lines 5 --nostreamConfirmed by pm2.keymetrics.io
Cause 2 of 3
The variable already exists, so dotenv leaves it alone
1Check
By default dotenv never modifies a variable that is already set. PM2 passes your shell's environment to the app, and the env block of the ecosystem file is applied after that and wins over the shell. Either source can hold an old value.
printenv DB_HOST
grep -n "DB_HOST" ecosystem.config.js2Fix
Remove the stale value from the shell or the env block, or tell dotenv to override.
require('dotenv').config({ override: true });3Verify
The log shows the value from .env.
pm2 restart my-app && pm2 logs my-app --lines 5 --nostreamConfirmed by github.com
Cause 3 of 3
The env_production block exists, but --env was not passed
1Check
PM2 applies env_<name> blocks only when you name them. A plain pm2 start uses env only.
grep -n "env_" ecosystem.config.js2Fix
Start or restart with the environment name.
pm2 start ecosystem.config.js --env production3Verify
The production values show in the app's log output.
pm2 logs my-app --lines 5 --nostreamConfirmed by pm2.keymetrics.io
How do I stop it coming back?
- Set cwd in the ecosystem file for every app.
- Keep one source for each variable: either .env or the ecosystem env block, not both.
- Use the same start command in deploy scripts every time, including --env.
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
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
Loading a .env file into a PM2 ecosystem config fails or gives undefined values
[PM2][ERROR] File ecosystem.config.js malformated
PM2 only passes the env block of the config to your app.
4 causes, each with a fixBack 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 fix