Ubuntu Load Balancing will solve your problem of High availability and optimal performance for modern PHP applications. HAProxy (High Availability Proxy) has emerged as a leading open-source Ubuntu Load Balancing solution, particularly excelling in HTTP traffic distribution and session management. This comprehensive guide explores implementing HAProxy for PHP applications, with a focus on practical configuration and best practices.
In this era, we automate some tasks, including server maintenance. To maintain our application effectively, we also need to ensure proper load balancing for optimal performance.”
Table of Contents
What is HAProxy for Ubuntu Load Balancing?
HAProxy is an open-source Ubuntu Load Balancing and proxy server designed to improve web application reliability through distributed computing. It excels in:
- TCP and HTTP load balancing
- Session persistence management
- Layer 7 processing
- Real-time monitoring
- High-performance traffic distribution
System Requirements & Architecture
To implement HAProxy effectively, you’ll need:
- Three Ubuntu servers:
- One dedicated load balancer (HAProxy server)
- Two or more backend web servers running PHP applications
- Private network connectivity between servers
- Root or sudo access on all servers
- Basic understanding of networking concepts
Installation & Basic Setup
Installing HAProxy
First, update your package manager and install HAProxy. These commands will ensure you have the latest version:
sudo apt-get update
sudo apt-get install haproxy
Enable HAProxy to start automatically when your system boots. Add this line to /etc/default/haproxy:
ENABLED=1
Core Configuration
Create a new configuration file at /etc/haproxy/haproxy.cfg. This basic configuration sets up logging, connection limits, and timeouts:
global
log /dev/log local0
log /dev/log local1 notice
maxconn 4096 # Maximum number of concurrent connections
user haproxy # User that will run HAProxy
group haproxy # Group that will run HAProxy
daemon # Run in background mode
defaults
log global
mode http # Layer 7 mode (HTTP)
option httplog # Enable HTTP logging
option dontlognull # Don't log null connections
retries 3 # Number of retries if connection fails
timeout connect 5000 # Maximum time to wait for connection
timeout client 10000 # Client inactivity timeout
timeout server 10000 # Server inactivity timeout
frontend php_frontend
bind *:80 # Listen on all IPs on port 80
default_backend php_backend
backend php_backend
balance roundrobin # Use round-robin algorithm
option httpchk HEAD / HTTP/1.1\r\nHost:\ localhost # Health check
server web1 10.0.0.1:80 check # First backend server
server web2 10.0.0.2:80 check # Second backend server
Advanced Configuration for PHP Applications
Session Persistence
Here are two methods to maintain session persistence, crucial for PHP applications:
1. Cookie-based persistence – This method adds a cookie to track which server handled the initial request:
backend php_backend
balance roundrobin
cookie SERVERID insert indirect nocache # Add a cookie for tracking
server web1 10.0.0.1:80 check cookie s1 # Assign cookie value 's1'
server web2 10.0.0.2:80 check cookie s2 # Assign cookie value 's2'
2. Source IP persistence – This method ensures requests from the same IP go to the same server:
backend php_backend
balance source # Use source IP for persistence
hash-type consistent # Maintain consistency during server changes
server web1 10.0.0.1:80 check
server web2 10.0.0.2:80 check
Health Checks
This configuration implements health monitoring for your backend servers. The check sends HTTP requests to verify server health:
backend php_backend
option httpchk GET /health.php HTTP/1.1\r\nHost:\ localhost
server web1 10.0.0.1:80 check inter 5000 rise 2 fall 3 # Check every 5 seconds
server web2 10.0.0.2:80 check inter 5000 rise 2 fall 3 # Require 2 successes to enable
Create this health check file (health.php) on each backend server to verify critical services:
<?php
// Basic health check script to verify database and session functionality
$healthy = true;
// Check database connectivity
try {
$pdo = new PDO("mysql:host=localhost;dbname=myapp", "user", "password");
} catch (PDOException $e) {
$healthy = false;
}
// Check session handling
if (!session_start()) {
$healthy = false;
}
// Return appropriate status code - 200 for healthy, 503 for unhealthy
http_response_code($healthy ? 200 : 503);
echo $healthy ? 'OK' : 'ERROR';
Monitoring & Statistics
Enable Statistics Page
Add this configuration to enable a web-based statistics dashboard. Access it at http://your-server:8404/stats:
listen stats
bind *:8404 # Port for accessing stats
stats enable # Enable stats page
stats uri /stats # URL path for stats
stats refresh 10s # Auto-refresh every 10 seconds
stats admin if LOCALHOST # Allow admin actions from localhost
stats auth admin:securepassword # Basic authentication
Logging Configuration
Configure rsyslog to separate HAProxy logs into their own file:
# Add to /etc/rsyslog.d/haproxy.conf
if ($programname == 'haproxy') then -/var/log/haproxy.log
& stop
Performance Optimization
Connection Handling
Optimize connection settings for better performance and resource usage:
frontend php_frontend
bind *:80
option http-server-close # Close server connection but keep client alive
option forwardfor # Add X-Forwarded-For header
timeout client 30s # Client timeout
timeout http-request 5s # Request timeout
timeout http-keep-alive 2s # Keep-alive timeout
SSL Termination
Configure SSL termination to handle HTTPS traffic. Place your SSL certificate at the specified path:
frontend php_frontend
bind *:443 ssl crt /etc/ssl/certs/combined.pem # SSL certificate path
option httplog
option forwardfor # Forward client IP
http-request set-header X-Forwarded-Proto https # Add protocol header
default_backend php_backend
Testing & Validation
Create this test script (test.php) on backend servers to verify load balancing and session handling:
<?php
// Test script to verify load balancer configuration
session_start();
// Display server information for debugging
echo "Server IP: " . $_SERVER['SERVER_ADDR'] . "\n";
echo "Client IP: " . $_SERVER['REMOTE_ADDR'] . "\n";
echo "Session ID: " . session_id() . "\n";
// Test session persistence by counting visits
if (!isset($_SESSION['visits'])) {
$_SESSION['visits'] = 0;
}
$_SESSION['visits']++;
echo "Visit count: " . $_SESSION['visits'] . "\n";
Common Problems & Fixes
Session Loss
- Check cookie settings
- Check session storage
- Private network connectivity
Uneven Load
- Check balancing algorithm
- Check server weights
- Check server health
Performance
- Adjust timeout
- Monitor connections
- Check backend server resources
Best Practices
Security
- Strong auth on stats page
- Proper firewall rules
- Regular security updates
- SSL/TLS config
Monitoring
- Regular log analysis
- Performance metrics
- Health checks
- Resource usage
Maintenance
- Regular backups
- Documented updates
- Testing environment for changes
- Disaster recovery plan
HAProxy is a great Ubuntu Load Balancing tool for PHP applications. Follow the configurations and best practices in this guide, and you’ll have high availability, good performance, and session handling for your web apps.
Remember: Load balancer configuration is not a one-size-fits-all solution. Monitor, test, and adjust according to your use case.