Linux上服务自动重启

前言

有时因为各种原因,比如程序崩溃,内存不足等原因导致服务down掉,我们可以使用systemd让服务自动重启。

自动重启

在 Linux 上,让 Go 服务“崩溃后自动重启”最省心的做法就是:

不要把守护逻辑写进 Go 程序里,而是交给 systemd(Ubuntu/CentOS/Debian 均自带)。

systemd 会在进程退出码非 0 时立即帮你拉起,还能限制重启频率、记录日志、设置环境变量、开机自启,一条命令搞定。

服务

准备一个最小单元文件

假设你的可执行文件放在 /data/wwwjarapi/8931mcws/xh-control-ws,用户 root

创建文件

1
vi /etc/systemd/system/xh-control-ws.service

内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[Unit]
Description=xh-control-ws
After=network.target

[Service]
Type=simple
User=root
Group=root
WorkingDirectory=/data/wwwjarapi/8931mcws
ExecStart=/data/wwwjarapi/8931mcws/xh-control-ws
Restart=always
RestartSec=5s
StartLimitInterval=60s
StartLimitBurst=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

Service配置说明:

Type=simple → 拉起进程就算启动完成
User=root → 用 root 身份跑
Group=root → 用户组 root
WorkingDirectory=… → 先 cd 到该目录再启动
ExecStart=… → 要执行的命令(必须绝对路径)
Restart=always → 一挂就重启
RestartSec=5s → 等待5秒再重启
StartLimitInterval=60s + StartLimitBurst=10 → 60 秒内超 10 次重启就放弃
StandardOutput=journal → 把 stdout 打进 systemd 日志
StandardError=journal → 把 stderr 也打进 systemd 日志

启用并立即启动

1
2
sudo systemctl daemon-reload
sudo systemctl enable --now xh-control-ws

验证

手动 kill 进程:

1
2
ps -ef | grep xh-control-ws
sudo kill -9 <pid>

查看状态

1
systemctl status xh-control-ws

可以看到 systemd 5 秒后已重新拉起,日志在

1
journalctl -u xh-control-ws -f

正常停止/启动服务

1
2
3
4
5
6
7
8
# 只停掉当前运行实例(下次开机若 enable 了仍会自启)
sudo systemctl stop xh-control-ws

# 需要时再启动
sudo systemctl start xh-control-ws

# 重启(先 stop 再 start)
sudo systemctl restart xh-control-ws

彻底禁用自启(stop + disable)

1
sudo systemctl disable --now xh-control-ws   # --now 顺便帮你 stop