Systemd(Linux 系统级守护,最稳定)
Systemd 是 Linux 系统原生的服务管理器,优先级高于 PM2/Docker,适合对稳定性要求极高的场景(如核心业务):
步骤 1:创建 Systemd 服务文件
bash
运行
# 编辑服务文件(名称自定义为 nest-api.service)
sudo vim /etc/systemd/system/nest-api.service
步骤 2:写入以下配置(适配你的项目路径)
ini
[Unit]
Description=NestJS API Service # 服务描述
After=network.target docker.service # 网络/Docker启动后再启动
Requires=network.target # 依赖网络
[Service]
Type=simple
User=root # 运行用户(建议用非root,如 www)
WorkingDirectory=/home/nestjs-app # 项目根目录
ExecStart=/usr/local/bin/node /home/nestjs-app/dist/main.js # 启动命令(node 路径需用 which node 确认)
Restart=always # 始终重启(崩溃/退出/服务器重启)
RestartSec=3 # 重启间隔3秒
Environment=NODE_ENV=production # 环境变量
StandardOutput=append:/home/nestjs-app/logs/nest-api.log # 日志输出
StandardError=append:/home/nestjs-app/logs/nest-api.error.log # 错误日志
[Install]
WantedBy=multi-user.target # 多用户模式下开机自启
步骤 3:创建日志目录(确保权限)
bash
运行
mkdir -p /home/nestjs-app/logs
chmod 755 /home/nestjs-app/logs
步骤 4:启动并设置开机自启
bash
运行
# 重新加载 systemd 配置
sudo systemctl daemon-reload
# 启动服务
sudo systemctl start nest-api
# 设置开机自启
sudo systemctl enable nest-api
Systemd 常用管理命令
bash
运行
sudo systemctl status nest-api # 查看服务状态
sudo systemctl restart nest-api # 重启服务
sudo systemctl stop nest-api # 停止服务
sudo systemctl disable nest-api # 关闭开机自启
journalctl -u nest-api -f # 实时查看日志
方案 4:Supervisor(通用进程管理,支持所有语言)
Supervisor 是跨语言的进程管理器,适合同时管理多个服务(如 NestJS + Redis + MySQL):
步骤 1:安装 Supervisor
bash
运行
# CentOS/RHEL
sudo yum install supervisor -y
# Ubuntu/Debian
sudo apt install supervisor -y
步骤 2:创建配置文件
bash
运行
sudo vim /etc/supervisord.d/nest-api.ini
步骤 3:写入配置
ini
[program:nest-api]
directory=/home/nestjs-app ; 项目目录
command=/usr/local/bin/node dist/main.js ; 启动命令
autostart=true ; 开机自启
autorestart=true ; 崩溃自动重启
startretries=3 ; 启动失败重试次数
user=root ; 运行用户
redirect_stderr=true ; 错误日志重定向到stdout
stdout_logfile=/home/nestjs-app/logs/nest-api.log ; 日志文件
stdout_logfile_maxbytes=10MB ; 单日志文件大小
stdout_logfile_backups=10 ; 日志备份数
environment=NODE_ENV="production" ; 环境变量
步骤 4:启动 Supervisor 并加载配置
bash
运行
# 启动 Supervisor 服务
sudo systemctl start supervisord
sudo systemctl enable supervisord
# 加载新配置
sudo supervisorctl reread
sudo supervisorctl update
# 启动 NestJS 服务
sudo supervisorctl start nest-api
Supervisor 常用命令
bash
运行
sudo supervisorctl status nest-api # 查看状态
sudo supervisorctl restart nest-api # 重启
sudo supervisorctl stop nest-api # 停止
sudo supervisorctl tail -f nest-api # 实时日志