如何配置HAProxy实现Tomcat请求从localhost:8080/path转发至1.2.3.4:8080/path
HAProxy Configuration to Forward /path Requests to Remote Tomcat
Got it, let's walk through exactly how to set up HAProxy to forward requests coming to localhost:8080/path (and its subpaths) to 1.2.3.4:8080/path. The core here is preserving the request path while routing, which is easy with HAProxy's ACL and backend directives.
Here's a complete, ready-to-use configuration example (typically saved at /etc/haproxy/haproxy.cfg):
global log /dev/log local0 log /dev/log local1 notice chroot /var/lib/haproxy stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners stats timeout 30s user haproxy group haproxy daemon defaults log global mode http option httplog option dontlognull timeout connect 5000 timeout client 50000 timeout server 50000 frontend tomcat_path_frontend bind *:8080 # Match requests starting with /path (covers /path, /path/sub, etc.) acl matches_path path_beg /path # Route matching requests to our backend use_backend remote_tomcat if matches_path backend remote_tomcat # Define the target Tomcat server server tomcat_node 1.2.3.4:8080 check # Pass the client's real IP to Tomcat (optional but useful for logs) option forwardfor
Key Breakdown of the Configuration:
- Global Section: These are base HAProxy settings (logging, permissions, daemon mode) – you can leave these as-is unless you have specific infrastructure needs.
- Defaults Section: Sets universal HTTP proxy rules: enables HTTP logging, sets reasonable timeouts for connections, clients, and servers.
- Frontend:
bind *:8080: Tells HAProxy to listen on all network interfaces at port 8080 (solocalhost:8080will hit this frontend).acl matches_path path_beg /path: Creates an Access Control List (ACL) that triggers when the request path starts with/path. This matches both/pathand any subpaths like/path/apior/path/page. If you need exact match only (just/path, no subpaths), replacepath_begwithpath /path.use_backend remote_tomcat if matches_path: Routes any request matching the ACL to theremote_tomcatbackend.
- Backend:
server tomcat_node 1.2.3.4:8080 check: Defines the target Tomcat server. Thecheckflag enables health checks to ensure HAProxy only sends traffic to the server if it's online.option forwardfor: Adds anX-Forwarded-Forheader to the request, so Tomcat can log the original client IP instead of HAProxy's IP.
To Apply the Configuration:
- Save the config to
/etc/haproxy/haproxy.cfg(adjust path if your distro uses a different location). - Test the config for syntax errors:
haproxy -c -f /etc/haproxy/haproxy.cfg - Restart HAProxy to apply changes:
- For systemd-based systems:
systemctl restart haproxy - For SysVinit:
service haproxy restart
- For systemd-based systems:
That's it! Now any request to localhost:8080/path (or its subpaths) will be forwarded to 1.2.3.4:8080/path with the full path preserved.
内容的提问来源于stack exchange,提问作者user5123481566
相关产品推荐
相关产品推荐

