温馨提示×

centos nodejs如何配置开机自启

小樊
39
2026-07-20 01:56:54
栏目: 编程语言

CentOS(7 及以后) 里,给 Node.js 应用配置开机自启,最常见、最推荐的方式是 systemd。下面分步骤说明,包含示例和常见注意事项。


一、准备条件

  1. CentOS 版本
cat /etc/centos-release
  • CentOS 7 / 8 / Stream ✅ 都支持 systemd
  1. Node.js 已安装
node -v
npm -v
  1. Node.js 应用示例 假设你的项目路径是:
/opt/myapp

启动命令是:

node /opt/myapp/app.js

npm start

二、使用 systemd 配置开机自启(推荐 ✅)

1️⃣ 创建 systemd 服务文件

sudo vi /etc/systemd/system/myapp.service

2️⃣ 示例配置(非常重要)

✅ 使用 node 直接启动

[Unit]
Description=Node.js App
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node /opt/myapp/app.js
Restart=always
RestartSec=5
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target

✅ 使用 npm start 启动

ExecStart=/usr/bin/npm start

⚠️ 注意:

  • ExecStart 必须是 绝对路径
  • 查看 node 路径:
which node
which npm

3️⃣ 重载 systemd 配置

sudo systemctl daemon-reload

4️⃣ 启动并设置开机自启

sudo systemctl start myapp
sudo systemctl enable myapp

5️⃣ 查看状态

systemctl status myapp

三、常用管理命令

# 启动
systemctl start myapp

# 停止
systemctl stop myapp

# 重启
systemctl restart myapp

# 查看日志
journalctl -u myapp -f

# 禁用开机自启
systemctl disable myapp

四、常见问题排查

❌ 1. 服务启动失败

查看详细日志:

journalctl -u myapp --no-pager

❌ 2. 端口被占用

netstat -tunlp | grep 3000

❌ 3. node 路径错误

which node

确保 ExecStart 路径一致


五、CentOS 6(不推荐,老系统)

如果是 CentOS 6,使用 chkconfig + init.d

vi /etc/init.d/myapp
chmod +x /etc/init.d/myapp
chkconfig --add myapp
chkconfig myapp on

⚠️ 但 强烈建议升级到 CentOS 7+ 使用 systemd


六、推荐生产方案(进阶)

  • ✅ 使用 PM2 + systemd
npm install -g pm2
pm2 start app.js
pm2 startup
pm2 save

七、总结

最佳实践

  • CentOS 7+ → systemd
  • 高可用 → PM2 + systemd
  • 一定用 绝对路径
  • 一定要 systemctl enable

如果你愿意,可以把你的:

  • CentOS 版本
  • Node 启动方式
  • 是否用 npm start

发给我,我可以帮你 直接生成可用的 service 文件

0