systemd 是什么

现代 Linux 发行版(Ubuntu 16.04+、CentOS 7+、Debian 8+)都用 systemd 做 init 系统——开机启动 + 服务管理 + 日志聚合一体化。

操作入口是 systemctl

服务管理 6 个核心命令

# 看状态
sudo systemctl status nginx

# 启动 / 停止 / 重启
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx

# 重载配置(不重启进程,nginx / postgres 等支持)
sudo systemctl reload nginx

# 开机自启 / 取消
sudo systemctl enable nginx        # 开机自启
sudo systemctl disable nginx       # 取消自启

# 一步到位
sudo systemctl enable --now nginx  # 启用 + 立即启动
sudo systemctl disable --now nginx # 停止 + 取消

看服务状态

sudo systemctl status nginx
# ● nginx.service - A high performance web server and a reverse proxy server
#      Loaded: loaded (/lib/systemd/system/nginx.service; enabled; ...)
#      Active: active (running) since Fri 2026-05-09 10:23:45 UTC; 2h ago
#    Main PID: 1234 (nginx)
#       Tasks: 3 (limit: 4915)
#      Memory: 12.3M
#         CPU: 250ms

关键看 Active

  • active (running) = 在跑
  • inactive (dead) = 没在跑
  • failed = 启动失败
  • activating = 正在启动

列出所有服务

systemctl list-units --type=service                  # 跑着的
systemctl list-units --type=service --state=failed   # 失败的
systemctl list-unit-files --type=service             # 所有(含没启用的)

写一个自己的服务

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

[Unit]
Description=My App
After=network.target
Wants=network.target

[Service]
Type=simple
User=wadely
WorkingDirectory=/home/wadely/myapp
ExecStart=/usr/bin/node server.js
Restart=on-failure
RestartSec=5
Environment=NODE_ENV=production
Environment=PORT=3000
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

字段速查

字段 含义
Type=simple 主进程就是 ExecStart
Type=forking 程序自己 fork 后台进程(老式服务)
Type=notify 程序自己发信号告诉 systemd 起好了
Restart=on-failure 异常退出自动重启(也可 always / no
RestartSec=5 重启前等 5 秒
After= 在哪些服务起来后再起
Environment= 环境变量(多行写多次)
EnvironmentFile= 从文件读环境变量

应用:

sudo systemctl daemon-reload          # 让 systemd 重新读 unit 文件
sudo systemctl enable --now myapp
sudo systemctl status myapp

看日志

systemd 把所有服务日志收到 journal:

journalctl -u nginx                    # 看 nginx 所有日志
journalctl -u nginx -f                 # 实时跟随(类似 tail -f)
journalctl -u nginx --since "1 hour ago"
journalctl -u nginx --since today
journalctl -u nginx -n 100             # 最后 100 行
journalctl -u nginx -p err             # 只看 error 级
journalctl -u nginx --no-pager         # 直接打印不分页

看服务依赖

systemctl list-dependencies nginx       # 它依赖谁
systemctl list-dependencies nginx --reverse  # 谁依赖它

故障排查流程

服务起不来 →

# 1. 看状态
sudo systemctl status myapp

# 2. 看完整日志
sudo journalctl -u myapp -n 50 --no-pager

# 3. 手动跑试试
sudo -u wadely /usr/bin/node /home/wadely/myapp/server.js

# 4. 改配置后
sudo systemctl daemon-reload
sudo systemctl restart myapp

下一篇:定时任务 crontab。