简体   繁体   中英

Start node.js express server as a service

I'm currently preparing a react web app for production have set up a centos machine to host the app using node.js and express. I'd like to automate the starting of the express server.

My file structure is as follows:

/opt/
  |__ /express/
       |__ /node_modules/~
       |__ express.js
       |__ /public/
            |__ bundle.js
            |__ styles.css
            |__ index.html

Once the react web app is developed locally, it's packaged into a distribution and then moved into the public folder as seen above. express.js then starts the server and serves the page:

var path = require('path');
var express = require('express');
var app = express();
var port = 8000;

app.use(express.static('./public'));
app.get('*', (req, res) => {
    res.sendfile(path.resolve(__dirname, 'public/index.html'));
});
app.listen(port, () => {
    console.log('server running on port ' + port);
});

This works fine but requires me to manually start the server every time. I would like now to run express.js as an operating system level service so that its persistent and automatically starts up on boot/restart.

Ideally I would like this to be managed purely by the OS and not us any other npm packages.

How can this be done?

You probably want to use https://en.wikipedia.org/wiki/Systemd

TLDR:

Create the file /lib/systemd/system/<NiceReactApp>.service

Now put the service information in the file, replace what is in between <> with your values.

[Unit]
Description=<a nice react web app>

[Service]
Type=simple
User=<TheAccountForThisReactApp>
ExecStart=/usr/bin/node /home/<TheAccountForThisReactApp>/opt/express/express.js
Restart=on-failure

[Install]
WantedBy=multi-user.target

sudo systemctl daemon-reload

sudo systemctl start <NiceReactApp>

If you're using nvm to manage your node packages you will want to change the first argument for ExecStart to where you node package is.

You can use pm2 module to get the application to launch on system boot/restart, also it restarts the app automatically if it crashes or is killed to keep the server always available. TLDR:

Install pm2:

npm install pm2 -g

Start the app forever:

pm2 start app.js

Get the application to launch on system boot/restart:

pm2 startup systemd

I use forever

npm install -g forever

sudo forever-service install --script ./bin/www myapp

sudo service myapp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM