学习中心/工程实践/Linux/Linux 10:自己的程序也要能拉起来

· Linux · 10 · 服务

Linux 10:自己的程序也要能拉起来

写 unit、drop-in、timer。改发行版原文件会被升级盖掉。

正在加载录音…

长期跑的东西交给 systemd

关掉终端,前台进程就没了。这一块走完,你该能管别人装好的服务,也能把自己的程序写成 unit:开机起来、挂了能读原因、改配置不用去改发行版的原文件。

  1. 看status
  2. 启停restart / reload
  3. 开机enable
  4. 自己的unit + edit

1. 看状态

  • 看
    在不在跑、退出码、最近几行日志systemctl status nginx
  • 看
    开机启不启动systemctl is-enabled nginx
  • 看
    是否处于失败systemctl is-failed nginx
  • 看
    这台机器上所有失败的 unitsystemctl --failed

2. 启、停、重载

  • 启
    现在开始跑sudo systemctl start nginx
  • 停
    现在停sudo systemctl stop nginx
  • 重启
    停再启。进程会换 pidsudo systemctl restart nginx
  • 重载
    能重读配置就 reload,少断连接。没有 reload 再用 restartsudo systemctl reload nginx

3. 开机自己起来

  • 开机
    现在 start,并且开机自动sudo systemctl enable --now nginx
  • 取消
    开机不再自动。正在跑的不会因此停sudo systemctl disable nginx
  • 禁
    连手工 start 也被挡住。比 disable 更硬。解开:unmasksudo 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-insystemctl 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
  • 写
    前台跑。不要在这里 nohupExecStart=/opt/myapp/bin/myapp
  • 写
    挂了拉起来。死循环崩溃会打满日志,先修好Restart=on-failure
  • 写
    enable 时挂到哪[Install]
  • 写
    普通服务器用这个WantedBy=multi-user.target
  • 加载
    改了 unit 文件必须这一步sudo systemctl daemon-reload
  • 开机
    加载后再 enablesudo 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 不加 sudosudo crontab -l

新机器优先 timer:日志进 journalctl,依赖写在 unit 里。cron 还在,改之前先看现在有什么。输出默认寄邮件,没有 MTA 就会丢,重定向到文件更稳。

这块过关:能让自己的程序开机起来,挂了先 journalctl,改行为用 edit 不是改发行版原文件。最后一篇:机器病了按顺序量。

同模块

工程实践 →