98

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).

How do you daemonize a node.js server so that it can run even after the current session is closed?

Strider
  • 3,539
  • 5
  • 32
  • 60
Jerome WAGNER
  • 21,986
  • 8
  • 62
  • 77

9 Answers9

99

Forever is answer to your question.

Install

$ curl https://npmjs.org/install.sh | sh
$ npm install forever
# Or to install as a terminal command everywhere:
$ npm install -g forever

Usage

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();
Alexander Otavka
  • 948
  • 1
  • 7
  • 10
Baggz
  • 17,207
  • 4
  • 37
  • 25
  • 7
    Should use -g option to install globally. Might need permissions to do so. – refaelio May 20 '14 at 07:20
  • 1
    what happens when you reboot? –  Dec 12 '14 at 17:55
  • 1
    @AlexBrown - you'll need to add the `forever start server.js` to a startup script (e.g. `rc.local`), if you want it to survive reboots. – UpTheCreek Mar 18 '15 at 12:54
  • 3
    I eventually settled on using monit to start and stop the forever process. –  Mar 29 '15 at 04:04
  • 13
    forever is dead, pm2 is the new king. Please dont waste your time on forever. I've just switched and i'm blown away. pm2 can load balance your app on all cores with a simple .. pm2 start app.js -i 0 --name "myapp" ... WOW ... try it and you won't forever look back ... see @Gary Bernitz answer – danday74 Jan 29 '17 at 02:28
48

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.

Budleigh
  • 505
  • 4
  • 2
41

To start a systemd service manager daemon, write a service file. For example, create a file /etc/systemd/system/myservice.service.

If your server.js script is shebanged (#!/usr/bin/env node on the first line) and the system can find node on the path, this works:

[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

Or, if you don't shebang the file, consider adding the absolute path to the node executable that you want to use and prepend that to the ExecStart= attribute of the service file.

...
ExecStart=/root/.nvm/versions/node/v16.15.1/bin/node ...
...

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
activedecay
  • 10,129
  • 5
  • 47
  • 71
24

UPDATE: i updated to include the latest from pm2:

for many use cases, using a systemd service is the simplest and most appropriate way to manage a node process. for those that are running numerous node processes or independently-running node microservices in a single environment, pm2 is a more full featured tool.

https://github.com/unitech/pm2

http://pm2.io

  • it has a really useful monitoring feature -> pretty 'gui' for command line monitoring of multiple processes with pm2 monit or process list with pm2 list
  • organized Log management -> pm2 logs
  • other stuff:
    • Behavior configuration
    • Source map support
    • PaaS Compatible
    • Watch & Reload
    • Module System
    • Max memory reload
    • Cluster Mode
    • Hot reload
    • Development workflow
    • Startup Scripts
    • Auto completion
    • Deployment workflow
    • Keymetrics monitoring
    • API
Hutch
  • 10,392
  • 1
  • 22
  • 18
  • 4
    forever is dead, pm2 is king! I've been using forever since forever but just made the switch to pm2. WOW! WOW! WOW! forever runs your app on 1 core, pm2 can do the same OR it can load balance your app on all available cores. WOW! no need for @reboot cron jobs, just do pm2 startup (to start pm2 as a systemd or OS equivalent service) and then pm2 save. now reboot and your apps are still running. You can get the status of a running app with pm2 show. watch is readily available. WOW! unbelievable WOW! – danday74 Jan 29 '17 at 02:24
  • 1
    Setting up pm2 for non-root user in openshift is too much pain. – karthik101 Jul 16 '18 at 14:22
18

The simplest approach would just to send the command to the background.

$ node server.js &

Then you can kill the process at a later time. I usually do the following:

$ killall node

Note: I'm running OS X.

raidfive
  • 6,603
  • 1
  • 35
  • 32
  • 57
    Note that this will not work if you log out of your terminal/ssh session. The full solution for that is nohup node server.js >/dev/null 2>&1 & – Michael Dillon Feb 21 '11 at 05:58
  • 1
    @MichaelDillon Why do you think redirecting outputs to `/dev/null` should be included in the full solution? – nurettin Sep 26 '18 at 08:59
11

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.

Lane
  • 4,682
  • 1
  • 36
  • 20
3

There are more advanced general-purpose runners, such as monit and runit.

nponeccop
  • 13,527
  • 1
  • 44
  • 106
0

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.

jgmjgm
  • 4,240
  • 1
  • 25
  • 18
0

2022 - PM2

There is a better and one of the most popular solutions for that and it's called pm2 (npm package link).

To run one or multiple Node.js servers you need to install it: npm install pm2 -g

To run: pm2 start app.js

To stop: pm2 stop nameOfAppFromList


You can also list your running apps pm2 list

To check logs of a specific one, run pm2 logs nameOfAppFromList

GlKosh
  • 67
  • 6