Skip to main content

Running a Node.js application in the background

Method 1: Using nohup

nohup stands for ‘no hang up’ and allows the process to continue running after you log out from the shell.
  • nohup: Command to run the process immune to hangups.
  • node index.js: Your Node.js application entry point.
  • &: Runs the process in the background.

Method 2: Using screen

screen is a terminal multiplexer that allows you to run multiple terminal sessions from a single SSH session.
  1. Start a new screen session:
  2. Run your Node.js application:
  3. Detach from the screen session by pressing Ctrl + A, then D.
  4. To reattach to the session later:

Method 3: Using tmux

tmux is another terminal multiplexer, similar to screen.
  1. Start a new tmux session:
  2. Run your Node.js application:
  3. Detach from the tmux session by pressing Ctrl + B, then D.
  4. To reattach to the session later:

Method 4: Using pm2

pm2 is a process manager specifically designed for Node.js applications.
  1. Install pm2 globally:
  2. Start your Node.js application with pm2:
  3. To list all running applications:
  4. To save the process list and resurrect them on reboot:
This method ensures that your application will restart automatically if it crashes and can be configured to start on server reboot.

Method 5: Using Systemd

Create a systemd service file to manage your Node.js application.
  1. Create a new service file for your application:
  2. Add the following content to the service file:
  3. Reload systemd to apply the new service:
  4. Start your service:
  5. Enable the service to start on boot:

Summary

Each method has its own advantages:
  • nohup is simple and easy.
  • screen and tmux are great for interactive processes.
  • pm2 offers advanced features for managing and monitoring Node.js applications.
  • systemd integrates well with the system’s init process and is robust for production environments.
Choose the method that best fits your needs and the environment where your application will run.