Linux服务怎么启动停止_服务管理教程

5次阅读

linux服务管理分systemd(centos 7+/ubuntu 16.04+)和system v init(centos 6/debian 7)两类:前者用systemctl命令操作服务及开机自启,后者依赖/etc/init.d/脚本配合service与chkconfig;可通过ps -p 1 -o comm=快速判断机制类型。

Linux服务怎么启动停止_服务管理教程

Linux服务的启动和停止,核心取决于你用的是哪种服务管理机制——当前主流是 systemd,老系统(如 CentOS 6、Ubuntu 14.04)则用 System V init。两者命令不同、配置位置不同,混用容易出错。下面按实际场景分清楚讲。

systemd 系统(CentOS 7+/Ubuntu 16.04+ 等)

这是你现在最可能遇到的环境。所有操作都用 systemctl 命令:

  • 启动服务:sudo systemctl start nginx
  • 停止服务:sudo systemctl stop nginx
  • 重启服务:sudo systemctl restart nginx
  • 查看状态:sudo systemctl status nginx(会显示是否运行、主进程号、最近日志)
  • 检查是否启用开机自启:sudo systemctl is-enabled nginx(返回 enabled 或 disabled)
  • 设置开机自启:sudo systemctl enable nginx(会在 /etc/systemd/system/multi-user.target.wants/ 创建软链接)
  • 取消开机自启:sudo systemctl disable nginx

注意:startenable 是两回事——前者只管当前会话,后者管下次开机。服务名通常不带 .service 后缀,但写全(如 nginx.service)也兼容。

System V init 系统(CentOS 6、Debian 7 等)

这类系统依赖 /etc/init.d/ 下的脚本,用 servicechkconfig 管理:

  • 启动服务:sudo service httpd start
  • 停止服务:sudo service httpd stop
  • 重启服务:sudo service httpd restart
  • 查看状态:sudo service httpd status
  • 设置开机自启:sudo chkconfig httpd on(对运行级别 3 和 5 生效)
  • 取消开机自启:sudo chkconfig httpd off
  • 查看服务在各运行级别的状态:sudo chkconfig –list httpd

服务脚本必须放在 /etc/init.d/,且有可执行权限。RPM 包安装的服务一般自带该脚本;源码编译安装的需手动创建或使用自带的控制脚本(如 /usr/local/nginx/sbin/nginx -s reload)。

通用方法:直接调用服务二进制或脚本

无论哪种体系,只要你知道服务程序路径和参数,都能绕过上层工具直接操作:

  • apache(源码安装):/usr/local/apache2/bin/apachectl start
  • mysql(二进制版):/opt/mysql/bin/mysqld_safe --user=mysql &
  • Nginx(无 systemd 脚本):/usr/local/nginx/sbin/nginx 启动,nginx -s stop 停止

这种方式不依赖系统服务管理器,适合调试或临时运行,但不会被 systemctl statusservice status 识别,也无法自动加入开机流程。

快速判断你用的是哪种机制

终端里执行:

  • ps -p 1 -o comm= —— 如果输出 systemd,就是 systemd;如果输出 init,大概率是 System V
  • systemctl list-units --type=service --state=running | head -5 —— 能正常列出服务,说明 systemd 可用
  • ls /etc/init.d/ | head -3 —— 有大量脚本,说明 System V 兼容层存在

多数现代发行版虽已默认 systemd,但仍保留 service 命令作为兼容入口——它内部会自动转发给 systemctl。所以 service nginx start 在 CentOS 8 上也能用,但建议统一用 systemctl 避免混淆。

text=ZqhQzanResources