服务管理 6 个核心

sudo systemctl status nginx              # 看状态
sudo systemctl start nginx               # 启动
sudo systemctl stop nginx                # 停止
sudo systemctl restart nginx             # 重启
sudo systemctl reload nginx              # 重载配置(不重启)
sudo systemctl enable nginx              # 开机自启
sudo systemctl disable nginx             # 取消自启
sudo systemctl enable --now nginx        # 自启 + 立刻启动

看状态

sudo systemctl status nginx
# ● nginx.service - High performance web 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
#      Memory: 12.3M

关键看 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             # 所有(含未启用)
systemctl list-units --type=service --all            # 含 inactive

用户级服务

不需要 sudo,给当前用户跑:

systemctl --user status myapp
systemctl --user enable myapp

unit 文件放 ~/.config/systemd/user/

reload-or-restart

不知道某服务支持不支持 reload?

sudo systemctl reload-or-restart nginx       # 支持 reload 就 reload,否则 restart

mask / unmask(彻底禁用)

sudo systemctl mask cups                     # 禁用且不允许启动(链到 /dev/null)
sudo systemctl unmask cups                   # 取消

比 disable 更狠——disablestart 仍可,mask 后连 start 都不行。

daemon-reload

改了 unit 文件后必须

sudo systemctl daemon-reload

不然 systemd 不知道你改了配置。

写一个简单 unit

/etc/systemd/system/myapp.service:

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

[Service]
Type=simple
User=wadely
WorkingDirectory=/home/wadely/myapp
ExecStart=/usr/bin/node server.js
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now myapp

详见 linux/21-systemctl

看依赖关系

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

  • 改了 unit 文件不 daemon-reload = 改动不生效
  • service / systemctl 都还能用,但 systemctl 是现代标准
  • 容器里通常没有 systemd——别在 Docker 容器里指望 systemctl