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

Web Technologies Web Development 2 years ago

0 1 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating
_x000D_ _x000D_ 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: I want my node.js server to run in the background, i.e.: when I close my terminal I want my server to keep running. I've googled this and came up with this tutorial, however it doesn't work as intended. So instead of using that daemon script, I thought I just used the output redirection (the 2>&1 >> file part), but this too does not exit - I get a blank line in my terminal, like it's waiting for output/errors. I've also tried to put the process in the background, but as soon as I close my terminal the process is killed as well. So how can I leave it running when I shut down my local computer? Top solutions: Systemd (Linux) Launchd (Mac) node-windows (Windows) PM2 (Node.js)

Posted on 16 Aug 2022, this text provides information on Web Development related to Web Technologies. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago
_x000D_ Copying my own answer from How do I run a Node.js application as its own process? 2015 answer: nearly every Linux distro comes with systemd, which means forever, monit, PM2, etc are no longer necessary - your OS already handles these tasks. Make a myapp.service file (replacing 'myapp' with your app's name, obviously): [Unit] Description=My app [Service] ExecStart=/var/www/myapp/app.js Restart=always User=nobody # Note Debian/Ubuntu uses 'nogroup', RHEL/Fedora uses 'nobody' Group=nogroup Environment=PATH=/usr/bin:/usr/local/bin Environment=NODE_ENV=production WorkingDirectory=/var/www/myapp [Install] WantedBy=multi-user.target Note if you're new to Unix: /var/www/myapp/app.js should have #!/usr/bin/env node on the very first line. Copy your service file into the /etc/systemd/system. Start it with systemctl start myapp. Enable it to run on boot with systemctl enable myapp. See logs with journalctl -u myapp This is taken from How we deploy node apps on Linux, 2018 edition, which also includes commands to generate an AWS/DigitalOcean/Azure CloudConfig to build Linux/node servers (including the .service file).

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Important Web Technologies Links