305

On a Debian server, I installed Node.js. I understand how to launch an app from putty with this command line:

node /srv/www/MyUserAccount/server/server.js

and get to it on the address 50.51.52.53:8080 (IP and port).

But as soon as I close putty, then I cannot reach the address 50.51.52.53:8080 anymore.

How to make a Node.js application run permanently?

As you can guess, I am a beginner with Linux and Node.js.

vqdave
  • 2,361
  • 1
  • 18
  • 36
Sam
  • 3,479
  • 4
  • 17
  • 17
  • 9
    Note that [pm2](https://github.com/Unitech/pm2) is a good alternative to [Forever](https://github.com/nodejitsu/forever), if you didn't want to use Forever for whatever reason. – Kevin B Oct 15 '14 at 20:20
  • thanks @KevinB https://github.com/Unitech/pm2 is really good alternative – Sachin Chavan Jul 25 '17 at 20:48
  • Possible duplicate of [How do I run a node.js app as a background service?](https://stackoverflow.com/questions/4018154/how-do-i-run-a-node-js-app-as-a-background-service) – mikemaccana May 03 '18 at 11:21

20 Answers20

394

You could install forever using npm like this:

sudo npm install -g forever

And then start your application with:

forever server.js

Or as a service:

forever start server.js

Forever restarts your app when it crashes or stops for some reason. To restrict restarts to 5 you could use:

forever -m5 server.js

To list all running processes:

forever list

Note the integer in the brackets and use it as following to stop a process:

forever stop 0

Restarting a running process goes:

forever restart 0

If you're working on your application file, you can use the -w parameter to restart automatically whenever your server.js file changes:

forever -w server.js
Mohd_PH
  • 1,590
  • 12
  • 19
N20
  • 3,989
  • 2
  • 11
  • 2
  • 13
    @MarthaJames if its closing when your ssh session / window closes, then you likely forgot to include "start" in the `forever start ` – Kristian Aug 21 '15 at 22:55
  • 8
    What's the difference between using `forever server.js` and `forever start server.js`? I know it says it's "as a service" but what does that mean? – M - Feb 29 '16 at 20:57
  • 8
    When I type in `forever server.js`, it starts the server. If I press `Ctrl` + `C`, it then stops the service. If I type in `forever start server.js` then it starts the service and even if I press `Ctrl` + `C` it stays open. You can then do the other referenced commands above to stop / look at the list. That's what I experienced at least. – Termato Apr 19 '16 at 18:49
  • If you are using express, you have to run using `forever start ./bin/www` instead. – Eranda Sep 22 '16 at 04:27
  • 7
    Does this start the script after a server restart? – beingalex Nov 02 '16 at 08:43
  • Maybe this will help someone... I also had to ensure that I had "normal" shell instead of jailed shell, or the process would be killed when I closed my SSH session. – sethasaurus Jun 19 '17 at 15:15
  • 4
    The `forever` module (v0.15.3) is vulnerable to Regular Expression Denial of Service attacks and shouldn't be used: https://github.com/foreverjs/forever/issues/960 – Benny Code Oct 19 '17 at 20:31
  • I tried `forever index.js` and the application stopped when I did `Ctrl+c`. I then tried `forever index.js &` and it worked even after exiting the ssh. – Doug Mar 12 '18 at 09:50
  • 1
    None of these commands kept the server running after I killed the SSH session. – Andrew Koster Nov 26 '18 at 17:06
  • npm rm -g forever for removing it – DragonFire May 20 '20 at 01:08
  • ... or just redirect output properly instead of downloading a bunch of crappy middleware – Krusty the Clown Apr 01 '23 at 20:02
264

Although the other answers solve the OP's problem, they are all overkill and do not explain why he or she is experiencing this issue.

The key is this line, "I close putty, then I cannot reach the address"

When you are logged into your remote host on Putty you have started an SSH linux process and all commands typed from that SSH session will be executed as children of said process.

Your problem is that when you close Putty you are exiting the SSH session which kills that process and any active child processes. When you close putty you inadvertently kill your server because you ran it in the foreground. To avoid this behavior run the server in the background by appending & to your command:

node /srv/www/MyUserAccount/server/server.js &

The problem here is a lack of linux knowledge and not a question about node. For some more info check out: http://linuxconfig.org/understanding-foreground-and-background-linux-processes

UPDATE:

As others have mentioned, the node server may still die when exiting the terminal. A common gotcha I have come across is that even though the node process is running in bg, it's stdout and stderr is still pointed at the terminal. This means that if the node server writes to console.log or console.error it will receive a broken pipe error and crash. This can be avoided by piping the output of your process:

node /srv/www/MyUserAccount/server/server.js > stdout.txt 2> stderr.txt &

If the problem persists then you should look into things like tmux or nohup, which are still more robust than node specific solutions, because they can be used to run all types of processes (databases, logging services, other languages).

A common mistake that could cause the server to exit is that after running the nohup node your_path/server.js & you simply close the Putty terminal by a simple click. You should use exit command instead, then your node server will be up and running.

Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
  • 9
    If you still close the Putty Session while doing `&` the service still closes though. (Just tested on Debian Jesse) – NiCk Newman Sep 12 '15 at 02:50
  • I've experienced this with certain complex commands that confuse the shells command parser which then neglects the bg command. For those situations use something like tmux, which is still superiors to a node specific solution because it is OS level (useful if starting processes outside of node like a db or separate service): http://askubuntu.com/questions/8653/how-to-keep-processes-running-after-ending-ssh-session –  Oct 08 '15 at 18:11
  • 1
    As @NiCkNewman said, this answer is incomplete! See [Rick Roy's answer](http://stackoverflow.com/a/33360288/4376460) for the correct solution. – thejonwithnoh Oct 28 '15 at 01:28
  • 21
    The "&" makes the process run in the background but you would actually need to add "nohup" to the beginning of this command to detach it from the console window so that the application would not stop when the window goes to sleep after a few hours, modifying the previously mentioned command to: `nohup node /srv/www/MyUserAccount/server/server.js &` – SirRodge Feb 14 '16 at 06:32
  • Thanks to last update (with > stdout.txt 2> stderr.txt) - it works! – dod_basim Aug 26 '16 at 13:31
  • You could also use Upstart or Systemd I believe – JREAM Mar 24 '17 at 03:23
  • 2
    AIX powersystem, `nohup node myApp.js &` ran the app in the bg but it dies when the term was closed. Not sure why though. – Anjan Biswas Apr 04 '17 at 04:46
  • Hi, i used this method to start my node module. Now i need to restart it. How do i kill the previous process? – Sydney Oct 01 '17 at 02:31
  • 4
    @Annjawn, you have to use `exit` command to exit the terminal. – Ionut Necula Mar 01 '18 at 15:07
  • Then, how to stop the running server in the normal and reasonable way after using 'node /srv/www/MyUserAccount/server/server.js &' ? – KoreanXcodeWorker Mar 04 '18 at 16:23
  • i was closing the putty directly, it was causing problem. After using exit commnad, it works for me and now my server is running in background too. – Joginder Malik Dec 15 '20 at 15:54
110

You can use PM2, it's a production process manager for Node.js applications with a built-in load balancer.

Install PM2

$ npm install pm2 -g

Start an application

$ pm2 start app.js

If you using express then you can start your app like

pm2 start ./bin/www --name="app"

Listing all running processes:

$ pm2 list

It will list all process. You can then stop / restart your service by using ID or Name of the app with following command.

$ pm2 stop all                  
$ pm2 stop 0                    
$ pm2 restart all               

To display logs

$ pm2 logs ['all'|app_name|app_id]
Vikash Rajpurohit
  • 1,525
  • 2
  • 13
  • 13
44

I'd recommend looking for something such as Forever to restart Node in the event of a crash, and handle daemonizing this for you.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • I would like to point out that without `nohup`, node will exit when you exit the ssh session if you run it this way (unless you are using something like screen to tmux). – Haozhun Mar 25 '13 at 14:55
  • 1
    @Haozhun, Interesting, but that isn't how it has been working for me on my machines. When I ssh in and start something using this command, it runs forever in the background, even after closing the SSH session. – Brad Mar 25 '13 at 16:38
  • @Brad Please see the 2nd answer on http://stackoverflow.com/questions/4018154/node-js-as-a-background-service . It appears quite some people agree with the 1st comment of that question which explains `nohup`. It would be great if we can resolve this confusion. But I don't know where to start. – Haozhun Mar 26 '13 at 02:34
  • @Haozhun, The answers change order randomly. Can you link directly to the answer? I don't see any confusion there. You should post a new question, if you have questions. – Brad Mar 26 '13 at 02:51
  • 4
    For most unixen (including most distros of Linux), running things in the background will still kill the process if you close the terminal window. To prevent this run it with `nohup`. Example: `nohup node app.js &` – slebetman Sep 26 '13 at 04:01
  • 1
    I use Forever with a production Linux env. I typically use the command forever start --minUptime 10000 -o /logs/myapp.log nodeApp.js – mbokil Mar 10 '16 at 19:44
42

If you just want to run your node app in the terminal always, just use screen.

Install on ubuntu/ debian:

sudo apt-get install screen

Usage:

$ screen
$ node /path/to/app.js

ctrl + a and then ctrl + d to dismiss

To get is back:

One screen: screen -r

If there's more than one you can list all the screens with: screen -ls

And then: screen -r pid_number

film42
  • 1,095
  • 12
  • 22
32

You could simply use this

nohup node /srv/www/MyUserAccount/server/server.js &

This will keep the application running and to shut it down you will have to kill it.

For that you could install htop and then search for node and then kill it

Rick Roy
  • 1,656
  • 2
  • 21
  • 47
  • 23
    It's important to note that in this case, the user would need to exit from the PuTTY session properly (i.e. via the `exit` command). If the user simply closes the window, this may use a signal other than `SIGHUP` to end the process, and therefore node would shutdown anyway. – thejonwithnoh Oct 28 '15 at 01:19
  • 1
    +1 for being a simple all purpose Linux solution to the problem though. This is better than [DogNibbler's answer](http://stackoverflow.com/a/32029341/4376460). – thejonwithnoh Oct 28 '15 at 01:24
  • @thejonwithnoh after reading your comment I have tried with abruptly closing putty but the server still worked, maybe it had to do with how the env was configured. But I figured for what the OP was asking this would be simplest way to achieve it – Rick Roy Oct 30 '15 at 16:24
  • I like this simple approach, it's the one I'm using, as for killing it, the easiest is just a `killall node` , which will kill all node processes, in my case only one. – Nelson Mar 14 '17 at 19:51
  • @Nelson That would kill all node processes what if you have multiple scripts running and only want to terminate one specific one, I would suggest you find the process and then terminate that particular one just in case you had multiple node processes running in a production server and dont want to feel like getting into a nightmare :D – Rick Roy Mar 16 '17 at 07:23
13

Forever is a very good NodeJs module to do exactly that.

Install forever by typing in the command line

$ npm install forever -g

Then use the following command to run a node.js script

$ forever start /path/to/script.js

You are good to go. Additionally you can run

$ forever list

to see all the running scripts. You can terminate any specific script by typing

$ forever stop [pid]

where [pid] is the process ID of the script you will obtain from the list command. To stop all scripts, you may type

$ forever stopall
13

Installation

$ [sudo] npm install forever -g

You can use forever to run scripts continuously

forever start server.js

forever list

for stop service

forever stop server.js
Sudhir Singh
  • 817
  • 11
  • 16
12

During development, I recommend using nodemon. It will restart your server whenever a file changes. As others have pointed out, Forever is an option but in production, it all depends on the platform you are using. You will typically want to use the operating system's recommended way of keeping services up (e.g. http://www.freedesktop.org/wiki/Software/systemd/).

Olivier Lalonde
  • 19,423
  • 28
  • 76
  • 91
  • This worked for me on a MEAN.JS application -- `nodemon` runs the grunt command unless you specify a server JS file, so I'm using this to run mongo and node forever/simultaneously – J-Dizzle Feb 01 '16 at 17:58
11

nohup working i checked in AWS Ubunto vm follow the correct syntax

ubuntu@ip-172-00-00-00:~/ms$ nohup node server.js &

then press enter you will see this line

ubuntu@ip-172-00-00-00:~/ms$ nohup: ignoring input and appending output to ‘nohup.out’

then type this

rm nohup.out

enter image description here

Adiii
  • 54,482
  • 7
  • 145
  • 148
  • 7
    I like how you blanked out the hostname in the small bash prompt, but left it in the big title of the window – conny Mar 31 '17 at 10:57
10

Here's an upstart solution I've been using for my personal projects:

Place it in /etc/init/node_app_daemon.conf:

description "Node.js Daemon"
author      "Adam Eberlin"

stop on shutdown

respawn
respawn limit 3 15

script
  export APP_HOME="/srv/www/MyUserAccount/server"
  cd $APP_HOME
  exec sudo -u user /usr/bin/node server.js
end script

This will also handle respawning your application in the event that it crashes. It will give up attempts to respawn your application if it crashes 3 or more times in less than 15 seconds.

Adam Eberlin
  • 14,005
  • 5
  • 37
  • 49
10

First install pm2 globally

npm install -g pm2

then start

pm2 start bin/www 
Vinayak Shedgeri
  • 2,222
  • 1
  • 21
  • 24
10

No need to install any other package.

Run this command

node server.js > stdout.txt 2> stderr.txt &

server.js is your server file or it can be api.js

After that hit "exit" to close terminal

exit
Gajender Singh
  • 1,285
  • 14
  • 13
  • It worked when i removed the `&` from the end of the command. but this is a good answer. I am wondered if this solution could really be replaced by `pm2` package. – Ali Nov 19 '21 at 20:08
  • Thanks to you i'm going to bed early today. – Rodrigo Burgos Jan 06 '23 at 05:22
9

I’ve found forever to do the job perfectly fine.

Assuming you already have npm installed, if not, just do

sudo apt-get install npm

Then install forever

npm install forever --global

Now you can run it like this

forever start app.js

https://codingweb.io/run-nodejs-application-background/

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
erax
  • 119
  • 1
  • 3
7

Another way is creating a system unit for your app. create a "XXX.service" file in "/etc/systemd/system" folder, similar to this:

[Unit]
Description=swagger
After=network.target

[Service]
ExecStart=/usr/bin/http-server /home/swagger/swagger-editor &
WorkingDirectory=/home/swagger
Restart=always
RestartSec=30

[Install]
WantedBy=multi-user.target

A benefit is the app will run as a service, it automatically restarts if it crashed.

You can also use sytemctl to manage it:

systemctl start XXX to start the service, systemctl stop XXX to stop it and systemctl enable XXX to automatically start the app when system boots.

Alex
  • 1,692
  • 13
  • 10
6

Try pm2 to make your application run forever.

npm install -g pm2

and then use

pm2 start server.js

to list and stop apps, use commnds

pm2 list

pm2 stop 0

Muhammad Athar
  • 109
  • 1
  • 4
  • Thank you sir. This is wonderful what you do for the community. Looks like now we can list, stop and start our valuable node.js apps. Didn't know it, I have just learned it ! Thanks ! – Thanasis Jun 08 '21 at 06:09
5

I hope this will help you.

At the command line, install forever:

npm install forever -g

Create an example file:

sudo nano server.js 

You can edit the file and get results directly in your browser.
You can use filezilla or any editor to edit the file. Run this command to run the file:

forever start --minUptime 1 --spinSleepTime 1000 -w server.js

enter image description here

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Ghanshyam Nakiya
  • 1,602
  • 17
  • 24
3

forever package worked for me, just one thing, it depends on deep-equal, so if you had issue with installing it like:

npm -g install forever

Try:

npm -g install forever deep-equal@1.1.1

instead.

Alireza
  • 100,211
  • 27
  • 269
  • 172
3

As we know that there are many options to do this. Here is a pure Shell solution, with no need for extra programs / packages.

This solution will restart server.js if it crashes for some reason / errors.

Let's say this is a run.sh:

#!/usr/bin/env sh

while :; do
    node server.js

    echo "Restarting..."
    sleep 1
done

Make sure to make the run.sh file executable:

chmod +x run.sh

And to run it:

./run.sh

If you want to run it in the background:

./run.sh &

Run in the background super-silently (detached, without any output):

( ./run.sh > /dev/null 2>&1 & )
nggit
  • 611
  • 8
  • 8
  • Great and pure answer! Good idea not for only node.js. – Markus Zeller Aug 13 '22 at 10:31
  • Using it with `npm run serve` command keeps running `npm run serve`, every moment. Instead of running once and only running again in case of error – parsecer Nov 07 '22 at 15:52
  • @parsecer How do you do it? This is not meant to run npm commands, but is run by npm commands. Here's an example `npm run start`: https://github.com/nggit/node-docker-router – nggit Nov 07 '22 at 16:19
2

I recommend use PM2, which is a process manager for Node.js applications. PM2 provides an easy way to manage and daemonize applications (run them as a service).

refer this link - https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-centos-7

vishwajit76
  • 2,300
  • 20
  • 16
  • 1
    There's already an answer recommending PM2. https://stackoverflow.com/a/40254977/390718 – hopia Aug 11 '17 at 17:21