学习中心/工程实践/Linux/Linux 10:自己的程序也要能拉起来
· Linux · 10 · 服务
Linux 10:自己的程序也要能拉起来
写 unit、drop-in、timer。改发行版原文件会被升级盖掉。

长期跑的东西交给 systemd
关掉终端,前台进程就没了。这一块走完,你该能管别人装好的服务,也能把自己的程序写成 unit:开机起来、挂了能读原因、改配置不用去改发行版的原文件。
- 看status
- 启停restart / reload
- 开机enable
- 自己的unit + edit
1. 看状态
- 看在不在跑、退出码、最近几行日志
systemctl status nginx - 看开机启不启动
systemctl is-enabled nginx - 看是否处于失败
systemctl is-failed nginx - 看这台机器上所有失败的 unit
systemctl --failed
2. 启、停、重载
- 启现在开始跑
sudo systemctl start nginx - 停现在停
sudo systemctl stop nginx - 重启停再启。进程会换 pid
sudo systemctl restart nginx - 重载能重读配置就 reload,少断连接。没有 reload 再用 restart
sudo systemctl reload nginx
3. 开机自己起来
- 开机现在 start,并且开机自动
sudo systemctl enable --now nginx - 取消开机不再自动。正在跑的不会因此停
sudo systemctl disable nginx - 禁连手工 start 也被挡住。比 disable 更硬。解开:unmask
sudo systemctl mask nginx
enable 不等于现在就 start。刚 enable 完还要 start,或 enable --now。
4. 失败先看日志
- 看跳到这个服务日志末尾
journalctl -u nginx -e --no-pager - 看这次开机以来
journalctl -u nginx -b --no-pager - 看按时间切
journalctl -u nginx --since "10 min ago"
status 里已经有几行。不够再 journalctl。不要先改一堆配置。
5. 读 unit
- 看实际生效的文件,含 drop-in
systemctl cat nginx - 看从哪加载、怎么启动、挂了重不重启
systemctl show nginx -p FragmentPath -p ExecStart -p Restart
发行版的 unit 在 /lib/systemd/system。不要直接改那里,升级会盖掉。覆盖用下一节的 edit。
6. 自己写一个最小 unit
程序已经能在前台跑,再交给 systemd。例子放 /etc/systemd/system/myapp.service:
- 写说明依赖
[Unit] - 写status 里看到的名字
Description=myapp - 写网络好了再起。按需要改
After=network-online.target - 写怎么跑
[Service] - 写不要用 root 跑应用
User=www-data - 写工作目录
WorkingDirectory=/opt/myapp - 写前台跑。不要在这里 nohup
ExecStart=/opt/myapp/bin/myapp - 写挂了拉起来。死循环崩溃会打满日志,先修好
Restart=on-failure - 写enable 时挂到哪
[Install] - 写普通服务器用这个
WantedBy=multi-user.target
- 加载改了 unit 文件必须这一步
sudo systemctl daemon-reload - 开机加载后再 enable
sudo systemctl enable --now myapp
7. 覆盖,不要改原文件
- 改生成 drop-in。只写你要改的键
sudo systemctl edit nginx
edit 打开的是覆盖层。Environment=、ExecStart= 要改启动参数时用这个。改完 daemon-reload,再 restart。systemctl revert 能撤掉覆盖。
8. 定时:timer 和 cron
- 看systemd 的定时任务
systemctl list-timers --all - 看root 的 cron。用户自己的 crontab -l 不加 sudo
sudo crontab -l
新机器优先 timer:日志进 journalctl,依赖写在 unit 里。cron 还在,改之前先看现在有什么。输出默认寄邮件,没有 MTA 就会丢,重定向到文件更稳。
这块过关:能让自己的程序开机起来,挂了先 journalctl,改行为用 edit 不是改发行版原文件。最后一篇:机器病了按顺序量。