Search code examples
linuxcentosboot

Running multiple npm scripts on boot


I have a server that runs an express app and a react app. I needed to start both the apps on boot. So I added two lines on rc.local but it seems like only the first line runs and the second one doesn't. Why is that and how can I solve it?


Solution

  • Just as in any other script, the second command will only be executed after the first one has finished. That's probably not what you want when the first command is supposed to keep running pretty much forever.

    If you want the second command to execute before the first has finished, and if you want the script to exit before the second command has finished, then you must arrange for the commands to run in the background.

    So, at a minimum, instead of

    my-first-command
    my-second-command
    

    you want:

    my-first-command &
    my-second-command &
    

    However, it's better to do something a little more complex that in addition to putting the command into the background also places the command's working directory at the root of the filesystem, disconnects the command's input from the console, delivers its standard output and standard error streams to the syslog service (which will typically append that data into /var/log/syslog) and protects it from unintended signals. Like:

    ( cd / && nohup sh -c 'my-first-command 2>&1 | logger -t my-first-command &' </dev/null >/dev/null 2>&1 )
    

    and similarly for the second command.

    The extra redirections at the end of the line are to keep nohup from emitting unwanted informational messages and creating an unused nohup.out file. You might want to leave the final 2>&1 out until you are sure that the rest of the command is correct and is behaving the way you want it to. When you get to the point where the only message shown is nohup: redirecting stderr to stdout then you can restore the 2>&1 to get rid of that message.