csdnceshi58
Didn"t forge
2011-01-25 17:53
采纳率: 25%
浏览 757

如何将 Node.js 作为后台进程运行并永远保持下去?

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 I can keep the process alive even with the terminal disconnected?


Edit 1

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.

转载于:https://stackoverflow.com/questions/4797050/how-to-run-node-js-as-a-background-process-and-never-die

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

14条回答 默认 最新

  • csdnceshi57
    perhaps? 2011-01-25 17:55
    已采纳

    Simple solution (if you are not interested in coming back to the process, just want it to keep running):

    nohup node server.js &
    

    Powerful solution (allows you to reconnect to the process if it is interactive):

    screen
    

    You can then detach by pressing Ctrl+a+d and then attach back by running screen -r

    Also consider the newer alternative to screen, tmux.

    点赞 评论
  • csdnceshi75
    衫裤跑路 2011-01-25 17:54

    Have you read about the nohup command?

    点赞 评论
  • weixin_41568183
    零零乙 2011-01-25 17:56

    nohup will allow the program to continue even after the terminal dies. I have actually had situations where nohup prevents the SSH session from terminating correctly, so you should redirect input as well:

    $ nohup node server.js </dev/null &
    

    Depending on how nohup is configured, you may also need to redirect standard output and standard error to files.

    点赞 评论
  • csdnceshi72
    谁还没个明天 2012-08-08 01:48

    nohup node server.js > /dev/null 2>&1 &

    1. nohup means: Do not terminate this process even when the stty is cut off.
    2. > /dev/null means: stdout goes to /dev/null (which is a dummy device that does not record any output).
    3. 2>&1 means: stderr also goes to the stdout (which is already redirected to /dev/null). You may replace &1 with a file path to keep a log of errors, e.g.: 2>/tmp/myLog
    4. & at the end means: run this command as a background task.
    点赞 评论
  • csdnceshi79
    python小菜 2013-04-11 08:39

    another solution disown the job

    $ nohup node server.js &
    [1] 1711
    $ disown -h %1
    
    点赞 评论
  • csdnceshi75
    衫裤跑路 2013-06-28 06:40

    You really should try to use screen. It is a bit more complicated than just doing nohup long_running &, but understanding screen once you never come back again.

    Start your screen session at first:

    user@host:~$ screen
    

    Run anything you want:

    wget http://mirror.yandex.ru/centos/4.6/isos/i386/CentOS-4.6-i386-binDVD.iso
    

    Press ctrl+A and then d. Done. Your session keep going on in background.

    You can list all sessions by screen -ls, and attach to some by screen -r 20673.pts-0.srv command, where 0673.pts-0.srv is an entry list.

    点赞 评论
  • csdnceshi51
    旧行李 2014-05-22 19:48

    I have this function in my shell rc file, based on @Yoichi's answer:

    nohup-template () {
        [[ "$1" = "" ]] && echo "Example usage:\nnohup-template urxvtd" && return 0
        nohup "$1" > /dev/null 2>&1 &
    }
    

    You can use it this way:

    nohup-template "command you would execute here"
    
    点赞 评论
  • csdnceshi71
    Memor.の 2014-07-30 17:09
    $ disown node server.js &
    

    It will remove command from active task list and send the command to background

    点赞 评论
  • csdnceshi80
    胖鸭 2015-09-21 18:44

    Nohup and screen offer great light solutions to running Node.js in the background. Node.js process manager (PM2) is a handy tool for deployment. Install it with npm globally on your system:

    npm install pm2 -g

    to run a Node.js app as a daemon:

    pm2 start app.js

    You can optionally link it to Keymetrics.io a monitoring SAAS made by Unitech.

    点赞 评论
  • weixin_41568110
    七度&光 2016-03-18 18:02

    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.

    PM2: http://pm2.keymetrics.io/

    # 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]
    

    Where platform can be ubuntu|centos|redhat|gentoo|systemd|darwin|amazon.

    forever.js: https://github.com/foreverjs/forever

    # 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
    

    Init scripts:

    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

    Docker:

    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!

    点赞 评论
  • csdnceshi62
    csdnceshi62 2017-06-05 07:48

    To run command as a system service on debian with sysv init:

    Copy skeleton script and adapt it for your needs, probably all you have to do is to set some variables. Your script will inherit fine defaults from /lib/init/init-d-script, if something does not fits your needs - override it in your script. If something goes wrong you can see details in source /lib/init/init-d-script. Mandatory vars are DAEMON and NAME. Script will use start-stop-daemon to run your command, in START_ARGS you can define additional parameters of start-stop-daemon to use.

    cp /etc/init.d/skeleton /etc/init.d/myservice
    chmod +x /etc/init.d/myservice
    nano /etc/init.d/myservice
    
    /etc/init.d/myservice start
    /etc/init.d/myservice stop
    

    That is how I run some python stuff for my wikimedia wiki:

    ...
    DESC="mediawiki articles converter"
    DAEMON='/home/mss/pp/bin/nslave'
    DAEMON_ARGS='--cachedir /home/mss/cache/'
    NAME='nslave'
    PIDFILE='/var/run/nslave.pid'
    START_ARGS='--background --make-pidfile --remove-pidfile --chuid mss --chdir /home/mss/pp/bin'
    
    export PATH="/home/mss/pp/bin:$PATH"
    
    do_stop_cmd() {
        start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 \
            $STOP_ARGS \
            ${PIDFILE:+--pidfile ${PIDFILE}} --name $NAME
        RETVAL="$?"
        [ "$RETVAL" = 2 ] && return 2
        rm -f $PIDFILE
        return $RETVAL
    }
    

    Besides setting vars I had to override do_stop_cmd because of python substitutes the executable, so service did not stop properly.

    点赞 评论
  • csdnceshi67
    bug^君 2017-11-17 20:21

    Apart from cool solutions above I'd mention also about supervisord and monit tools which allow to start process, monitor its presence and start it if it died. With 'monit' you can also run some active checks like check if process responds for http request

    点赞 评论
  • weixin_41568196
    撒拉嘿哟木头 2018-01-18 17:07

    For Ubuntu i use this:

    (exec PROG_SH &> /dev/null &)

    regards

    点赞 评论
  • csdnceshi72
    谁还没个明天 2018-06-12 17:12

    Try this for a simple solution

    cmd & exit

    点赞 评论

相关推荐