Skip to content

systemctl

基本用法

查看服务状态

bash
#!/bin/bash

# 查看服务状态
systemctl status service_name

启动服务

bash
#!/bin/bash

# 启动服务
systemctl start service_name

停止服务

bash
#!/bin/bash

# 停止服务
systemctl stop service_name

重启服务

bash
#!/bin/bash

# 重启服务
systemctl restart service_name

重新加载服务

bash
#!/bin/bash

# 重新加载服务
systemctl reload service_name

服务管理

启用服务

bash
#!/bin/bash

# 启用服务(开机自启)
systemctl enable service_name

禁用服务

bash
#!/bin/bash

# 禁用服务(关闭开机自启)
systemctl disable service_name

查看服务是否启用

bash
#!/bin/bash

# 查看服务是否启用
systemctl is-enabled service_name

查看服务是否运行

bash
#!/bin/bash

# 查看服务是否运行
systemctl is-active service_name

服务列表

查看所有服务

bash
#!/bin/bash

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

# 查看所有服务(包括未运行的)
systemctl list-units --type=service --all

查看运行中的服务

bash
#!/bin/bash

# 查看运行中的服务
systemctl list-units --type=service --state=running

查看失败的服务

bash
#!/bin/bash

# 查看失败的服务
systemctl list-units --type=service --state=failed

实用示例

示例1:管理 Nginx 服务

bash
#!/bin/bash

# 启动 Nginx 服务
systemctl start nginx

# 停止 Nginx 服务
systemctl stop nginx

# 重启 Nginx 服务
systemctl restart nginx

# 重新加载 Nginx 服务
systemctl reload nginx

# 启用 Nginx 服务
systemctl enable nginx

# 禁用 Nginx 服务
systemctl disable nginx

# 查看 Nginx 服务状态
systemctl status nginx

示例2:管理 MySQL 服务

bash
#!/bin/bash

# 启动 MySQL 服务
systemctl start mysql

# 停止 MySQL 服务
systemctl stop mysql

# 重启 MySQL 服务
systemctl restart mysql

# 启用 MySQL 服务
systemctl enable mysql

# 禁用 MySQL 服务
systemctl disable mysql

# 查看 MySQL 服务状态
systemctl status mysql

示例3:管理 Apache 服务

bash
#!/bin/bash

# 启动 Apache 服务
systemctl start apache2

# 停止 Apache 服务
systemctl stop apache2

# 重启 Apache 服务
systemctl restart apache2

# 启用 Apache 服务
systemctl enable apache2

# 禁用 Apache 服务
systemctl disable apache2

# 查看 Apache 服务状态
systemctl status apache2

示例4:管理 Docker 服务

bash
#!/bin/bash

# 启动 Docker 服务
systemctl start docker

# 停止 Docker 服务
systemctl stop docker

# 重启 Docker 服务
systemctl restart docker

# 启用 Docker 服务
systemctl enable docker

# 禁用 Docker 服务
systemctl disable docker

# 查看 Docker 服务状态
systemctl status docker

最佳实践

1. 使用 systemctl

bash
# 好的做法
systemctl start service_name

# 不好的做法
service service_name start

2. 启用服务

bash
# 好的做法
systemctl enable service_name

# 不好的做法
chkconfig service_name on

3. 查看服务状态

bash
# 好的做法
systemctl status service_name

# 不好的做法
service service_name status

总结

systemctl 的关键点:

  1. 基本用法:启动、停止、重启、重新加载服务
  2. 服务管理:启用、禁用服务
  3. 服务列表:查看所有服务、运行中的服务、失败的服务
  4. 实用示例:管理 Nginx 服务、管理 MySQL 服务、管理 Apache 服务、管理 Docker 服务
  5. 最佳实践:使用 systemctl、启用服务、查看服务状态

下一节我们将学习网络配置的使用。