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

Squid 3 反向代理加速架構部署全流程:從編譯安裝到生產級配置調優

編輯:Linux 教學

架構定位:Squid 作為反向代理(HTTP 加速器)

正向代理:Client → Proxy → Internet(代理客戶端上網)。
反向代理:Client → Squid → Backend Web Server(代理伺服器對外服務,對客戶端透明)。

Squid 3.x 透過 http_port ... accel / vhost / vport 模式,實現:

  • 靜態資源緩存(減輕後端壓力、降低延遲)
  • 連接複用/管理(後端短連接、前端長連接)
  • SSL 終結(可選)
  • 負載均衡/故障轉移(cache_peer 輪詢/權重)

一、編譯安裝(生產級參數)

# 1. 依賴
yum install -y gcc gcc-c++ make openssl-devel libtool autoconf automake \
               libxml2-devel libcap-devel pam-devel

# 2. 下載穩定版(以 3.5.28 為例,LTS 分支)
wget https://www.squid-cache.org/Versions/v3/3.5/squid-3.5.28.tar.xz
tar -xJf squid-3.5.28.tar.xz
cd squid-3.5.28

# 3. 配置編譯參數
./configure --prefix=/usr/local/squid \
            --enable-http-violations \
            --enable-ssl-crtd \
            --with-openssl \
            --enable-epoll \
            --enable-async-io \
            --enable-storeio="ufs,aufs,diskd,rock" \
            --enable-icmp \
            --enable-htcp \
            --enable-cache-digests \
            --enable-wccpv2 \
            --enable-esi \
            --enable-ecap \
            --with-default-user=squid \
            --with-logdir=/var/log/squid \
            --with-pidfile=/var/run/squid.pid \
            --enable-large-cache-files \
            --enable-linux-netfilter \
            --enable-pf-transparent \
            --disable-arch-native

# 4. 編譯安裝
make -j$(nproc)
make install

# 5. 建立用戶、目錄、權限
useradd -r -s /bin/false -d /usr/local/squid squid
mkdir -p /usr/local/squid/var/cache /usr/local/squid/var/logs
chown -R squid:squid /usr/local/squid/var
chmod 750 /usr/local/squid/var/cache /usr/local/squid/var/logs

# 6. 初始化緩存目錄
/usr/local/squid/sbin/squid -z
# 輸出 "Creating Swap Directories" 即成功

二、systemd 服務單元 /etc/systemd/system/squid.service

[Unit]
Description=Squid HTTP Proxy/Caching Server
After=network.target
Documentation=man:squid(8)

[Service]
Type=forking
User=squid
Group=squid
ExecStartPre=/usr/local/squid/sbin/squid -k parse
ExecStart=/usr/local/squid/sbin/squid -YC -f /usr/local/squid/etc/squid.conf
ExecReload=/usr/local/squid/sbin/squid -k reconfigure
ExecStop=/usr/local/squid/sbin/squid -k shutdown
TimeoutSec=30
LimitNOFILE=500000
LimitNPROC=500000
PrivateTmp=true
ProtectSystem=full
ProtectHome=true

[Install]
WantedBy=multi-user.target

三、核心配置 /usr/local/squid/etc/squid.conf(生產級模板)

# ===== 基礎身份 =====
visible_hostname squid-proxy-01
cache_mgr admin@example.com

# ===== 監聽埠:反向代理模式 =====
# 80 埠透明加速(需 root 權限或 CAP_NET_BIND_SERVICE)
# 建議:Nginx 監聽 80/443 終結 SSL,轉發給 Squid 3128
http_port 3128 accel vhost vport defaultsite=backend.example.com

# ===== 記憶體緩存 =====
cache_mem 4 GB
maximum_object_size_in_memory 256 KB
memory_replacement_policy heap GDSF

# ===== 磁碟緩存(建議獨立掛載點、SSD)=====
cache_dir ufs /cache1 20000 16 256
cache_dir ufs /cache2 20000 16 256
cache_swap_low 85
cache_swap_high 95

# ===== 對象大小限制 =====
minimum_object_size 0 KB
maximum_object_size 128 MB   # 視業務調整,視頻/下載站需調大

# ===== 替換策略 =====
cache_replacement_policy heap LFUDA

# ===== 後端上游定義 =====
# 單後端
cache_peer 10.0.1.10 parent 80 0 no-query originserver name=web01
# 多後端負載均衡(輪詢)
cache_peer 10.0.1.10 parent 80 0 no-query originserver weight=2 name=web01
cache_peer 10.0.1.11 parent 80 0 no-query originserver weight=1 name=web02

# 域名路由
cache_peer_domain web01 web.example.com
cache_peer_domain web02 api.example.com

# 允許所有訪問(實際應配合 ACL 限制)
cache_peer_access web01 allow all
cache_peer_access web02 allow all

# ===== 客戶端存取控制 =====
acl all src all
http_access allow all

# ===== 緩存規則:動態不緩存、靜態緩存 =====
acl dynamic urlpath_regex -i \.php$ \.jsp$ \.asp$ \.aspx$ \.do$ \.action$ \? .*api.* .*ajax.*
cache deny dynamic

# 靜態資源強制緩存(配合後端 Cache-Control)
refresh_pattern -i \.(jpg|jpeg|png|gif|ico|css|js|woff2?|svg|mp4|webm|pdf)$ 1440 90% 10080 override-expire ignore-no-cache ignore-private
refresh_pattern -i \.(html|htm|xml|json)$ 60 50% 1440

# ===== 日誌格式與輸出 =====
logformat combined %>a %ui %un [%tl] "%rm %ru HTTP/%rv" %Hs %h" "%{User-Agent}>h" %Ss:%Sh
access_log /usr/local/squid/var/logs/access.log combined
cache_log /usr/local/squid/var/logs/cache.log
cache_store_log none

# ===== 進程身份 =====
cache_effective_user squid
cache_effective_group squid

# ===== 錯誤頁面本地化 =====
error_directory /usr/local/squid/share/errors/Chinese_Traditional

# ===== FD 與網路優化 =====
max_filedescriptors 500000
pinger_enable off
dns_v4_first on
ipcache_size 10240
ipcache_low 90
ipcache_high 95
fqdncache_size 10240

四、後端 Web Server 配合調整

  1. 修改監聽埠避開 80:Apache/Nginx 改監聽 8080(或 81),Squid 監聽 80/3128。
  2. 輸出標準緩存頭:
    # Nginx 靜態資源
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2?|svg)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
    
    # 動態頁面由應用輸出 Cache-Control
  3. 關閉後端 Keep-Alive(可選):Squid 負責前端長連接,後端短連接釋放更快:proxy_http_version 1.1; proxy_set_header Connection "";

五、防火牆、SELinux、啟動驗證

# 防火牆
firewall-cmd --permanent --add-port=3128/tcp
firewall-cmd --reload

# SELinux
setsebool -P squid_connect_any on
semanage port -a -t squid_port_t -p tcp 3128  # 若用非標準埠

# 啟動
systemctl daemon-reload
systemctl enable squid
systemctl start squid

# 驗證
curl -I https://localhost:3128/ -H "Host: web.example.com"
# 應見 X-Cache: MISS/HIT from squid-proxy-01

六、常見問題與調優清單

現象排查方向解決
啟動失敗 "cannot bind port 80"權限不足用 3128 + Nginx 前置、或 setcap CAP_NET_BIND_SERVICE=+ep /usr/local/squid/sbin/squid
緩存不生效(全 MISS)後端無 Cache-Control、Vary 頭過度、Squid refresh_pattern 不匹配檢查後端回應頭、簡化 Vary、調整 refresh_pattern
命中率低動態/靜態未拆分、大文件擠佔緩存、上游頻繁 Set-Cookie業務拆分、分叢集、ignore-no-cache、忽略 Set-Cookie
磁碟 IO 瓶頸cache_dir 單盤、ufs 效能差多盤分散、改用 rock/storeio、SSD、調大 cache_mem
FD 耗盡max_filedescriptors 過小、系統 fs.file-max 限制調大 Squid 與系統 FD 限制

七、監控與日誌分析

  • SNMP:--enable-snmp + snmp_port 3401,配合 squid_exporter → Prometheus + Grafana。
  • 存取日誌分析:GoAccess、Sarg、ELK/EFK、ClickHouse。
  • 關鍵指標:RHR、BHR、Service Time (HIT/MISS)、Swap Usage、FD Usage、CPU/MEM、上游健康狀態。

總結

Squid 3 反向代理部署的核心在於:正確的編譯參數(epoll/async-io/rock)、反向代理模式 http_port 配置、後端緩存頭配合、動靜分離緩存策略、磁碟佈局與 FD 優化。配合 Nginx 前置終結 SSL、做 WAF、統一標頭治理,構建「Nginx (Edge) → Squid (Cache) → Backend (App)」三層加速架構,可將靜態資源命中率推至 95%+,後端負載降低 80%+。

Copyright © Windows教程網 All Rights Reserved