温馨提示×

如何管理linux服务进程

小樊
36
2026-10-09 11:16:18
栏目: 智能运维

在 Linux 中,“管理服务进程”通常包含启动/停止/重启服务、查看状态、设置开机自启、日志查看、资源监控等内容。下面按常用方式 + 实战命令来说明。


一、使用 systemd(最推荐,现代 Linux 主流)

大多数发行版(CentOS 7+、Ubuntu 16.04+)都使用 systemd。

1️⃣ 基本管理命令

# 启动服务
sudo systemctl start nginx

# 停止服务
sudo systemctl stop nginx

# 重启
sudo systemctl restart nginx

# 重新加载配置(不中断服务)
sudo systemctl reload nginx

# 查看状态
systemctl status nginx

2️⃣ 开机自启管理

# 设置开机启动
sudo systemctl enable nginx

# 取消开机启动
sudo systemctl disable nginx

# 查看是否开机启动
systemctl is-enabled nginx

3️⃣ 查看所有服务

systemctl list-units --type=service
systemctl list-unit-files --type=service

4️⃣ 查看日志(非常重要)

# 查看某服务日志
journalctl -u nginx

# 实时查看
journalctl -u nginx -f

# 最近 100 行
journalctl -u nginx -n 100

二、使用 service(兼容旧系统)

sudo service nginx start
sudo service nginx stop
sudo service nginx restart
sudo service nginx status

⚠️ 本质还是调用 systemd(在新系统中)


三、查看和管理进程(通用)

1️⃣ 查看进程

ps aux | grep nginx
top
htop   # 更友好(需安装)

2️⃣ 杀死进程

kill PID
kill -9 PID   # 强制
pkill nginx

四、设置自定义服务(进阶)

例如写一个 myapp.service:

[Unit]
Description=My App
After=network.target

[Service]
ExecStart=/usr/bin/python3 /opt/myapp/app.py
Restart=always
User=myuser

[Install]
WantedBy=multi-user.target
sudo cp myapp.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl start myapp
sudo systemctl enable myapp

五、常见管理建议

✅ 优先用 systemctl
✅ 服务异常先看 status 和 journalctl
✅ 生产环境服务加 Restart=always
✅ 不要用 kill -9 作为首选


如果你愿意,可以告诉我:

  • 使用的是 CentOS / Ubuntu / Debian?
  • 是 系统服务 还是 自己写的服务(Python/Java/Node)?

我可以给你更具体的示例。

0 踩