CentOS 7 起全面採用 systemd 管理服務,service 與 /etc/init.d/ 兼容但非首選。本文給出 **systemd 原生命令** 為主、兼容命令為輔的標準操作姿勢,並補充**狀態檢查、開機自啟、日誌查看**等運維必備技能。
systemctl [start|stop|restart|reload|status|enable|disable|is-enabled] 服務名
| 操作 | Apache (httpd) | MySQL / MariaDB | Nginx |
|---|---|---|---|
| 服務名 | httpd | mysqld / mariadb | nginx |
| 啟動 | systemctl start httpd | systemctl start mysqld | systemctl start nginx |
| 停止 | systemctl stop httpd | systemctl stop mysqld | systemctl stop nginx |
| 重啟 | systemctl restart httpd | systemctl restart mysqld | systemctl restart nginx |
| 重載配置 (不中斷連接) | systemctl reload httpd | systemctl reload mysqld | systemctl reload nginx |
| 查看狀態 | systemctl status httpd | systemctl status mysqld | systemctl status nginx |
| 設置開機自啟 | systemctl enable httpd | systemctl enable mysqld | systemctl enable nginx |
| 取消開機自啟 | systemctl disable httpd | systemctl disable mysqld | systemctl disable nginx |
| 查看是否開機自啟 | systemctl is-enabled httpd | systemctl is-enabled mysqld | systemctl is-enabled nginx |
service httpd restart /etc/init.d/httpd restart service mysqld restart /etc/init.d/mysqld restart service nginx restart /etc/init.d/nginx restart
# 跟蹤 Apache 錯誤日誌 journalctl -u httpd -f --since "10 min ago" # 跟蹤 MySQL 錯誤日誌 journalctl -u mysqld -f -p err # 跟蹤 Nginx 錯誤日誌 journalctl -u nginx -f -n 100
# Apache httpd -t # 或 apachectl configtest # Nginx nginx -t # MySQL (無專用語法檢查,啟動前可檢查權限/數據目錄) ls -ld /var/lib/mysql
systemctl show httpd --property=FragmentPath,ExecStart,Restart,Wants,Requires
| 坑點 | 現象 | 解決 |
|---|---|---|
| MySQL 服務名不一致 | CentOS 7 默認 mariadb,裝官方 RPM 可能是 mysqld | systemctl list-unit-files | grep -i mysql 確認實際服務名 |
| Nginx 非系統服務 (手動編譯安裝) | 無 systemd unit 文件,systemctl 找不到 | 手動創建 /etc/systemd/system/nginx.service 或用 /usr/local/nginx/sbin/nginx -s reload |
| 配置修改後 reload 無效 | 語法錯誤導致 reload 失敗,舊配置繼續生效 | **先跑語法檢查**,再 reload;reload 失敗會報錯並保持舊進程 |
| SELinux 導致啟動失敗 | journalctl 顯示 Permission denied / SELinux 拒絕 | setsebool -P httpd_can_network_connect 1 等,或暫時 setenforce 0 排查 |
| 端口衝突 (80/3306/443 被佔用) | 啟動失敗,日誌提示 Address already in use | ss -tlnp | grep :80 找佔用進程 kill 或改端口 |
#!/bin/bash
echo "=== $(date) Web Stack Health Check ==="
for svc in httpd mysqld nginx; do
if systemctl is-active --quiet $svc; then
echo "[OK] $svc is running"
else
echo "[FAIL] $svc is DOWN! Attempting restart..."
systemctl restart $svc
sleep 2
if systemctl is-active --quiet $svc; then
echo "[RECOVERED] $svc restarted successfully"
else
echo "[CRITICAL] $svc restart FAILED! Check journalctl -u $svc"
fi
fi
done
# 端口檢查
for port in 80 443 3306; do
ss -tln | grep -q ":$port " && echo "[OK] Port $port listening" || echo "[WARN] Port $port NOT listening"
done
加入 crontab 每 5 分鐘執行:*/5 * * * * /usr/local/bin/check_web_stack.sh >> /var/log/web_stack_check.log 2>&1
CentOS 7/8 運維核心:**拥抱 systemd**。掌握 systemctl 全家桶 + journalctl 日誌分析 + 配置語法預檢 三板斧,覆蓋 95% 的服務管理場景。把兼容命令扔進歷史垃圾堆,用原生姿勢才專業、才高效、才能在故障風暴中穩住陣腳。