Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

基於 xinetd 實現 Shell 腳本 HTTP 服務:為 HAProxy 提供 MySQL 健康檢查端點

編輯:Linux 教學

生產環境常用 HAProxy 負載均衡 MySQL,需實時感知後端實例存活狀態。本文展示如何利用 Linux 守護進程 xinetd (extended Internet daemon) 快速將一個 Shell 檢查腳本暴露為 HTTP 服務:HAProxy → xinetd 端口 → Shell 腳本 → 返回 HTTP 狀態碼與信息,無需編寫任何網絡代碼。

架構圖解

HAProxy (TCP/HTTP 健檢)
    │
    ▼
xinetd 監聽 9200 端口 (tcp)
    │
    ├─ 收到連接
    ├─ fork 執行 /root/mysql_check.sh
    ├─ 捕獲腳本 stdout
    └─ 直接作為 HTTP 響應返回

核心組件

1. MySQL 健康檢查腳本 /root/mysql_check.sh

#!/bin/bash
# 返回 HTTP 響應:狀態行 + 頭部 + 體
# 正常:HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nMySQL OK
# 異常:HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\n\r\nMySQL DOWN

if mysqladmin ping --silent; then
    echo -e "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nMySQL OK"
    exit 0
else
    echo -e "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\n\r\nMySQL DOWN"
    exit 1
fi

chmod +x /root/mysql_check.sh

2. xinetd 服務配置 /etc/xinetd.d/mysql_check

service mysql_check
{
    disable         = no
    port            = 9200
    socket_type     = stream
    protocol        = tcp
    wait            = no
    user            = root
    server          = /root/mysql_check.sh
    # server_args   =  # 腳本無需參數時留空
    log_on_failure  += USERID
}
  • wait = no:並發處理每個連接(fork 模式)
  • server:指定可執行腳本路徑

3. 註冊服務名(可選,便於管理)

echo "mysql_check 9200/tcp" >> /etc/services

4. 重啟 xinetd 生效

systemctl restart xinetd   # CentOS 7+/RHEL 7+
# 或
service xinetd restart     # CentOS 6

驗證測試

# nc 測試
nc localhost 9200
# 輸出:
# HTTP/1.1 200 OK
# Content-Type: text/plain
# MySQL OK

# telnet 測試
telnet localhost 9200

HAProxy 配置片段

backend mysql_cluster
    option httpchk GET / HTTP/1.1\r\nHost:\ localhost
    http-check expect status 200
    server mysql1 10.0.0.1:3306 check port 9200 inter 2000 rise 2 fall 3
    server mysql2 10.0.0.2:3306 check port 9200 inter 2000 rise 2 fall 3

HAProxy 定期向 9200 端口發送 HTTP 請求,根據返回狀態碼判斷 MySQL 實例健康狀態。

優缺點分析

優點缺點
零依賴,系統自帶 xinetd每請求 fork 進程,高併發下開銷大
腳本語言無關(bash/python/perl)無法處理 HTTPS/TLS
部署極簡,適合健檢等低頻場景響應頭需腳本手動構造,易出錯

生產建議

  • 健檢腳本務必設置超時機制(如 timeout 2 mysqladmin ...)防止卡死阻塞 xinetd。
  • 高頻/高併發場景建議改用 Go/Python 寫輕量 HTTP 服務(如 Flask/FastAPI + systemd)。
  • 通過 only_from 限制來源 IP,增強安全性。

總結

xinetd + Shell 腳本是**將任意命令行工具快速 HTTP 化**的經典技巧,極適合 HAProxy/MySQL/Redis 等中間件的健康檢查端點構建。理解「inetd 模式:連接即執行、輸出即響應」的核心模型,能靈活解決許多「不想寫服務端代碼」的場景。

Copyright © Windows教程網 All Rights Reserved