Loading

systemctl命令

一、systemctl 常用命令

systemctlsystemd 的管理工具,用来管理服务、查看状态、控制开机启动等。

1. 服务管理

# 启动服务
systemctl start nginx

# 停止服务
systemctl stop nginx

# 重启服务
systemctl restart nginx

# 重新加载配置(不重启进程)
systemctl reload nginx

# 查看服务状态
systemctl status nginx

2. 开机自启管理

# 设置服务开机自启
systemctl enable nginx

# 取消开机自启
systemctl disable nginx

# 检查是否开机自启
systemctl is-enabled nginx

3. 单次开机自启 / 禁止

# 临时禁止启动(不会修改 enable 配置)
systemctl mask nginx

# 解除禁止
systemctl unmask nginx

4. 系统状态相关

# 查看所有服务的状态
systemctl list-units --type=service

# 列出开机启动服务
systemctl list-unit-files --type=service

# 关机
systemctl poweroff

# 重启
systemctl reboot

# 挂起
systemctl suspend

二、systemd 配置文件示例

systemd 服务配置文件一般放在 /etc/systemd/system/ 下,以 .service 结尾。

下面给出一个自定义服务的示例,比如运行一个 Python Web 应用(Flask):

文件路径/etc/systemd/system/myapp.service

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

[Service]
# 启动用户和工作目录
User=www-data
Group=www-data
WorkingDirectory=/opt/myapp

# 启动命令
ExecStart=/usr/bin/python3 /opt/myapp/app.py

# 环境变量
Environment="FLASK_ENV=production"

# 异常退出后重启
Restart=always
RestartSec=5

# 资源限制(可选)
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target

启用并启动该服务

# 重新加载 systemd 配置
systemctl daemon-reexec
systemctl daemon-reload

# 启动服务
systemctl start myapp

# 设置开机自启
systemctl enable myapp

# 查看状态
systemctl status myapp
posted @ 2025-09-09 23:05  kiiou  阅读(45)  评论(0)    收藏  举报