Skip to content

Linux-服务程序管理

systemd 是 Linux 系统的新型初始化系统和服务管理器,取代传统的 SysVinit。它提供:

  • 并行启动服务
  • 按需激活守护进程
  • 快照和系统状态恢复
  • 依赖关系管理

服务状态管理

命令作用
systemctl start <服务名>启动服务(立即生效)
systemctl stop <服务名>停止服务
systemctl restart <服务名>重启服务
systemctl reload <服务名>重新加载配置(不重启服务)
systemctl status <服务名>查看服务状态(运行/失败/日志)
systemctl enable <服务名>开机自启
systemctl disable <服务名>开机不自启
systemctl is-active <服务名>检查服务是否正在运行
systemctl is-enabled <服务名>检查服务是否开机自启
systemctl enable --now <服务名>开机自启,并立即启动
systemctl disable --now <服务名>开机不自启,并立即关
systemctl status系统管理
journalctl -u <服务名>日志管理
journalctl查看系统日志

systemd 配置文件参数解析

systemd 中,服务、挂载点、定时任务等均由 单元文件(Unit File) 定义,通常以 .service.mount.timer 等后缀命名。以下是 systemd 配置文件的核心参数解析,涵盖 [Unit][Service][Install] 三个主要区块的配置选项

配置文件位置

  • 系统级服务
    • /usr/lib/systemd/system/:软件包安装的默认单元文件。
    • /etc/systemd/system/:管理员自定义或覆盖的单元文件(优先级更高)。
  • 用户级服务
    • ~/.config/systemd/user/:用户自定义服务。

配置文件结构

ini
[Unit]
Description=My Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/bin/myapp
Restart=on-failure

[Install]
WantedBy=multi-user.target

[Unit] 区块参数

定义服务的元信息和依赖关系。

参数说明
Description服务描述信息(显示在 systemctl status 中)。
After指定在哪些服务之后启动(如 network.target 表示网络就绪后启动)。
Before指定在哪些服务之前启动。
Requires强依赖的其他服务(如果依赖服务失败,当前服务也会停止)。
Wants弱依赖的其他服务(即使依赖服务失败,当前服务仍会启动)。
Conflicts指定不能共存的单元(如 foo.servicebar.service 不能同时运行)。
ConditionPathExists=/path仅在指定路径存在时启动服务。

示例

ini
[Unit]
Description=My Web Service
After=network.target mysql.service
Requires=mysql.service

[Service] 区块参数

定义服务的运行行为。

参数说明
Type服务类型: simple(默认,主进程立即启动) forking(主进程 fork 子进程后退出) oneshot(执行一次后退出) notify(通过 sd_notify 通知 systemd 启动完成)
ExecStart启动服务的命令(必须是绝对路径)。
ExecStop停止服务的命令。
ExecReload重载配置的命令(如 nginx -s reload)。
Restart退出时是否重启: no(默认) on-failure(失败时重启) always(总是重启)
RestartSec重启间隔时间(如 5s)。
User / Group以指定用户/组运行服务(如 User=nginx)。
WorkingDirectory服务的工作目录。
Environment设置环境变量(如 Environment="PORT=8080")。
EnvironmentFile从文件加载环境变量(如 EnvironmentFile=/etc/myapp.conf)。
LimitNOFILE限制文件描述符数量(如 LimitNOFILE=65536)。
StandardOutput / StandardError日志输出方式: journal(默认,写入 journald) file:/path/to/log(写入文件)

示例

ini
[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/myapp/app.py
User=myapp
Restart=on-failure
RestartSec=5s
Environment="DB_HOST=localhost"

[Install] 区块参数

定义服务的安装目标(开机自启)。

参数说明
WantedBy指定服务所属的 target(如 multi-user.target 表示多用户模式)。
RequiredBy类似 WantedBy,但表示强依赖关系。
Alias为服务设置别名(如 alias-for-myapp.service)。

示例

ini
[Install]
WantedBy=multi-user.target

重点说明

  • 修改单元文件后,必须重新加载

    systemctl daemon-reload