How to run Node.js as a background process and never die?

前端 未结 14 1216
刺人心
刺人心 2020-11-22 10:59

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

14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 11:22

    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.

提交回复
热议问题