How do I run a node.js app as a background service?

前端 未结 26 1394
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 05:28

Since this post has gotten a lot of attention over the years, I\'ve listed the top solutions per platform at the bottom of this post.


Original post

26条回答
  •  萌比男神i
    2020-11-22 06:01

    Since I'm missing this option in the list of provided answers I'd like to add an eligible option as of 2020: docker or any equivalent container platform. In addition to ensuring your application is working in a stable environment there are additional security benefits as well as improved portability.

    There is docker support for Windows, macOS and most/major Linux distributions. Installing docker on a supported platform is rather straight-forward and well-documented. Setting up a Node.js application is as simple as putting it in a container and running that container while making sure its being restarted after shutdown.

    Create Container Image

    Assuming your application is available in /home/me/my-app on that server, create a text file Dockerfile in folder /home/me/my-app with content similar to this one:

    FROM node:lts-alpine
    COPY /my-app /app
    CMD ["/app/server.js"]
    

    Create the image using command like this:

    docker build -t myapp-as-a-service /home/me
    

    Note: Last parameter is selecting folder containing that Dockerfile instead of the Dockerfile itself. You may pick a different one using option -f.

    Start Container

    Use this command for starting the container:

    docker run -d --restart always -p 80:3000 myapp-as-a-service
    

    This command is assuming your app is listening on port 3000 and you want it to be exposed on port 80 of your host.

    This is a very limited example for sure, but it's a good starting point.

提交回复
热议问题