I connect to the linux server via putty SSH. I tried to run it as a background process like this:
$ node server.js &
However, after 2.5 hrs the terminal becomes inactive and the process dies. Is there anyway that I can keep the process alive even the terminal disconnected?
Actually, I tried
nohup, but as soon as I close the Putty SSH terminal or unplug my internet, the server process stops right away.
Is there anything I have to do in Putty?
Edit 2 (on Feb, 2012)
There is a
node.js module, forever. It will run node.js server as daemon service.
This is an old question, but is high ranked on Google. I almost can't believe on the highest voted answers, because running a node.js process inside a screen session, with the
& or even with the
nohup flag -- all of them -- are just workarounds.
Specially the screen/tmux solution, which should really be considered an amateur solution. Screen and Tmux are not meant to keep processes running, but for multiplexing terminal sessions. It's fine, when you are running a script on your server and want to disconnect. But for a node.js server your don't want your process to be attached to a terminal session. This is too fragile. To keep things running you need to daemonize the process!
There are plenty of good tools to do that.
# basic usage $ npm install pm2 -g $ pm2 start server.js # you can even define how many processes you want in cluster mode: $ pm2 start server.js -i 4 # you can start various processes, with complex startup settings # using an ecosystem.json file (with env variables, custom args, etc): $ pm2 start ecosystem.json
One big advantage I see in favor of PM2 is that it can generate the system startup script to make the process persist between restarts:
$ pm2 startup [platform]
platform can be
# basic usage $ npm install forever -g $ forever start app.js # you can run from a json configuration as well, for # more complex environments or multi-apps $ forever start development.json
I'm not go into detail about how to write a init script, because I'm not an expert in this subject and it'd be too long for this answer, but basically they are simple shell scripts, triggered by OS events. You can read more about this here
Just run your server in a Docker container with
-d option and, voilá, you have a daemonized node.js server!
Here is a sample Dockerfile (from node.js official guide):
FROM node:argon # Create app directory RUN mkdir -p /usr/src/app WORKDIR /usr/src/app # Install app dependencies COPY package.json /usr/src/app/ RUN npm install # Bundle app source COPY . /usr/src/app EXPOSE 8080 CMD [ "npm", "start" ]
Then build your image and run your container:
$ docker build -t <your username>/node-web-app . $ docker run -p 49160:8080 -d <your username>/node-web-app
Hope this helps somebody landing on this page. Always use the proper tool for the job. It'll save you a lot of headaches and over hours!