How to require dotenv/config file on (before) PM2 starts
Asked Answered
K

3

3

I run node app like this:

node -r dotenv/config dist/app

I need something similar using PM2:

pm2 start -r dotenv/config dist/app.js --name appname // doesn't work

I receive the next error: error: unknown option -r

Kordofan answered 1/7, 2019 at 8:15 Comment(1)
chekout npmjs.com/package/dotenv you can load the .env files from the script itselfBo
V
11

Using node_args.

pm2 start --node-args="-r dotenv/config" dist/app.js --name appname
Villagomez answered 1/7, 2019 at 9:22 Comment(1)
This! Finally. Working on ubuntu 20 / node 10 / pm2 5.2.0Deianira
K
0

I have made a Shell script:

// pm2-start.sh

NODE_ENV=production &&
node -r dotenv/config dist/app

Then I ran pm2 start pm2-start.sh --name appname

Tip I have also ran: pm2 startup then copied command that pm2 instructed to run in order to activate the auto startup of all apps that are registered via pm2.

Then I ran pm2 save to save the auto service.

Note: pm2 lists apps distinctly between server account respectively. That means that apps that are listed on user A will not be listed on user B. That's true for the pm2 startup command - that should be done for each account.

Hope it helps.

Kordofan answered 1/7, 2019 at 8:37 Comment(0)
O
0

None of this worked for me because I was using an ecosystem file AND cluster mode which behaves really odd (not like without cluster mode...).

I installed dotenv as dev dependency at the root (I was using yarn workspaces too).

Then I did this:

require('dotenv').config({ path: 'path/to/your/.env' })

module.exports = {
    apps: [
        {
            name: 'app',
            script: 'server/dist/index.js',
            instances: 2,
            exec_mode: 'cluster',
            instance_var: 'APP_INSTANCE_SEQ',
            // listen_timeout: 10000,
            // restart_delay: 10000,
        }
    ]
}

Ovary answered 8/8, 2021 at 16:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.