Skip to content

Duplicate environment config with pm2 #5974

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
vitaly-t opened this issue Apr 17, 2025 · 1 comment
Open

Duplicate environment config with pm2 #5974

vitaly-t opened this issue Apr 17, 2025 · 1 comment

Comments

@vitaly-t
Copy link

vitaly-t commented Apr 17, 2025

I've been using Node v20, passing it --env-file .env.dev in order to set environment variables.

Now, for some package scripts I need to add pm2 support. I see that pm2 forces me to place environment variables into ecosystem.config.js.

Now I have 2 copies of environment variables, ones to be used by pure NodeJS scripts, and ones used by PM2 scripts. I would think that PM2 should be smarter than that, and let us reuse what NodeJS supports natively, but I haven't been able to find how.

Is there a way to avoid duplication of environment configuration in this scenario? I really do not want to maintain environment config in 2 places because of PM2.

My package scripts now look like this:

    "start": "tsc && node --env-file .env.dev ./src/index.js channel=primary",
    "start-dev": "pm2 start ecosystem.config.js --env dev",
    "start-prod": "pm2 start ecosystem.config.js --env prod",

And so now I have to maintain the same environment variables inside .env.dev file, plus inside ecosystem.config.js file, which isn't good maintenance-wise.

@vitaly-t
Copy link
Author

vitaly-t commented Apr 18, 2025

To resolve this, I had to add my own parser for reading the values.

Now my ecosystem.config.js file looks like this:

const fs = require('node:fs');

function loadConfig(file) {
    const txt = fs.readFileSync(file, 'utf-8');
    const m = txt.match(/(\w+)=(\w*)/g);
    return m.reduce((p, c) => {
        const s = c.split('=');
        return {...p, [s[0]]: s[1]}
    }, {});
}

const env_dev = loadConfig('env/.dev');
const env_prod = loadConfig('env/.prod');

module.exports = {
    apps: [
        {
            name: 'my-app',
            script: './src/index.js',
            args: 'patam1=123',
            watch: true,
            env_dev,
            env_prod
        }
    ]
}

I am hopeful, that PM2 would be able to do something like this automatically, to consume existing .env files and reuse them internally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant