温馨提示×

centos怎么批量管理进程

小樊
55
2026-10-20 17:59:43
栏目: 智能运维

在 CentOS(以及一般 Linux)上“批量管理进程”,常见场景有:批量启动/停止/重启、批量查看状态、批量杀进程、按规则批量操作。下面按“从简单到专业”给你一套实用方案。


一、最常用:用命令批量操作进程

1. 批量查看进程

ps -ef | grep nginx

或

pgrep -a nginx

2. 批量杀进程(按名称)

pkill nginx

或

killall nginx

按条件杀(例如运行超过 1 小时):

ps -eo pid,etimes,comm | awk '$2>3600 && $3=="java"{print $1}' | xargs kill -9

3. 批量重启(示例)

for s in nginx php-fpm redis; do
  systemctl restart $s
done

二、使用 systemd(CentOS 7+ 推荐)

1. 批量管理同一个服务的多实例

如果你用的是 @ 实例服务:

systemctl start myapp@1
systemctl start myapp@2

批量:

systemctl start 'myapp@*'

2. 查看所有运行中的服务

systemctl list-units --type=service --state=running

3. 批量停止一类服务

systemctl list-units --type=service | grep app | awk '{print $1}' | xargs systemctl stop

三、用 Shell 脚本批量管理(灵活)

示例:批量启动多个程序

#!/bin/bash
apps=(nginx redis mysql)

for app in "${apps[@]}"; do
  systemctl restart $app
done

示例:批量检查进程是否存在

for p in nginx redis; do
  pgrep $p >/dev/null && echo "$p running" || echo "$p not running"
done

四、使用 Supervisor(适合自研程序)

安装

yum install supervisor -y
systemctl enable supervisord
systemctl start supervisord

配置示例

[program:app1]
command=/opt/app1/run.sh
autostart=true
autorestart=true

批量管理

supervisorctl start all
supervisorctl stop all
supervisorctl restart all
supervisorctl status

✅ 优点:

  • 自动重启
  • 日志集中
  • 很适合 Java / Python / Go 程序

五、集群级批量管理(多台 CentOS)

如果是多台服务器:

1. Ansible(强烈推荐)

ansible all -m shell -a "systemctl restart nginx"

或 playbook:

- hosts: web
  tasks:
    - name: restart nginx
      systemd:
        name: nginx
        state: restarted

2. pssh(轻量)

pssh -h hosts.txt "systemctl restart nginx"

六、容器 / K8s(现代方案)

  • Docker Compose
  • Kubernetes(Deployment + kubectl)

七、我该用哪种?

场景 推荐
单机少量服务 systemctl
自研程序 supervisor
脚本灵活控制 shell
多台服务器 Ansible
微服务 K8s

如果你能告诉我:

  • 是 单机还是多机
  • 管理的是 什么进程(Java / Nginx / 自研)
  • 想实现 启动 / 停止 / 监控 / 自动重启

我可以直接给你一套可复制的配置方案。

0 踩