Skip to content

systemctl 的使用

配置示例

已自定义服务名为 abc 为例:

  • 文件地址:/etc/systemd/system/abc.service
  • 配置内容:
ini
Description=abc
After=network-online.target

[Service]
Environment="PYTHON_ENV=prod"
Environment="DB=abc"
Restart=on-failure
ExecStart=/usr/bin/python3 /root/abc.py

[Install]
WantedBy=multi-user.target
  • 环境变量:使用 Environment 字段添加,多个使用多次就行
  • 使配置生效:systemctl daemon-reload
  • 查询启动状态:systemctl status abc
  • 设置开机启动:systemctl enable abc

常用命令

bash
systemctl status abc        # 查询状态
systemctl start abc         # 启动服务
systemctl stop abc          # 停止服务
systemctl restart abc       # 重启服务

systemctl enable abc        # 设置开机自启
systemctl disable abc       # 关闭开机自启

systemctl daemon-reload     # 使配置生效

# 查看开机启动顺序,命令执行后用浏览器打开 boot.svg,分析启动顺序和启动时间
systemd-analyze plot > boot.svg

查看所有开机自启的服务

bash
systemctl list-unit-files
systemctl list-unit-files | grep enabled
txt
UNIT FILE                                     STATE
proc-sys-fs-binfmt_misc.automount             static
dev-hugepages.mount                           static
dev-mqueue.mount                              static
proc-sys-fs-binfmt_misc.mount                 static
sys-fs-fuse-connections.mount                 static
sys-kernel-config.mount                       static
sys-kernel-debug.mount                        static
tmp.mount                                     disabled
brandbot.path                                 disabled
systemd-ask-password-console.path             static
systemd-ask-password-plymouth.path            static
systemd-ask-password-wall.path                static
session-1091679.scope                         static
session-407810.scope                          static
session-8731.scope                            static
aegis.service                                 enabled
aliyun.service                                enabled
arp-ethers.service                            disabled
AssistDaemon.service                          enabled
atd.service                                   enabled

设置依赖关系(设置启动顺序)

bash
[Unit]
Description=My Website
After=syslog.target network.target mongodb.service