ExpressJS Server Goes Offline Every Night - 502 Bad Gateway ExpressJS Server Goes Offline Every Night - 502 Bad Gateway nginx nginx

ExpressJS Server Goes Offline Every Night - 502 Bad Gateway


I think you should check this github thread, it seems like it could help you.

Basically, after few hours, a Nodejs server stop functioning, and the poor nginx can not forward its requests, as the service listening to the forward port is dead. So it triggers a 502 error.

It was all due to a memory leak, that leads to a massive garbage collection, then to the server to crash. Check your memory consumption, you could have some surprises. And try to debug your app code, a piece (dependency) at the time.

Updated answer:

So, i will add another branch to my question as it seems it has not helped you so far. You could try to get rid of pm2, and use systemd to manage your app life cycle.

Create a service file

sudo vim /lib/systemd/system/appname.service

this is a simple file i used myself for a random ExpressJS app:

[Unit]Description=YourApp Site Server[Service]ExecStart=/home/user/appname/index.jsRestart=alwaysEnvironment=PATH=/usr/bin:/usr/local/binEnvironment=NODE_ENV=productionWorkingDirectory=/home/user/appname[Install]WantedBy=multi-user.target

Note that it will try to restart if it fails somehow Restart=always

Manage it with systemd

Register the new service with:

sudo systemctl daemon-reload

Now start your app from systemd with:

sudo systemctl start appname

from now on you should be able to manage your app life cycle with the usual systemd commands.

You could add stdout and stderr to syslog to understand what you app is doing

StandardOutput=syslogStandardError=syslog

Hope it helps more


You cannot say when exactly NodeJS will crash, or will do big GC, or will stun for other reason.

Easiest way to cover such issues is to do health check and restart an app. This should not be an issue when working with cluster.

Please look at health check module implementation, you may try to use it, or write some simple shell script to do the check