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 node index.js &
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:
screen -S my-node-app
-
Run your Node.js application:
node index.js
-
Detach from the screen session by pressing
Ctrl + A
, thenD
. -
To reattach to the session later:
screen -r my-node-app
Method 3: Using tmux
tmux
is another terminal multiplexer, similar to screen
.
-
Start a new
tmux
session:tmux new -s my-node-app
-
Run your Node.js application:
node index.js
-
Detach from the
tmux
session by pressingCtrl + B
, thenD
. -
To reattach to the session later:
tmux attach -t my-node-app
Method 4: Using pm2
pm2
is a process manager specifically designed for Node.js applications.
-
Install
pm2
globally:npm install -g pm2
-
Start your Node.js application with
pm2
:pm2 start index.js
-
To list all running applications:
pm2 list
-
To save the process list and resurrect them on reboot:
pm2 save pm2 startup
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.
-
Create a new service file for your application:
sudo nano /etc/systemd/system/my-node-app.service
-
Add the following content to the service file:
[Unit] Description=My Node.js Application After=network.target [Service] ExecStart=/usr/bin/node /path/to/your/index.js Restart=always User=your-username Group=your-groupname Environment=PATH=/usr/bin:/usr/local/bin Environment=NODE_ENV=production WorkingDirectory=/path/to/your/application [Install] WantedBy=multi-user.target
-
Reload systemd to apply the new service:
sudo systemctl daemon-reload
-
Start your service:
sudo systemctl start my-node-app
-
Enable the service to start on boot:
sudo systemctl enable my-node-app
Summary
Each method has its own advantages:
nohup
is simple and easy.screen
andtmux
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.