如何在CentOS上将Node.js Express服务器配置为自动启动服务?
Hey there! Let's get your Express server set up to auto-start on your CentOS machine—here are the most reliable, battle-tested methods I recommend:
1. Use Systemd (CentOS Official Recommendation, No Extra Dependencies)
This is the go-to method for CentOS since it's built right into the system, ensuring robust auto-start and crash recovery.
- First, create a systemd service file:
sudo nano /etc/systemd/system/express-react.service - Paste the following config, replacing the placeholders with your actual details:
[Unit] Description=Express Server for React Production App After=network.target # Wait for network to be ready before starting [Service] User=your-server-username # e.g., root or a dedicated app user WorkingDirectory=/absolute/path/to/your/express-project # Where your app.js/server.js lives ExecStart=/usr/bin/node app.js # Use `which node` to get your Node path if unsure Restart=always # Auto-restart if the server crashes RestartSec=10 # Wait 10 seconds before restarting Environment=NODE_ENV=production # Enable production mode for better performance [Install] WantedBy=multi-user.target # Start when the system reaches multi-user mode - Save and exit the editor (Ctrl+O, Enter, Ctrl+X in nano)
- Reload systemd to recognize the new service:
sudo systemctl daemon-reload - Start the service immediately:
sudo systemctl start express-react - Set it to auto-start on boot:
sudo systemctl enable express-react - Verify everything's working:
sudo systemctl status express-react
2. Use PM2 (Node.js Process Manager, Feature-Rich)
If you prefer a Node.js-native tool with extra features like log management and process monitoring, PM2 is a great choice.
- Install PM2 globally:
npm install pm2 -g - Navigate to your Express project root directory, then start the server:
pm2 start app.js --name "express-react" - Set up PM2 to auto-start on boot:
Follow the on-screen prompt to run the generated command (it will set up the necessary systemd config for PM2 itself).pm2 startup centos - Save your current PM2 process list so it's restored on boot:
pm2 save - Useful PM2 commands for maintenance:
pm2 status: Check running processespm2 logs express-react: View real-time logspm2 restart express-react: Restart the serverpm2 stop express-react: Stop the server temporarily
Quick Notes
- Always use the absolute path for your project directory and Node executable to avoid issues with systemd/PM2's working context.
- If using a non-root user, make sure they have read/write permissions for your Express project and the
distfolder. - Setting
NODE_ENV=productionis critical—it optimizes React's bundled assets and disables Express's debug mode.
内容的提问来源于stack exchange,提问作者JavascriptLoser
相关产品推荐
相关产品推荐

