單台 Web 服務器性能有限,傳統方案是 DNS 輪詢(Round-Robin DNS)分發請求到多台后端,但 DNS 無法感知後端健康狀態、無法緩存靜態資源。引入 Squid 反向代理 作為前端統一入口,結合 DNS 輪詢多個 Squid 節點,實現「全局負載均衡 + 本地緩存加速 + 健康檢查」三層架構。本文詳解部署全流程。
用戶
│
▼
DNS (Round-Robin) ──→ squid1.example.com (IP1)
──→ squid2.example.com (IP2)
│
▼
Squid 反向代理叢集 (前端緩存、ACL、SSL 終結)
│
├─→ 後端 Web 叢集 (內網 IP:192.168.1.10, 192.168.1.18)
│ ├─ Web1 (真實內容源)
│ └─ Web2 (真實內容源)
│
└─→ 透明代理輔助 (transproxy/iptables) 可選
cd /usr/local/src
wget https://www.squid-cache.org/Versions/v2/2.2/squid-2.2.STABLE5-src.tar.gz
tar zxvf squid-2.2.STABLE5-src.tar.gz
cd squid-2.2.STABLE5
./configure --prefix=/usr/local/squid
make
make install
安裝後目錄結構:/usr/local/squid/{etc,bin,logs}。
# 內存緩存
cache_mem 256 MB
# 磁盤緩存
cache_dir ufs /usr/local/squid/cache 1000 16 256
# ACL:允許後端 Web 服務器 IP 訪問代理(反向代理場景實為允許所有客戶端)
acl all src 0.0.0.0/0
http_access allow all
# 反向代理核心參數
httpd_accel_host web1.example.com
httpd_accel_host web2.example.com
httpd_accel_port 80
httpd_accel_with_proxy off # 關閉正向代理功能
httpd_accel_uses_host_header on # 使用 Host 頭路由到對應後端
# 管理員郵箱
cache_mgr admin@example.com
# 可見主機名
visible_hostname squid-proxy-1
/usr/local/squid/bin/squid -z
/usr/local/squid/bin/squid -NCd1
# 看到 Ready to serve requests. 即成功
# 正式運行
/usr/local/squid/bin/squid
外部 DNS 將 web1.example.com 解析到 Squid 公網 IP,但 Squid 內部需解析到後端內網 IP,避免流量繞回公網。
| 域名 | 外部 DNS (公網) | 內部 DNS (Squid 所在機器 /etc/hosts 或內網 DNS) |
|---|---|---|
| web1.example.com | 202.99.157.10 (Squid 公網 IP) | 192.168.1.10 (Web1 內網 IP) |
| web2.example.com | 202.99.157.18 (Squid 公網 IP) | 192.168.1.18 (Web2 內網 IP) |
192.168.1.10 web1.example.com
192.168.1.18 web2.example.com
或搭建內網 DNS(BIND/Unbound/dnsmasq)統一管理。
eth0:0、eth0:1。transproxy 監聽 81 端口,配合 ipchains/iptables 將 80 端口流量 REDIRECT 到 81,再由 transproxy 轉發給 Squid 3128 端口。在權威 DNS 為 proxy.example.com 配置多條 A 記錄:
proxy.example.com. IN A 202.99.157.10
proxy.example.com. IN A 202.99.157.18
proxy.example.com. IN A 202.99.157.25
curl -x https://squid-ip:3128 https://web1.example.com/ 應返回後端內容。tail -f /usr/local/squid/logs/access.log 觀察 TCP_HIT/TCP_MEM_HIT。curl 後端,失敗則修改 squid.conf ACL 並 squid -k reconfigure。現代 Squid 4+ 支持 cache_peer + healthcheck。| 方案 | 優點 | 缺點 |
|---|---|---|
| DNS 輪詢 + Squid 反向代理 | 成本低、標準協議、緩存加速 | 無健康檢查、TTL 延遲、會話保持難 |
| Nginx 反向代理 + upstream | 原生健檢、權重、會話保持、SSL 終結、動態重載 | 無內建對象緩存(需 ngx_cache 或 Varnish) |
| HAProxy + Varnish | 四/七層負載均衡專業級、高性能緩存 | 架構複雜、組件多 |
| 云負載均衡 | 全托管、健檢、自動擴縮容、DDoS 防護 | 成本高、廠商鎖定 |
DNS 輪詢分發流量到多個 Squid 反向代理節點,Squid 內部通過 /etc/hosts 或內網 DNS 解析後端真實內網 IP,實現「全局分發 + 本地緩存 + 內網直連」的經典負載均衡架構。雖然現代生產環境多遷移至 Nginx/HAProxy + 云負載均衡,但理解 Squid 反向代理的 httpd_accel_* 參數、內外 DNS 分離、透明代理輔助機制,對維護老系統、設計混合雲網關仍具參考價值。