Auto-Restart Node.js Script with Bash


Back to All Posts

Auto-Restarting a Node.js Script Using Bash

Introduction

When running a Node.js application, crashes can happen due to various reasons, such as unhandled exceptions or rate limits. To ensure continuous operation, we can use a simple Bash script that automatically restarts the application whenever it crashes.

Bash Script for Auto-Restart

Below is a Bash script that continuously restarts a Node.js script (filename.js) if it stops running:

#!/bin/bash
while true; do
  echo "Starting..."
  node filename.js
  echo "crashed. Restarting in 5 seconds..."
  sleep 5
done

How It Works

  1. The script runs an infinite loop (while true).
  2. It starts the Node.js application using node filename.js.
  3. If the script crashes, it prints a message and waits for 5 seconds before restarting the application.
  4. The loop continues indefinitely, ensuring that the application is always running.

Making the Script Executable

Before running the script, give it executable permissions:

chmod +x restart.sh

Running the Script in a Screen Session

To run this script in the background and keep it running even after closing the terminal, use screen:

screen -S namescreen bash restart.sh

You can detach from the screen session by pressing CTRL + A, then D. To reattach, use:

screen -r namescreen

Stopping the Script

To stop the script, reattach to the screen session and press CTRL + C, or use the following command:

screen -X -S namescreen quit

This simple Bash script ensures that your Node.js application remains running continuously, even if it crashes. Using screen allows you to manage the process efficiently without worrying about terminal disconnections.

By implementing this method, you can maintain high availability and reduce downtime for your Node.js applications.