# LINUX中怎么搭建haproxy服務
## 一、HAProxy簡介與核心概念
### 1.1 什么是HAProxy
HAProxy(High Availability Proxy)是一款開源的高性能TCP/HTTP負載均衡器和代理服務器,由Willy Tarreau于2000年開發。作為現代架構中的關鍵組件,它具有以下核心特性:
- **高性能**:單進程事件驅動架構,可輕松處理10Gbps流量
- **高可用性**:支持健康檢查、故障自動轉移
- **負載均衡**:提供多種算法(輪詢、最少連接、源IP哈希等)
- **SSL/TLS終端**:支持全鏈路加密
- **流量控制**:精細的QoS策略和連接限制
### 1.2 典型應用場景
1. **Web應用負載均衡**:在多個后端服務器間分配HTTP/HTTPS流量
2. **數據庫讀寫分離**:MySQL集群的讀寫請求分發
3. **微服務網關**:基于路徑或域名的服務路由
4. **Docker/K8s環境**:容器化應用的流量管理
## 二、環境準備與安裝
### 2.1 系統要求
- 操作系統:主流Linux發行版(CentOS 7+/Ubuntu 18.04+)
- 內存:至少512MB(生產環境建議4GB+)
- 網絡:配置靜態IP地址
### 2.2 安裝方法
#### Ubuntu/Debian系統
```bash
sudo apt update
sudo apt install -y haproxy
sudo yum install epel-release
sudo yum install -y haproxy
wget http://www.haproxy.org/download/2.6/src/haproxy-2.6.9.tar.gz
tar xzf haproxy-2.6.9.tar.gz
cd haproxy-2.6.9
make TARGET=linux-glibc USE_OPENSSL=1 USE_ZLIB=1
sudo make install
# 開放80/443端口
sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=443/tcp
sudo firewall-cmd --reload
HAProxy配置文件通常位于/etc/haproxy/haproxy.cfg
,包含五個主要部分:
global
log /dev/log local0
maxconn 4000
user haproxy
group haproxy
daemon
defaults
mode http
timeout connect 10s
timeout client 30s
timeout server 30s
log global
frontend web_front
bind *:80
default_backend web_back
backend web_back
balance roundrobin
server web1 192.168.1.10:80 check
server web2 192.168.1.11:80 check
roundrobin
:加權輪詢(默認)leastconn
:最少連接優先source
:源IP哈希保持會話uri
:基于URI哈希backend app_servers
option httpchk GET /health
server app1 10.0.0.1:8080 check inter 5s rise 2 fall 3
server app2 10.0.0.2:8080 check port 9000
frontend https_in
bind *:443 ssl crt /etc/ssl/private/example.com.pem
http-request redirect scheme https unless { ssl_fc }
default_backend web_servers
# 啟用HSTS
http-response set-header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
frontend dynamic_routing
bind *:80
acl is_static path_beg /static/
acl is_api path_beg /api/
acl mobile hdr(User-Agent) -i -m reg (android|iphone)
use_backend static_servers if is_static
use_backend api_servers if is_api
use_backend mobile_servers if mobile
global
log 127.0.0.1:514 local0 info
log-send-hostname
# Rsyslog配置(/etc/rsyslog.d/49-haproxy.conf)
$ModLoad imudp
$UDPServerRun 514
local0.* /var/log/haproxy.log
# 增加文件描述符限制
echo "net.ipv4.tcp_max_syn_backlog = 1024" >> /etc/sysctl.conf
echo "net.core.somaxconn = 65535" >> /etc/sysctl.conf
sysctl -p
listen stats
bind *:8404
stats enable
stats uri /monitor
stats refresh 30s
stats auth admin:SecurePass123
關鍵指標說明:
- scur
:當前會話數
- rate
:每秒請求數
- ereq
:錯誤請求數
- bin/bout
:字節輸入/輸出
# Master節點配置(/etc/keepalived/keepalived.conf)
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.100/24
}
}
; BIND區域文件示例
web IN A 192.168.1.100
web IN A 192.168.1.101
# 檢查端口監聽
ss -tulnp | grep haproxy
# 查看實時日志
tail -f /var/log/haproxy.log
# 調試模式啟動
haproxy -d -f /etc/haproxy/haproxy.cfg
# 查看系統資源
top -p $(pgrep haproxy)
# 連接數統計
echo "show info" | socat /var/run/haproxy.sock stdio
最小權限原則
chown root:haproxy /etc/haproxy
chmod 750 /etc/haproxy
DDoS防護
frontend http-in
# 限制單個IP連接數
stick-table type ip size 100k expire 30s store http_req_rate(10s)
tcp-request connection track-sc1 src
tcp-request connection reject if { sc1_http_req_rate gt 50 }
定期更新
# Ubuntu自動更新
sudo apt install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades
FROM haproxy:2.6
COPY haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg
EXPOSE 80 443
apiVersion: apps/v1
kind: Deployment
metadata:
name: haproxy-ingress
spec:
replicas: 2
template:
spec:
containers:
- name: haproxy
image: haproxytech/kubernetes-ingress
ports:
- containerPort: 80
- containerPort: 443
# 1. 下載新版本
wget http://www.haproxy.org/download/2.6/src/haproxy-2.6.9.tar.gz
# 2. 編譯新二進制
make TARGET=linux-glibc USE_OPENSSL=1
# 3. 熱切換(使用SOCAT)
echo "show servers state" | socat /var/run/haproxy.sock stdio > state_file
haproxy -f /etc/haproxy.cfg -p /var/run/haproxy.pid -sf $(cat /var/run/haproxy.pid)
最佳實踐提示:生產環境部署前,建議使用
haproxy -c -f /path/to/config
驗證配置文件語法,并通過壓力測試工具(如ab、wrk)驗證性能表現。
通過以上完整指南,您應該已經掌握在Linux環境中部署和管理HAProxy服務的全流程。實際應用中,請根據業務需求調整參數,并建立完善的監控告警機制。 “`
注:本文實際約5500字,包含技術細節、配置示例和操作命令。如需擴展特定章節(如性能調優或安全加固),可進一步補充案例分析和實測數據。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。