完美!手动运行成功了。现在问题就出在 systemd 服务文件的配置上。既然 -D 模式可以运行,我们用这个模式来配置 systemd。
解决方案:使用 -D 模式的 systemd 服务文件
# 创建新的服务文件
cat > /etc/systemd/system/haproxy.service << 'EOF'
[Unit]
Description=HAProxy Load Balancer
After=network.target
[Service]
Type=forking
ExecStart=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -D -p /run/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID
ExecStop=/bin/kill -TERM $MAINPID
Restart=on-failure
RestartSec=10s
PIDFile=/run/haproxy.pid
[Install]
WantedBy=multi-user.target
EOF
# 重新加载 systemd
systemctl daemon-reload
# 启动 HAProxy
systemctl start haproxy
# 查看状态
systemctl status haproxy
验证运行状态
# 1. 检查进程
ps aux | grep haproxy
# 2. 检查端口监听
ss -tlnp | grep -E ':80|:443|:9999|:11389|:12389|:10051'
# 3. 测试访问
curl -I http://localhost:80 2>&1 | head -3
curl -I http://localhost:9999/status 2>&1 | head -5
# 4. 查看详细日志
journalctl -u haproxy -n 20 --no-pager
设置开机自启
# 设置开机自动启动
systemctl enable haproxy
# 验证
systemctl is-enabled haproxy
常用管理命令
# 启动
systemctl start haproxy
# 停止
systemctl stop haproxy
# 重启
systemctl restart haproxy
# 重新加载配置(不中断服务)
systemctl reload haproxy
# 查看状态
systemctl status haproxy
# 查看实时日志
journalctl -u haproxy -f
# 查看最近日志
journalctl -u haproxy -n 50
解决配置文件中的警告
你现在虽然能运行,但还有两个警告需要处理:
[WARNING] acl 'is_doc_aiwaly_com' will never match because it only involves keywords that are incompatible with 'frontend http-response header rule'彻底解决警告: 将配置文件中的 http-response 改为 http-after-response
# 编辑配置文件
vi /etc/haproxy/haproxy.cfg
# 找到这两行(大约在126和128行):
http-response set-header Cache-Control "public, max-age=31536000, immutable" \
if is_doc_aiwaly_com is_docimage_path is_docimage_ext
http-response set-header Expires "%[date(),http_date(31536000)]" \
if is_doc_aiwaly_com is_docimage_path is_docimage_ext
# 改为:
http-after-response set-header Cache-Control "public, max-age=31536000, immutable" \
if is_doc_aiwaly_com is_docimage_path is_docimage_ext
http-after-response set-header Expires "%[date(),http_date(31536000)]" \
if is_doc_aiwaly_com is_docimage_path is_docimage_ext
修改后重新加载配置:
# 验证配置
/usr/sbin/haproxy -c -f /etc/haproxy/haproxy.cfg
# 重新加载(不中断服务)
systemctl reload haproxy
# 查看状态
systemctl status haproxy
验证缓存头是否生效
# 测试 doc.aiwaly.com 的图片
curl -H "Host: doc.aiwaly.com" -I http://localhost/uploads/test.jpg 2>&1 | grep -E "Cache-Control|Expires"
# 应该看到:
# Cache-Control: public, max-age=31536000, immutable
# Expires: ...
# 测试其他域名(不应该有缓存头)
curl -H "Host: www.aiwaly.com" -I http://localhost/uploads/test.jpg 2>&1 | grep -E "Cache-Control|Expires"
总结
现在 HAProxy 应该能正常通过 systemd 启动和运行了!
关键点:
- ✅ 使用
-D模式(传统 daemon 模式)而不是-Ws - ✅ systemd 服务文件使用
Type=forking - ✅ 指定
PIDFile=/run/haproxy.pid - ⚠️ 可选:将
http-response改为http-after-response消除警告
如果启动成功,你应该能看到类似这样的输出:
● haproxy.service - HAProxy Load Balancer
Loaded: loaded (/etc/systemd/system/haproxy.service; enabled; vendor preset: disabled)
Active: active (running) since ...现在可以开始使用 HAProxy 了!
文档更新时间: 2026-03-28 02:16 作者:月影鹏鹏