In Python Twisted, you have the twistd
command that helps you with a number of things related to running your application (daemonize it for example).
Ho
If you need your process to daemonize itself, not relaying on forever - you can use the daemonize module.
$ npm install daemonize2
Then just write your server file as in example:
var daemon = require("daemonize2").setup({
main: "app.js",
name: "sampleapp",
pidfile: "sampleapp.pid"
});
switch (process.argv[2]) {
case "start":
daemon.start();
break;
case "stop":
daemon.stop();
break;
default:
console.log("Usage: [start|stop]");
}
Mind you, that's rather a low level approach.
To start a systemd
service manager daemon, write a service file. For example, create a file /etc/systemd/system/myservice.service
.
[Unit]
Description=myservice-description
After=network.target
[Service]
ExecStart=/opt/myservice-location/src/node/server.js --args=here
Restart=always
User=me
Group=group
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/opt/myservice-location
[Install]
WantedBy=multi-user.target
Remember to update the service manager daemon after every change to the myservice.service file.
$ systemctl daemon-reload
Then start the service running and enable the service to start at boot.
$ systemctl start myservice
$ systemctl enable myservice
For the background on the normal way to daemonise on a POSIX system you can search for the C method.
I have not seen enough methods in the node.js API to allow it to be done the C way by hand. However, when using child_process, you can have node.js do it for you:
http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options
I consider this a potential waste of time because there's a good chance your system provides the same.
For example:
http://libslack.org/daemon/manpages/daemon.1.html
If you want something portable (cross platform) the other posts offer solutions that might suffice.
There are more advanced general-purpose runners, such as monit
and runit
.
You can try:
$ nohup node server.js &
It work for me on Mac and Linux.
The output will be in the ./nohup.out
file
But I still recommend you use pm2
or forever
, because they are easily used for restarting, stopping and logging.
Forever is answer to your question.
$ curl https://npmjs.org/install.sh | sh
$ npm install forever
# Or to install as a terminal command everywhere:
$ npm install -g forever
Using Forever from the command line
$ forever start server.js
Using an instance of Forever from Node.js
var forever = require('forever');
var child = new forever.Forever('your-filename.js', {
max: 3,
silent: true,
args: []
});
child.on('exit', this.callback);
child.start();