插件窝 干货文章 linux停止服务命令有哪些

linux停止服务命令有哪些

服务 sudo 系统 systemctl 544    来源:    2025-04-20

在 Linux 系统中,停止服务(或管理服务状态)的命令取决于系统使用的初始化系统(init system)。以下是主流初始化系统的对应命令:


1. systemd(现代主流系统:Ubuntu 16.04+/CentOS 7+/RHEL 7+)

# 停止服务
sudo systemctl stop <服务名>

# 禁止开机启动
sudo systemctl disable <服务名>

# 查看服务状态
sudo systemctl status <服务名>

# 重启服务
sudo systemctl restart <服务名>

示例:停止 Nginx 服务

sudo systemctl stop nginx

2. SysVinit(旧版系统:Debian 7/CentOS 6 等)

# 停止服务
sudo service <服务名> stop

# 或直接调用 init 脚本
sudo /etc/init.d/<服务名> stop

# 禁止开机启动(需工具支持)
sudo chkconfig <服务名> off  # CentOS/RHEL
sudo update-rc.d -f <服务名> remove  # Debian/Ubuntu

示例:停止 Apache 服务

sudo service httpd stop
# 或
sudo /etc/init.d/httpd stop

3. 通用方法(强制终止进程)

如果服务无法通过正常命令停止,可以用 killpkill

# 查找进程 PID
ps aux | grep <服务名>

# 优雅终止(SIGTERM)
kill <PID>

# 强制终止(SIGKILL)
kill -9 <PID>

# 通过进程名终止
pkill -f <服务名>

示例:强制终止 MySQL 进程

pkill -9 mysqld

4. 其他工具

  • Upstart(Ubuntu 14.04 等过渡系统):

    sudo stop <服务名>
    
  • OpenRC(Gentoo/Alpine Linux):

    sudo rc-service <服务名> stop
    

注意事项

  1. 权限:大多数操作需要 sudo 或 root 权限。
  2. 服务名:可通过 systemctl list-unit-filesls /etc/init.d/ 查看可用服务。
  3. 依赖关系:直接 kill 进程可能导致数据损坏,优先使用系统提供的服务管理命令。

根据你的 Linux 发行版和版本选择合适的命令即可。