记一次华为云ECS Linux下用systemd托管Go服务踩坑:环境变量丢失与Restart=always无限重启限制排查
最近在华为云 ECS(Ubuntu 22.04 / Rocky Linux 9)上线 Go 服务,配置 /etc/systemd/system/app-api.service 后用 systemctl start app-api 启动,结果遇到了环境变量丢失与重启限制两个问题。
-
现象描述
启动后程序 panic 拿不到 /etc/profile 里的环境变量。由于 panic 导致进程频繁重启,触发了 systemd 的 Start request repeated too quickly 错误,被拒绝重启并挂起。 -
排查与解决
通过日志命令排查:
journalctl -u app-api -n 50 --no-pager
发现 systemd 不加载 Shell 交互配置 /etc/profile。解决办法是使用 EnvironmentFile=/etc/sysconfig/app-api.env 显式引入环境变量。
同时配置 Restart=on-failure 与 RestartSec=5s,并在 [Unit] 段设置 StartLimitIntervalSec=0 避免偶发连续崩溃后被 systemd 彻底挂起。 -
完整服务配置与部署命令
/etc/systemd/system/app-api.service 文件内容:
[Unit]
Description=Go API Service
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
User=root
WorkingDirectory=/opt/app-api
EnvironmentFile=/etc/sysconfig/app-api.env
ExecStart=/opt/app-api/bin/app-api
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=multi-user.target
使配置生效并启动服务:
systemctl daemon-reload && systemctl enable --now app-api
- 点赞
- 收藏
- 关注作者
评论(0)