banner
约 1,200 字
4 分钟

systemd 服务管理教程:从 systemctl 到自己写服务

摘要

systemctl 是现代 Linux 运维每天都要用的工具。本教程依据 systemd 官方文档,介绍服务的启停重启、开机自启(enable --now)、查看服务列表、手写一个自定义 .service 文件(ExecStart/Restart/User 等关键字段),以及 journalctl 查看日志的方法。

systemd 服务管理教程

现代 Linux 发行版(Debian、Ubuntu、CentOS、RHEL、Fedora、Arch 等)默认都使用 systemd 作为初始化系统。管理服务的 systemctl 命令,是服务器运维每天都要打交道的工具。本教程依据 systemd 官方文档整理。

一、查看与启停服务

bash
systemctl status nginx     # 查看服务状态(是否运行、最近日志)
sudo systemctl start nginx     # 启动
sudo systemctl stop nginx      # 停止
sudo systemctl restart nginx   # 重启
sudo systemctl reload nginx    # 重载配置(不中断服务,Nginx 常用)

服务名可以省略 .service 后缀,systemctl status nginxnginx.service 等价。

二、开机自启

bash
sudo systemctl enable nginx    # 设置开机自启
sudo systemctl disable nginx   # 取消开机自启
sudo systemctl enable --now nginx   # 设置自启并立即启动,一步到位

enable 只是建立开机自启的链接,不会立刻启动服务——这就是 enable --now 存在的意义。

三、查看所有服务

bash
systemctl list-units --type=service            # 当前加载的所有服务
systemctl list-units --type=service --state=running   # 只看正在运行的
systemctl list-unit-files --type=service       # 所有服务及自启状态

四、写一个自己的服务

/etc/systemd/system/ 下新建 myapp.service

ini
[Unit]
Description=My Web App
After=network.target

[Service]
ExecStart=/usr/local/bin/myapp --port 8080
Restart=on-failure
RestartSec=5
User=www-data
WorkingDirectory=/opt/myapp

[Install]
WantedBy=multi-user.target

关键字段说明:

  • ExecStart:启动命令,必须用绝对路径

  • Restart=on-failure:异常退出时自动重启,always 则无论怎么退都重启

  • User:以哪个用户身份运行,服务不要用 root 跑

  • WantedBy=multi-user.target:enable 时挂到开机流程里

写完之后执行:

bash
sudo systemctl daemon-reload    # 让 systemd 重新读取配置
sudo systemctl enable --now myapp

修改了 .service 文件后,也要先 daemon-reload 再 restart。

五、看日志:journalctl

systemd 统一收集了所有服务的日志:

bash
journalctl -u nginx                  # 看某个服务的日志
journalctl -u nginx -f               # 实时滚动(类似 tail -f)
journalctl -u nginx --since today    # 今天的日志
journalctl -u nginx --since "1 hour ago"
journalctl -p err -b                 # 本次开机以来的错误级别日志

六、总结

需求

命令

看状态

systemctl status 服务

启动/停止/重启

start / stop / restart

开机自启

enable / disable,推荐 enable --now

自定义服务

/etc/systemd/system/xxx.service + daemon-reload

查日志

journalctl -u 服务 -f

把常驻程序写成 systemd 服务,系统崩溃重启、程序异常退出都能自动拉起,是比 nohup、screen 优雅得多的方案。

END