Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run node js server as a daemon process?

Tags:

linux

node.js

I am using Ionic framework and nodejs for one app. All nodejs files are in linux server. I am starting the nodejs server using 'npm start &' command through putty. But the problem is if I close putty the server is getting stopped after sometime. I tried 'nohup npm start &'. But still I am facing the same issue. How to start this as a daemon process..?

like image 973
Santhosh Aineri Avatar asked Dec 28 '15 09:12

Santhosh Aineri


People also ask

How do I run a process as a daemon?

To create a daemon, you need a background process whose parent process is init. In the code above, _daemon creates a child process and then kills the parent process. In this case, your new process will be a subprocess of init and will continue to run in the background.

How do I run a node js app as a background service?

Method 1: The easiest method to make a node. js app run as a background service is to use the forever tool. The forever is a simple Command Line Interface Tool that ensures that a given particular script runs continuously without any interaction.

How do I run a node js server?

The usual way to run a Node. js program is to run the globally available node command (once you install Node. js) and pass the name of the file you want to execute. While running the command, make sure you are in the same directory which contains the app.


2 Answers

You can use pm2 for production.

To install pm2 :

npm install pm2 -g

To start an application simply just run :

pm2 start app.js

You can check logs via:

pm2 logs

For more options just checkout their readme files on github repo.

like image 165
nyzm Avatar answered Oct 06 '22 02:10

nyzm


This is adaptation of daemon module:

const child_process = require('child_process')

function child(exe, args, env) {
    const child = child_process.spawn(exe, args, { 
        detached: true,
        stdio: ['ignore', 'ignore', 'ignore'],
        env: env
    })
    child.unref()
    return child
}

module.exports = function(nodeBin) {
    console.log('Daemonize process')

    if (process.env.__daemon) {
        return process.pid
    }
    process.env.__daemon = true

    var args = [].concat(process.argv)
    var node = args.shift()
    var env = process.env
    child(node, args, env)
    return process.exit()
}

Usage:

const daemon = require('daemon')
daemon()

app.listen(...)

https://wiki.unix7.org/node/daemon-sample

like image 36
Oleg N. Borodin Avatar answered Oct 06 '22 02:10

Oleg N. Borodin