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.
-
Start a new screen session:
-
Run your Node.js application:
-
Detach from the screen session by pressing
Ctrl + A, thenD. -
To reattach to the session later:
Method 3: Using tmux
tmux is another terminal multiplexer, similar to screen.
-
Start a new
tmuxsession: -
Run your Node.js application:
-
Detach from the
tmuxsession by pressingCtrl + B, thenD. -
To reattach to the session later:
Method 4: Using pm2
pm2 is a process manager specifically designed for Node.js applications.
-
Install
pm2globally: -
Start your Node.js application with
pm2: -
To list all running applications:
-
To save the process list and resurrect them on reboot:
Method 5: Using Systemd
Create a systemd service file to manage your Node.js application.-
Create a new service file for your application:
-
Add the following content to the service file:
-
Reload systemd to apply the new service:
-
Start your service:
-
Enable the service to start on boot:
Summary
Each method has its own advantages:nohupis simple and easy.screenandtmuxare great for interactive processes.pm2offers advanced features for managing and monitoring Node.js applications.systemdintegrates well with the system’s init process and is robust for production environments.
