How To Run Node JS Server In Background

When you use Node JS to implement an HTTP / HTTPS web server, you always follow the general steps as below. But if you close the terminal or kill the node process unexpectedly, the HTTP web server will stop also. This article will tell you how to avoid such an issue and make the node HTTP web server continuously running in the background even it is stopped.

1. General Steps To Run Node HTTP Web Server.

  1. Create a js file that will start an HTTP web server on a special port.
    http_server.js

    // Include http module.
    var http = require('http');
    
    // Create http server.
    var httpServer = http.createServer(function (req, resp) {
    
        resp.writeHead(200, {'Access-Control-Allow-Origin':'*','Content-Type': 'text/plain'});
        resp.write("Welcome to dev2qa.com.");
        resp.end();
    });
    
    // Start http server listen on port 8888.
    httpServer.listen(8888);
    
    console.log("Use browser to get url 'http://localhost:8888/http_server.js'");
  2. Open a terminal and run the below command to start the HTTP web server.
    sh-3.2# node http_server.js
    Use browser to get url 'http://localhost:8888/http_server.js'
    
  3. Open a web browser and browse URL http://localhost:8888/http_server.js, then you can get below web page that means the HTTP web server has been started successfully.
    node-js-http-web-server-page
  4. Run ps -ef|grep node command in terminal, you can see there are two processes in the list, one is the ps command the other is the node http web server process.
     192:~ zhaosong$ ps -ef|grep node
        0  4166  3516   0 12:33PM ttys000    0:00.22 node http_server.js
       501 4226  4213   0 12:39PM ttys003    0:00.01 grep node
    

2. Run Node In Background With Nohup Command.

In the above method, the Node JS server will always occupy the terminal until the terminal is closed. But when you close the terminal, the Node JS server will also stop. To fix this issue, you can start the Node JS server with nohup command as below.

sh-3.2# nohup node http_server.js > output.log &
[1] 4327
sh-3.2# ps -ef|grep node
    0  4327  3516   0 12:52PM ttys000    0:00.19 node http_server.js
    0  4329  3516   0 12:52PM ttys000    0:00.01 grep node

The nohup command will run a command in background, in this case, it will start the Node JS HTTP web server in background and display the node server process id. All the server-side output will be saved in output.log file. Excellent, but when the node process is killed unnormal ( $ kill 4327 ), the HTTP server stops also.

3. Run Node In Background Continuously Use Node Forever Package.

Forever is a Node JS package that can make a node script execute forever even after the node script process is killed. It will execute the node js script in a new process when the old process has been stopped suddenly. To use the node forever package, follow below steps.

  1. Install Node forever package. Below command will install the forever package globally.
    sh-3.2# npm install forever -g
  2. After installation, run npm list command to see the forever package installation path. Generally npm package is installed in /usr/local/lib/node_modules folder.
    sh-3.2# npm list forever -g
    /usr/local/lib
    └── [email protected]
    
  3. Start node js HTTP web server with forever start command. From the below output message, you can see first forever start the HTTP web server in process with id 4854, after you kill that process, forever start another process ( id is 4872 ) to run the node HTTP web server immediately. So the HTTP web server will run in background continuously.
    sh-3.2# forever start http_server.js
    ......
    info:    Forever processing file: http_server.js
    sh-3.2# ps -ef|grep node
        0  4853     1   0  2:51PM ??         0:00.36 /usr/local/bin/node /usr/local/lib/node_modules/forever/bin/monitor http_server.js
        0  4854  4853   0  2:51PM ??         0:00.10 /usr/local/bin/node /Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/NodeJSWorkspace/RunScriptForever/http_server.js
        0  4857  3516   0  2:51PM ttys000    0:00.00 grep node
    
    sh-3.2# kill 4854
    sh-3.2# ps -ef|grep node
        0    1   0  2:51PM ??         0:00.37 /usr/local/bin/node /usr/local/lib/node_modules/forever/bin/monitor http_server.js
        0  4872 4853   0  2:53PM ??         0:00.12 /usr/local/bin/node /Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/NodeJSWorkspace/RunScriptForever/http_server.js
        0  4874  3516   0  2:53PM ttys000    0:00.00 grep node
    
    
  4. You can use # forever list command to list all forever running processes.
  5. # forever stop command can stop the running node script.
    sh-3.2# forever stop http_server.js
  6. For more information about forever, you can refer to it’s official website

4. Run Node In Background Use Linux Systemd.

  1. If you run the node js app in Linux OS, you can use this method.
  2. All the Linux OS contains the systemd daemon which is running in the background when Linux OS startup.
  3. First, go to /etc/systemd/system directory and create a node-app-service-name.service file in this directory.
  4. Edit the node-app-service-name.service file in vim, add the below content in it.
    [Unit]
    Description=Run my node js app in background
    
    [Service]
    
    # This is your node js app file saved location. It will be executed in background when system startup.
    ExecStart=/var/www/node-app/my-node-app.js
    
    Restart=always
    User=nobody
    
    # For RHEL/Fedora Linux OS uses 'nobody', for Debian/Ubuntu Linux OS uses 'nogroup', 
    Group=nogroup
    
    Environment=PATH=/usr/bin:/usr/local/bin
    
    Environment=NODE_ENV=production
    
    WorkingDirectory=/var/www/my-node-app
    
    [Install]
    WantedBy=multi-user.target
  5. Edit the /var/www/node-app/my-node-app.js file in vim, add text #!/usr/bin/env node at the beginning of the file content.
  6. Run command chmod +x /var/www/node-app/my-node-app.js to add execute permission to the target node js app file.
  7. Run command systemctl daemon-reload in a terminal to let systemd load the new service ( node-app-service-name.service ) which you just add.
  8. Run command systemctl start node-app-service-name to start the service, the node-app-service-name is the service file name as above.
  9. If you want to run node in background every time when the Linux OS startup, you can run the command systemctl enable node-app-service-name in a terminal to achieve this.
  10. If you want to see the above node js systemd service execution logs you can run the command journalctl -u node-app-service-name.

5. Run Node In Background Use NPM Package PM2.

  1. PM2 is a process manager, monitor tool. It basic version is open source and free and enough to use.
  2. PM2 has a built-in load balancer which allow the node js app keep alive forever without downtime even the server restart.
  3. PM2 is platform-independent, it can run on both Linux, Windows & macOS.
  4. Run the command npm install pm2 -g in a terminal to install PM2 globally.
  5. If you did not install Node js on your server, you can run the command wget -qO- https://getpm2.com/install.sh | bash to install it.
  6. Run the command pm2 start node-js-app.js to start the node js application as a daemon service. Of course pm2 start can also be used to start any app ( written in python, java, etc) as a daemon servive.
  7. The pm2 command provides several options for you to manage the processes, such as pm2 list, pm2 stop, pm2 restart, pm2 delete.
  8. The pm2 monit command can be used to monitor logs.
  9. For more information, you can visit the pm2 official website.
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x