插件窝 干货文章 linux服务进程如何启动停止

linux服务进程如何启动停止

service sudo name 服务 588    来源:    2025-05-14

在Linux系统中,管理服务进程的启动和停止主要有以下几种方式,具体取决于系统的初始化系统(如Systemd、SysVinit等):


1. Systemd(现代Linux发行版主流方式)

适用系统:CentOS 7+/Ubuntu 16+/Debian 8+ 等

常用命令:

# 启动服务
sudo systemctl start <service_name>

# 停止服务
sudo systemctl stop <service_name>

# 重启服务
sudo systemctl restart <service_name>

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

# 设置开机自启
sudo systemctl enable <service_name>

# 禁用开机自启
sudo systemctl disable <service_name>

# 列出所有服务
systemctl list-unit-files --type=service

示例(以Nginx为例):

sudo systemctl start nginx
sudo systemctl stop nginx

2. SysVinit(旧版系统)

适用系统:CentOS 6/Ubuntu 14.04 等旧版本

常用命令:

# 启动服务
sudo service <service_name> start

# 停止服务
sudo service <service_name> stop

# 重启服务
sudo service <service_name> restart

# 查看服务状态
sudo service <service_name> status

# 设置开机自启(需使用chkconfig)
sudo chkconfig <service_name> on

# 禁用开机自启
sudo chkconfig <service_name> off

示例(以Apache为例):

sudo service httpd start
sudo service httpd stop

3. 直接通过进程管理

如果服务未注册为系统服务,可通过进程管理命令操作:

# 启动进程(后台运行)
nohup /path/to/command &

# 停止进程(通过PID)
ps aux | grep <process_name>  # 找到PID
kill -9 <PID>                # 强制终止

# 优雅停止(发送SIGTERM信号)
kill -15 <PID>

4. 其他工具

  • Upstart(Ubuntu早期版本):

    sudo start <service_name>
    sudo stop <service_name>
    
  • Supervisor(第三方进程管理工具):

    sudo supervisorctl start <program_name>
    sudo supervisorctl stop <program_name>
    

常见问题排查

  1. 服务启动失败

    • 检查日志:journalctl -u <service_name(Systemd)或 /var/log/<service_name>.log
    • 确认端口冲突:netstat -tulnp | grep <port>
  2. 命令不存在

    • 确认服务名称是否正确(区分大小写)。
    • 确认是否安装了服务(如nginx vs httpd)。
  3. 权限问题

    • 使用sudo提权或确认当前用户是否有权限。

总结

  • 推荐优先使用systemctl(现代系统)。
  • 旧系统使用service + chkconfig
  • 进程级管理用killnohup

根据你的系统版本选择合适的命令即可。