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..?
Asked
Active
Viewed 1.2k times
8
-
http://stackoverflow.com/questions/4018154/node-js-as-a-background-service this will help you . install `npm install -g forever` and run `forever start server.js` – Shubham Batra Dec 28 '15 at 09:22
-
Another approach is to run in screen – slebetman Dec 28 '15 at 09:24
4 Answers
15
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.

nyzm
- 2,787
- 3
- 24
- 30
2
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(...)

Oleg N. Borodin
- 21
- 3
0
For creating true daemons (a process not attached to any tty) you can use one of the several daemon modules available on npm.
A quick search gave me this: https://www.npmjs.com/package/daemon
Interestingly, the module above works using pure javascript and node.js built-in modules without requiring any C extensions. It works by exploiting how child_process
works in newer versions of node (> 0.9).

slebetman
- 109,858
- 19
- 140
- 171
0
- either use PM2/forever & nginx for managing the services well. [RECOMMENDED]
- or you can run by the default OS services. I'm using ubuntu 20.04 amd64 on ec2-t2.micro and everything is preinstall with image.
# TO Run the service on port 80 as deamon thread
sudo PORT=80 nohup node server.js &
#To run the service on 3000 port and point to 80.
PORT=3000 nohup node server.js &
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000
# to kill the process run
ps -ef | grep "node"
kill -9 <pid>

gauravds
- 2,931
- 2
- 28
- 45