Search code examples
node.jswebsocketshared-hostingpusher

Is there a way to automatically restart nodejs app after a 503 error?


My nodejs app keeps getting 503 resource exceed error every few weeks after running so I need to keep restarting it via ssh. I was wondering if there is something I can install to automatically restart it whenever I get an error or it crashes.

I have checked our A2Hosting server's number of processes during the error but it just says 0/50.

I am using pusher real time.

const express = require("express");
const router = express.Router();

const Pusher = require("pusher");

var pusher = new Pusher({
  appId: "xxxxxx",
  key: "xxxxxxxxxxxxxxxxxx",
  secret: "xxxxxxxxxxxxxxx",
  cluster: "ap1",
  encrypted: true
});

router.post("/", (req, res) => {
  const newVote = {
    id: req.body.id,
    points: 1
  };

  pusher.trigger("scan", "scan-player", {
    id: req.body.id,
    player_id: req.body.player_id,
    admin_id: req.body.admin_id
  });

  return res.json({
    success: true,
    message: "Scan successful!",
    id: req.body.id
   });
});

module.exports = router;

Solution

  • An error should not get your app to crash, you should handle it and just log the error message. For example, with express error handler, see : error handling patterns with express

    Also, if your app crash, some programs can restart it automatically. The most basic one is forever :

    forever start app.js
    

    It restarts your app when it crashes. But the best one in my opinion is pm2 :

    pm2 start app.js
    

    It does the same, but has a lot of additional functionalities, like load balancing, deployment system, log managment

    Hope it helps,
    Best regards