在服务器上使用docker运行自己编写的程序,可以一直保持运行状态,但如果服务器资源有限或者不使用docker,而是一个可执行文件直接运行,通常会采用nohop和&来让它后台执行,或者使用screen来运行,但当服务器重启之后,还要自己想着手动重启一下服务。
有没有可以自动重启的方法,不需要人工干预呢?
可以尝试一下systemd或者supervisord。
这里使用的是systemd。
1. 编写service文件
文件路径是 /lib/systemd/system/YOURSERVICE.service
[Unit]
Description=随便写点什么
After=network.target
[Service]
Type=simple
PIDFile=指向一个pid文件service.pid
ExecStart=指向你的启动脚本或可执行程序
ExecReload=/bin/kill -SIGHUP $MAINPID
ExecStop=/bin/kill -SIGINT $MAINPID
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
2. 添加并装载服务
sudo systemctl daemon-reload
sudo systemctl enable YOURSERVICE.service
3. 启动服务
sudo systemctl start YOURSERVICE.service
4. 查看日志
sudo systemctl status YOURSERVICE.service
或者
sudo journalctl -u YOURSERVICE.service