一、systemd 是什么
现代 Linux 主流初始化系统(替代 SysV init),负责启动服务、管理进程生命周期、集中日志。
二、常用命令
systemctl status nginx # 查看状态
systemctl start/stop/restart nginx
systemctl enable nginx # 开机自启
systemctl daemon-reload # 改了 unit 后重载
三、写一个简单的 service
/etc/systemd/system/myapp.service:
[Unit]
Description=My App
After=network.target
[Service]
ExecStart=/usr/bin/java -jar /opt/myapp.jar
User=www-data
Restart=on-failure # 崩溃自动重启
[Install]
WantedBy=multi-user.target
四、查日志
journalctl -u myapp -f # 跟随日志
journalctl -u myapp --since "1 hour ago"
用 systemd 托管长驻进程比 nohup & 更稳:崩溃自愈、开机自启、日志统一、资源可控。Restart=on-failure 是关键防掉线配置。