From 06d1d447f84a1504d4b767236f4fc8285dda1c1c Mon Sep 17 00:00:00 2001 From: Joao Gilberto Magalhaes Date: Thu, 27 Nov 2025 19:02:39 -0500 Subject: [PATCH] Add comprehensive Docker, Kubernetes, Swarm, and static configuration examples - Added detailed `README.md` files with step-by-step instructions for Docker Compose, Kubernetes, Swarm, and static configuration examples. - Included use cases for SSL setup, Let's Encrypt integration, load balancing, and advanced features like plugins and path-based routing. - Documented environment variables, service labels, and troubleshooting tips across all examples. - Enhanced examples with clear testing guidelines, SSL certificate generation steps, and debugging workflows. --- examples/docker/README.md | 231 ++++++++++++ examples/kubernetes/README.md | 423 ++++++++++++++++++++++ examples/static/README.md | 462 ++++++++++++++++++++++++ examples/swarm/README.md | 650 ++++++++++++++++++++++++++++++++++ 4 files changed, 1766 insertions(+) create mode 100644 examples/docker/README.md create mode 100644 examples/kubernetes/README.md create mode 100644 examples/static/README.md create mode 100644 examples/swarm/README.md diff --git a/examples/docker/README.md b/examples/docker/README.md new file mode 100644 index 0000000..6a6f927 --- /dev/null +++ b/examples/docker/README.md @@ -0,0 +1,231 @@ +# Docker Compose Examples + +This directory contains various Docker Compose examples demonstrating different EasyHAProxy configurations. + +## Examples Overview + +### 1. Basic Configuration (`docker-compose.yml`) + +**What it demonstrates:** +- Basic SSL setup with two virtual hosts +- SSL redirect (HTTP → HTTPS) +- Custom SSL certificates (embedded and file-based) +- HAProxy stats interface + +**Features:** +- `host1.local`: SSL certificate embedded as base64 in labels +- `host2.local`: SSL certificate loaded from file (`host2.local.pem`) +- Automatic HTTP to HTTPS redirect +- Stats available at port 1936 + +**Usage:** +```bash +docker compose up -d +``` + +**Test:** +```bash +# Test HTTPS +curl -k -H "Host: host1.local" https://127.0.0.1/ +curl -k -H "Host: host2.local" https://127.0.0.1/ + +# Test HTTP redirect +curl -I -H "Host: host1.local" http://127.0.0.1 +# Should return: HTTP/1.1 301 Moved Permanently + +# View SSL certificate +openssl s_client -showcerts -connect 127.0.0.1:443 -servername host1.local +``` + +**Access stats:** +- URL: http://localhost:1936 +- Username: `admin` +- Password: `password` + +--- + +### 2. ACME/Let's Encrypt (`docker-compose-acme.yml`) + +**What it demonstrates:** +- Automatic SSL certificate generation using Let's Encrypt +- HTTP-01 ACME challenge +- Certificate persistence + +**Requirements:** +- Public IP address pointing to your machine +- Open ports 80 and 443 in firewall +- Valid domain name + +**Configuration:** +```yaml +EASYHAPROXY_CERTBOT_EMAIL: user@example.com # Change this! +easyhaproxy.http.certbot: true # Enable certbot +``` + +**Usage:** +```bash +# Edit docker-compose-acme.yml and set: +# - EASYHAPROXY_CERTBOT_EMAIL to your email +# - easyhaproxy.http.host to your domain + +docker compose -f docker-compose-acme.yml up -d +``` + +**Certificate storage:** +Certificates are persisted in `./certs/certbot/` to avoid re-challenges on restart. + +--- + +### 3. Multiple Containers with Load Balancing (`docker-compose-multi-containers.yml`) + +**What it demonstrates:** +- Multiple containers behind single domain +- Load balancing with round-robin +- Domain redirect functionality + +**Features:** +- 2 replicas of nginx container +- Load balancing across replicas +- Domain redirect: `google.helloworld.com` → `www.google.com` + +**Usage:** +```bash +docker compose -f docker-compose-multi-containers.yml up -d +``` + +**Test:** +```bash +# Test load balancing (hostname changes between containers) +curl -H "Host: www.helloworld.com" localhost:19901 +# Response: f6d8d45b7411 +curl -H "Host: www.helloworld.com" localhost:19901 +# Response: 59b213cb8592 + +# Test redirect +curl -I -H "Host: google.helloworld.com" localhost:19901 +# Should redirect to: www.google.com/ +``` + +--- + +### 4. Changed Label Prefix (`docker-compose-changed-label.yml`) + +**What it demonstrates:** +- Using custom label prefix instead of default `easyhaproxy` +- Useful for running multiple EasyHAProxy instances + +**Configuration:** +```yaml +environment: + EASYHAPROXY_LABEL_PREFIX: myproxy +``` + +**Container labels:** +```yaml +labels: + myproxy.http.host: example.com + myproxy.http.port: 80 +``` + +--- + +### 5. Portainer Integration (`docker-compose-portainer.yml`) + +**What it demonstrates:** +- Running Portainer behind EasyHAProxy +- Real-world application example + +**Access Portainer:** +- URL: http://portainer.local (add to `/etc/hosts` or use real DNS) +- First time: Create admin user + +--- + +### 6. Portainer + App Example (`docker-compose-portainer-app-example.yml`) + +**What it demonstrates:** +- Multiple applications behind EasyHAProxy +- Portainer + custom app setup + +--- + +## Common Configuration Options + +### Environment Variables (HAProxy Container) + +| Variable | Description | Default | +|-----------------------------|---------------------------|----------| +| `EASYHAPROXY_DISCOVER` | Discovery mode | `docker` | +| `EASYHAPROXY_SSL_MODE` | SSL mode (loose/strict) | `strict` | +| `EASYHAPROXY_CERTBOT_EMAIL` | Email for Let's Encrypt | - | +| `HAPROXY_CUSTOMERRORS` | Enable custom error pages | `false` | +| `HAPROXY_USERNAME` | Stats username | - | +| `HAPROXY_PASSWORD` | Stats password | - | +| `HAPROXY_STATS_PORT` | Stats port | `1936` | + +### Container Labels + +| Label | Description | Example | +|---------------------------------|----------------------|---------------| +| `easyhaproxy.http.host` | Virtual host domain | `example.com` | +| `easyhaproxy.http.port` | External port | `80` | +| `easyhaproxy.http.localport` | Container port | `8080` | +| `easyhaproxy.http.redirect_ssl` | Force HTTPS redirect | `true` | +| `easyhaproxy.http.certbot` | Enable Let's Encrypt | `true` | +| `easyhaproxy.https.ssl` | Enable SSL | `true` | +| `easyhaproxy.https.sslcert` | Base64 SSL cert | `LS0t...` | + +For complete documentation, see [Container Labels](../../docs/container-labels.md). + +## Tips + +1. **Local Testing with Fake Domains:** + Add entries to `/etc/hosts`: + ``` + 127.0.0.1 host1.local host2.local portainer.local + ``` + +2. **Viewing Logs:** + ```bash + docker compose logs -f haproxy + ``` + +3. **Reloading Configuration:** + EasyHAProxy automatically detects changes. Watch logs for reload events. + +4. **Generating Test SSL Certificates:** + ```bash + openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ + -keyout host.key -out host.crt \ + -subj "/CN=host1.local" + cat host.crt host.key > host.pem + ``` + +5. **Base64 Encoding SSL Certificate:** + ```bash + base64 -w 0 host.pem + ``` + +## Troubleshooting + +**Issue:** Container not detected +- Check labels are correct (prefix, syntax) +- Verify Docker socket is mounted +- Check logs: `docker compose logs haproxy` + +**Issue:** SSL not working +- Verify certificate format (cert + key in same PEM file) +- Check certificate matches domain +- Verify SSL mode (`loose` vs `strict`) + +**Issue:** Let's Encrypt fails +- Ensure ports 80/443 are publicly accessible +- Verify domain DNS points to your IP +- Check certbot logs in HAProxy container + +## Further Reading + +- [Docker Configuration Guide](../../docs/docker.md) +- [Container Labels Reference](../../docs/container-labels.md) +- [ACME/Let's Encrypt Guide](../../docs/acme.md) +- [Environment Variables](../../docs/environment-variable.md) diff --git a/examples/kubernetes/README.md b/examples/kubernetes/README.md new file mode 100644 index 0000000..0718de9 --- /dev/null +++ b/examples/kubernetes/README.md @@ -0,0 +1,423 @@ +# Kubernetes Examples + +This directory contains Kubernetes manifest examples demonstrating EasyHAProxy ingress configurations. + +## Prerequisites + +1. **EasyHAProxy installed in your cluster:** + ```bash + kubectl create namespace easyhaproxy + kubectl apply -f https://raw.githubusercontent.com/byjg/docker-easy-haproxy/4.6.0/deploy/kubernetes/easyhaproxy-daemonset.yml + ``` + +2. **Label the node where EasyHAProxy will run:** + ```bash + kubectl label nodes "easyhaproxy/node=master" + ``` + +See the [Kubernetes Guide](../../docs/kubernetes.md) for complete installation instructions. + +--- + +## Examples Overview + +### 1. Basic Ingress (`service.yml`) + +**What it demonstrates:** +- Basic ingress configuration +- Multiple domains pointing to same service +- Complete deployment + service + ingress setup + +**Components:** +- **Deployment**: `byjg/static-httpserver` container +- **Service**: ClusterIP exposing port 8080 +- **Ingress**: Routes for `example.org` and `www.example.org` + +**Apply:** +```bash +kubectl apply -f service.yml +``` + +**Test:** +```bash +# If using NodePort or port-forward: +curl -H "Host: example.org" http://:31080 + +# Or port-forward for testing: +kubectl port-forward -n easyhaproxy deployment/easyhaproxy 8080:80 +curl -H "Host: example.org" http://localhost:8080 +``` + +**Manifest breakdown:** +```yaml +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + annotations: + kubernetes.io/ingress.class: easyhaproxy-ingress # Required! + name: container-example +spec: + rules: + - host: example.org # First domain + http: + paths: + - backend: + service: + name: container-example + port: + number: 8080 + - host: www.example.org # Second domain (same service) + ... +``` + +--- + +### 2. TLS/SSL Ingress (`service_tls.yml`) + +**What it demonstrates:** +- HTTPS/TLS configuration +- Custom SSL certificates via Kubernetes secrets +- SSL redirect (HTTP → HTTPS) +- Certbot/Let's Encrypt integration + +**Components:** +- **Secret**: Custom SSL certificate for `host2.local` +- **Ingress**: TLS configuration + certbot annotation + +**Apply:** +```bash +kubectl apply -f service_tls.yml +``` + +**Features:** + +1. **Custom SSL Certificate:** + ```yaml + apiVersion: v1 + kind: Secret + metadata: + name: host2-tls + data: + tls.crt: + tls.key: + type: kubernetes.io/tls + ``` + +2. **Ingress TLS Configuration:** + ```yaml + spec: + tls: + - hosts: + - host2.local + secretName: host2-tls # References the secret above + ``` + +3. **Certbot/Let's Encrypt:** + ```yaml + metadata: + annotations: + easyhaproxy.certbot: 'true' + easyhaproxy.redirect_ssl: 'true' + ``` + +**Test:** +```bash +# Test HTTPS (if host2.local in /etc/hosts) +curl -k https://host2.local + +# Test HTTP redirect +curl -I http://host2.local +# Should return: HTTP/1.1 301 Moved Permanently +``` + +--- + +## Kubernetes Annotations Reference + +All annotations are applied at the **Ingress** level and affect all hosts in that ingress. + +### Required Annotation + +| Annotation | Description | Example | +|-------------------------------|-----------------------|-----------------------| +| `kubernetes.io/ingress.class` | Activates EasyHAProxy | `easyhaproxy-ingress` | + +### Optional Annotations + +| Annotation | Description | Default | Example | +|----------------------------|----------------------|---------|-------------------------| +| `easyhaproxy.redirect_ssl` | Force HTTPS redirect | `false` | `'true'` | +| `easyhaproxy.certbot` | Enable Let's Encrypt | `false` | `'true'` | +| `easyhaproxy.mode` | Protocol mode | `http` | `http` or `tcp` | +| `easyhaproxy.listen_port` | Override listen port | `80` | `8080` | +| `easyhaproxy.plugins` | Enable plugins | - | `cloudflare,deny_pages` | + +See [Kubernetes Guide](../../docs/kubernetes.md#kubernetes-annotations) for complete reference. + +--- + +## Common Use Cases + +### Use Case 1: Simple HTTP Application + +```yaml +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + annotations: + kubernetes.io/ingress.class: easyhaproxy-ingress + name: my-app +spec: + rules: + - host: myapp.example.com + http: + paths: + - backend: + service: + name: my-app-service + port: + number: 8080 + pathType: ImplementationSpecific +``` + +### Use Case 2: HTTPS with Let's Encrypt + +```yaml +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + annotations: + kubernetes.io/ingress.class: easyhaproxy-ingress + easyhaproxy.certbot: 'true' + easyhaproxy.redirect_ssl: 'true' + name: secure-app +spec: + rules: + - host: secure.example.com + http: + paths: + - backend: + service: + name: secure-app-service + port: + number: 8080 + pathType: ImplementationSpecific +``` + +**Requirements for Let's Encrypt:** +- Cluster must be publicly accessible on ports 80 and 443 +- DNS must point to cluster IP +- Configure certbot email: + ```bash + # Via Helm: + helm upgrade ingress byjg/easyhaproxy \ + --set easyhaproxy.certbot.email=your-email@example.com + + # Or via environment variable in manifest + ``` + +### Use Case 3: Custom SSL Certificate + +```yaml +--- +apiVersion: v1 +kind: Secret +metadata: + name: my-tls-secret +type: kubernetes.io/tls +data: + tls.crt: LS0tLS1CRUdJTi... # base64 encoded certificate + tls.key: LS0tLS1CRUdJTi... # base64 encoded private key + +--- +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + annotations: + kubernetes.io/ingress.class: easyhaproxy-ingress + name: custom-ssl-app +spec: + tls: + - hosts: + - myapp.example.com + secretName: my-tls-secret + rules: + - host: myapp.example.com + http: + paths: + - backend: + service: + name: my-app-service + port: + number: 8080 + pathType: ImplementationSpecific +``` + +### Use Case 4: Using Plugins (JWT, IP Whitelist, etc.) + +```yaml +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + annotations: + kubernetes.io/ingress.class: easyhaproxy-ingress + # Enable plugins + easyhaproxy.plugins: "jwt_validator,deny_pages" + # Configure JWT validator + easyhaproxy.plugin.jwt_validator.algorithm: "RS256" + easyhaproxy.plugin.jwt_validator.issuer: "https://auth.example.com/" + easyhaproxy.plugin.jwt_validator.audience: "https://api.example.com" + easyhaproxy.plugin.jwt_validator.pubkey_path: "/etc/haproxy/jwt_keys/api_pubkey.pem" + # Configure deny_pages + easyhaproxy.plugin.deny_pages.paths: "/admin,/private" + name: secure-api +spec: + rules: + - host: api.example.com + http: + paths: + - backend: + service: + name: api-service + port: + number: 8080 + pathType: ImplementationSpecific +``` + +See [Using Plugins with Kubernetes](../../docs/kubernetes.md#using-plugins-with-kubernetes) for more examples. + +--- + +## Creating SSL Secrets + +### From Certificate Files + +```bash +kubectl create secret tls my-tls-secret \ + --cert=path/to/cert.crt \ + --key=path/to/cert.key \ + -n default +``` + +### From PEM File + +```bash +# Extract certificate and key +openssl x509 -in cert.pem -out cert.crt +openssl rsa -in cert.pem -out cert.key + +# Create secret +kubectl create secret tls my-tls-secret \ + --cert=cert.crt \ + --key=cert.key \ + -n default +``` + +### Generate Self-Signed Certificate for Testing + +```bash +openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ + -keyout tls.key -out tls.crt \ + -subj "/CN=myapp.example.com" + +kubectl create secret tls my-tls-secret \ + --cert=tls.crt \ + --key=tls.key +``` + +--- + +## Troubleshooting + +### Ingress Not Detected + +**Check annotation:** +```bash +kubectl get ingress -o yaml | grep annotations -A 5 +``` + +Ensure `kubernetes.io/ingress.class: easyhaproxy-ingress` is present. + +**Check EasyHAProxy logs:** +```bash +kubectl logs -n easyhaproxy deployment/easyhaproxy -f +``` + +### SSL Certificate Not Loading + +**Verify secret exists:** +```bash +kubectl get secret -o yaml +``` + +**Check secret has correct fields:** +- `tls.crt`: base64-encoded certificate +- `tls.key`: base64-encoded private key + +**Check EasyHAProxy logs** for certificate loading errors. + +### Let's Encrypt Fails + +**Requirements:** +- Ports 80 and 443 must be publicly accessible +- DNS must resolve to cluster IP +- Certbot email must be configured + +**Check certbot logs:** +```bash +kubectl logs -n easyhaproxy deployment/easyhaproxy | grep certbot +``` + +### Changes Not Applied + +EasyHAProxy watches ingress changes automatically. If changes aren't applied: + +1. **Check discovery interval:** + ```bash + # Default is 10 seconds, increase if needed + EASYHAPROXY_REFRESH: "30" + ``` + +2. **Force reload:** + ```bash + kubectl rollout restart -n easyhaproxy deployment/easyhaproxy + ``` + +--- + +## Tips + +1. **Local Testing:** + Add entries to `/etc/hosts`: + ``` + example.org www.example.org host2.local + ``` + +2. **View HAProxy Config:** + ```bash + kubectl exec -n easyhaproxy deployment/easyhaproxy -- cat /etc/haproxy/haproxy.cfg + ``` + +3. **Access Stats Interface:** + ```bash + kubectl port-forward -n easyhaproxy deployment/easyhaproxy 1936:1936 + # Open: http://localhost:1936 + ``` + +4. **Debug Mode:** + Enable debug logging: + ```yaml + env: + - name: EASYHAPROXY_LOG_LEVEL + value: DEBUG + ``` + +--- + +## Further Reading + +- [Kubernetes Installation Guide](../../docs/kubernetes.md) +- [Helm Installation](../../docs/helm.md) +- [Using Plugins with Kubernetes](../../docs/kubernetes.md#using-plugins-with-kubernetes) +- [ACME/Let's Encrypt](../../docs/acme.md) +- [Environment Variables](../../docs/environment-variable.md) diff --git a/examples/static/README.md b/examples/static/README.md new file mode 100644 index 0000000..aa90cd7 --- /dev/null +++ b/examples/static/README.md @@ -0,0 +1,462 @@ +# Static Configuration Example + +This directory demonstrates EasyHAProxy using **static configuration** mode instead of dynamic service discovery. + +## What is Static Mode? + +Static mode uses a YAML configuration file (`config.yml`) to define HAProxy routing rules instead of discovering services automatically from Docker/Kubernetes/Swarm labels. + +**Use cases:** +- Non-containerized backends +- Mixed environments (containers + VMs + bare metal) +- Fixed infrastructure where services don't change frequently +- Testing HAProxy configurations + +--- + +## Files in This Example + +- `conf/config.yml` - Static configuration defining hosts and routing +- `docker-compose.yml` - EasyHAProxy container mounting the config file +- `host1.local.pem` - Example SSL certificate + +--- + +## Configuration Structure + +### docker-compose.yml + +```yaml +services: + haproxy: + image: byjg/easy-haproxy:4.6.0 + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ./conf:/etc/haproxy/static # Mount static config + - ./host1.local.pem:/certs/haproxy/host1.local.pem + environment: + EASYHAPROXY_DISCOVER: static # Use static mode + EASYHAPROXY_SSL_MODE: "loose" + ports: + - "80:80" + - "443:443" + - "1936:1936" +``` + +### conf/config.yml + +```yaml +stats: + username: admin + password: password + port: 1936 + +customerrors: true + +easymapping: + # HTTP Port 80 - Redirects to HTTPS + - port: 80 + redirect: + host1.local: https://host1.local + www.host1.local: https://host1.local + + # HTTPS Port 443 + - port: 443 + ssl: true + hosts: + host1.local: + containers: + - container:8080 # Backend container +``` + +--- + +## How It Works + +### 1. Port Definitions + +Each item in `easymapping` defines a listening port: + +```yaml +easymapping: + - port: 80 # Listen on port 80 + redirect: {...} # Optional redirects + + - port: 443 # Listen on port 443 + ssl: true # Enable SSL + hosts: {...} # Virtual hosts +``` + +### 2. Redirect Configuration + +Redirect specific domains to different URLs: + +```yaml +- port: 80 + redirect: + host1.local: https://host1.local # HTTP → HTTPS + www.host1.local: https://host1.local # www → non-www + HTTPS + old.domain.com: https://new.domain.com # Domain change +``` + +### 3. Virtual Hosts + +Define hosts and their backend containers: + +```yaml +- port: 443 + ssl: true + hosts: + host1.local: # Virtual host domain + containers: + - container:8080 # Backend: container_name:port + - another_container:3000 # Multiple backends = load balancing + + host2.local: + containers: + - webserver:80 +``` + +**Backend formats:** +- `container_name:port` - Docker container by name +- `ip_address:port` - Direct IP address +- `hostname:port` - Hostname resolution + +### 4. SSL Configuration + +```yaml +- port: 443 + ssl: true # Enable SSL on this port + hosts: + secure.example.com: + containers: + - app:8080 +``` + +SSL certificates must be placed in: +- `/certs/haproxy/.pem` inside container +- `./certs/.pem` on host (if volume mounted) + +Certificate format: PEM file containing both certificate and private key. + +### 5. Stats Interface + +```yaml +stats: + username: admin + password: password + port: 1936 +``` + +Access at: `http://localhost:1936` + +--- + +## Running the Example + +### 1. Start the Example + +```bash +cd examples/static +docker compose up -d +``` + +### 2. Create Backend Container + +The static config references `container:8080`. Create a container with this name: + +```bash +docker run -d --name container \ + -p 8080:8080 \ + byjg/static-httpserver +``` + +Or add to `docker-compose.yml`: + +```yaml +services: + # ... haproxy service ... + + container: + image: byjg/static-httpserver + ports: + - "8080:8080" +``` + +### 3. Test + +```bash +# Add to /etc/hosts: +# 127.0.0.1 host1.local www.host1.local + +# Test HTTP redirect +curl -I http://host1.local +# Should return: HTTP/1.1 301 Moved Permanently +# Location: https://host1.local + +# Test HTTPS +curl -k https://host1.local + +# Access stats +open http://localhost:1936 +# Username: admin +# Password: password +``` + +--- + +## Advanced Configuration + +### Load Balancing Multiple Backends + +```yaml +hosts: + api.example.com: + containers: + - api_server_1:8080 + - api_server_2:8080 + - api_server_3:8080 +``` + +Default algorithm: round-robin + +### Custom Balance Algorithm + +```yaml +hosts: + api.example.com: + balance: leastconn # Use least connections instead of round-robin + containers: + - api_1:8080 + - api_2:8080 +``` + +**Available algorithms:** +- `roundrobin` - Distribute evenly (default) +- `leastconn` - Send to server with fewest connections +- `source` - Same client IP always goes to same server + +### External Backends (Non-Docker) + +```yaml +hosts: + legacy.example.com: + containers: + - 192.168.1.100:8080 # VM + - 192.168.1.101:8080 # Another VM + - database.local:5432 # Database server +``` + +### Health Checks + +```yaml +hosts: + webapp.example.com: + containers: + - server1:8080 + - server2:8080 + healthcheck: + path: /health + interval: 5s +``` + +### Multiple Domains, Same Backend + +```yaml +hosts: + example.com: + containers: + - webapp:8080 + www.example.com: + containers: + - webapp:8080 # Same backend + app.example.com: + containers: + - webapp:8080 # Same backend +``` + +### Path-Based Routing + +While static mode focuses on host-based routing, you can achieve path-based routing using redirects: + +```yaml +- port: 80 + redirect: + api.example.com/v1: https://api-v1.internal:8080 + api.example.com/v2: https://api-v2.internal:8080 +``` + +Or use HAProxy ACLs via custom templates (advanced). + +--- + +## Plugins with Static Configuration + +Enable plugins globally or per-host in static mode: + +### Global Plugin Configuration + +```yaml +plugins: + enabled: [cleanup] + config: + cleanup: + max_idle_time: 600 +``` + +### Per-Host Plugin Configuration (via env vars) + +Since static mode doesn't support per-host plugin configuration directly, use environment variables for domain-specific plugins: + +```yaml +environment: + EASYHAPROXY_PLUGINS_ENABLED: cloudflare,deny_pages + EASYHAPROXY_PLUGIN_CLOUDFLARE_IP_LIST_PATH: /etc/haproxy/cloudflare_ips.lst + EASYHAPROXY_PLUGIN_DENY_PAGES_PATHS: /admin,/private +``` + +See [Using Plugins](../../docs/plugins.md) for more details. + +--- + +## Comparison: Static vs. Dynamic Discovery + +| Feature | Static Mode | Docker/Swarm/K8s Mode | +|---------|-------------|----------------------| +| Configuration | YAML file | Container labels / Ingress annotations | +| Backend types | Any (containers, VMs, IPs) | Containers only | +| Updates | Manual config edit + reload | Automatic discovery | +| Use case | Fixed infrastructure | Dynamic container environments | +| Plugin config | Global via YAML/env | Per-container/ingress via labels/annotations | + +--- + +## Tips + +1. **Reloading Configuration:** + ```bash + # EasyHAProxy watches config.yml for changes + # Edit conf/config.yml, changes auto-reload + + # Or manually restart: + docker compose restart haproxy + ``` + +2. **Validate Configuration:** + ```bash + # Check HAProxy config is valid + docker compose exec haproxy haproxy -c -f /etc/haproxy/haproxy.cfg + ``` + +3. **View Generated Config:** + ```bash + docker compose exec haproxy cat /etc/haproxy/haproxy.cfg + ``` + +4. **Debugging:** + ```bash + # Enable debug mode + docker compose up + # Watch logs in real-time + ``` + +5. **SSL Certificate Management:** + ```bash + # Generate self-signed cert + openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ + -keyout host.key -out host.crt \ + -subj "/CN=host1.local" + + # Combine into PEM + cat host.crt host.key > host1.local.pem + ``` + +--- + +## Troubleshooting + +### Backend Unreachable + +**Error:** `503 Service Unavailable` + +**Causes:** +- Backend container not running +- Wrong container name in config +- Wrong port number +- Network connectivity issues + +**Debug:** +```bash +# Check backend container is running +docker ps | grep container_name + +# Test backend directly +curl http://container_name:port + +# Check HAProxy logs +docker compose logs haproxy +``` + +### Configuration Not Reloading + +**Solution:** +```bash +# Restart HAProxy +docker compose restart haproxy + +# Check file is mounted correctly +docker compose exec haproxy cat /etc/haproxy/static/config.yml +``` + +### SSL Certificate Not Found + +**Error:** Certificate errors in logs + +**Solution:** +```bash +# Verify certificate is mounted +docker compose exec haproxy ls -la /certs/haproxy/ + +# Check certificate format (must be PEM with cert + key) +openssl x509 -in host.pem -text -noout +openssl rsa -in host.pem -check +``` + +--- + +## Migration from Dynamic to Static + +If you have Docker labels and want to convert to static config: + +**Docker label:** +```yaml +labels: + easyhaproxy.http.host: api.example.com + easyhaproxy.http.port: 80 + easyhaproxy.http.localport: 8080 + easyhaproxy.http.redirect_ssl: true +``` + +**Static config equivalent:** +```yaml +easymapping: + - port: 80 + redirect: + api.example.com: https://api.example.com + + - port: 443 + ssl: true + hosts: + api.example.com: + containers: + - container_name:8080 +``` + +--- + +## Further Reading + +- [Static Configuration Guide](../../docs/static.md) +- [Environment Variables](../../docs/environment-variable.md) +- [Using Plugins](../../docs/plugins.md) +- [SSL Configuration](../../docs/ssl.md) diff --git a/examples/swarm/README.md b/examples/swarm/README.md new file mode 100644 index 0000000..e7173b4 --- /dev/null +++ b/examples/swarm/README.md @@ -0,0 +1,650 @@ +# Docker Swarm Examples + +This directory contains Docker Swarm stack examples demonstrating EasyHAProxy in a Swarm cluster environment. + +## What is Docker Swarm Mode? + +Docker Swarm mode enables: +- **Service orchestration** across multiple nodes +- **Service scaling** with replicas +- **Load balancing** across service replicas +- **Rolling updates** with zero downtime +- **Service discovery** via overlay networks + +EasyHAProxy automatically discovers Swarm services and routes traffic based on service labels. + +--- + +## Prerequisites + +### 1. Initialize Docker Swarm + +```bash +# On manager node +docker swarm init + +# On worker nodes (use token from swarm init output) +docker swarm join --token :2377 +``` + +### 2. Create Overlay Network + +```bash +# Create attachable overlay network for EasyHAProxy +docker network create --driver overlay --attachable easyhaproxy +``` + +**Why attachable?** Allows both swarm services and standalone containers to connect. + +--- + +## Files in This Directory + +- `easyhaproxy.yml` - EasyHAProxy service stack +- `services.yml` - Example application services +- `portainer.yml` - Portainer management interface +- `certs/` - Directory for SSL certificates + +--- + +## Quick Start + +### 1. Deploy EasyHAProxy + +```bash +cd examples/swarm + +# Edit easyhaproxy.yml and change: +# EASYHAPROXY_CERTBOT_EMAIL: your-email@example.com + +# Deploy stack +docker stack deploy -c easyhaproxy.yml easyhaproxy +``` + +**What this creates:** +- EasyHAProxy service with 1 replica +- Exposed ports: 80, 443, 1936 +- Mounts Docker socket for service discovery +- Mounts volume for certbot certificates + +### 2. Deploy Example Services + +```bash +docker stack deploy -c services.yml myapp +``` + +### 3. (Optional) Deploy Portainer + +```bash +docker stack deploy -c portainer.yml portainer +``` + +--- + +## Example Files Explained + +### easyhaproxy.yml + +```yaml +version: "3" + +services: + haproxy: + image: byjg/easy-haproxy:4.6.0 + volumes: + - /var/run/docker.sock:/var/run/docker.sock # Service discovery + - ./certs:/certs/haproxy # SSL certificates + - certs_certbot:/certs/certbot # Let's Encrypt certs + deploy: + replicas: 1 # Single instance + environment: + EASYHAPROXY_DISCOVER: swarm # Swarm mode! + EASYHAPROXY_SSL_MODE: "loose" + EASYHAPROXY_CERTBOT_EMAIL: changeme@example.org # Change this! + HAPROXY_CUSTOMERRORS: "true" + HAPROXY_USERNAME: admin + HAPROXY_PASSWORD: password + HAPROXY_STATS_PORT: 1936 + ports: + - "80:80/tcp" + - "443:443/tcp" + - "1936:1936/tcp" + networks: + - easyhaproxy # Overlay network + +networks: + easyhaproxy: + external: true # Created separately + +volumes: + certs_certbot: # Persistent certbot data +``` + +**Key differences from Docker Compose mode:** +- `EASYHAPROXY_DISCOVER: swarm` - Discovery mode +- `deploy.replicas: 1` - Swarm deployment config +- External overlay network + +--- + +## Service Labels in Swarm + +Service labels are similar to container labels but applied to **services**, not containers. + +### Basic Service Example + +```yaml +version: "3" + +services: + webapp: + image: nginx:alpine + deploy: + replicas: 3 # 3 instances for load balancing + labels: + # Service labels (not container labels!) + easyhaproxy.http.host: "webapp.example.com" + easyhaproxy.http.port: "80" + easyhaproxy.http.localport: "80" + networks: + - easyhaproxy +``` + +**Important:** Use `deploy.labels`, NOT top-level `labels`! + +```yaml +# ✅ CORRECT - Service labels +deploy: + labels: + easyhaproxy.http.host: example.com + +# ❌ WRONG - Container labels (ignored in Swarm) +labels: + easyhaproxy.http.host: example.com +``` + +--- + +## Common Use Cases + +### Use Case 1: Simple HTTP Service + +```yaml +version: "3" + +services: + myapp: + image: my-app:latest + deploy: + replicas: 3 + labels: + easyhaproxy.http.host: "myapp.example.com" + easyhaproxy.http.port: "80" + easyhaproxy.http.localport: "3000" + networks: + - easyhaproxy + +networks: + easyhaproxy: + external: true +``` + +Deploy: +```bash +docker stack deploy -c myapp.yml myapp +``` + +### Use Case 2: HTTPS with Let's Encrypt + +```yaml +version: "3" + +services: + secure-app: + image: secure-app:latest + deploy: + replicas: 2 + labels: + easyhaproxy.http.host: "secure.example.com" + easyhaproxy.http.port: "80" + easyhaproxy.http.localport: "8080" + easyhaproxy.http.certbot: "true" + easyhaproxy.http.redirect_ssl: "true" + networks: + - easyhaproxy + +networks: + easyhaproxy: + external: true +``` + +**Requirements:** +- Public IP with DNS pointing to swarm +- Ports 80/443 open +- Certbot email configured in `easyhaproxy.yml` + +### Use Case 3: Multiple Domains, One Service + +```yaml +services: + webapp: + image: webapp:latest + deploy: + replicas: 4 + labels: + # Primary domain + easyhaproxy.http.host: "example.com" + easyhaproxy.http.port: "80" + easyhaproxy.http.localport: "8080" + + # Additional domain (www) + easyhaproxy.http2.host: "www.example.com" + easyhaproxy.http2.port: "80" + easyhaproxy.http2.localport: "8080" + + # API subdomain + easyhaproxy.api.host: "api.example.com" + easyhaproxy.api.port: "80" + easyhaproxy.api.localport: "8080" + networks: + - easyhaproxy +``` + +### Use Case 4: Service with Plugins + +```yaml +services: + api: + image: api-server:latest + deploy: + replicas: 3 + labels: + easyhaproxy.http.host: "api.example.com" + easyhaproxy.http.port: "80" + easyhaproxy.http.localport: "8080" + # Enable plugins + easyhaproxy.http.plugins: "jwt_validator,deny_pages" + # Configure JWT validator + easyhaproxy.http.plugin.jwt_validator.algorithm: "RS256" + easyhaproxy.http.plugin.jwt_validator.issuer: "https://auth.example.com/" + easyhaproxy.http.plugin.jwt_validator.pubkey_path: "/etc/haproxy/jwt_keys/api.pem" + # Configure deny_pages + easyhaproxy.http.plugin.deny_pages.paths: "/admin,/private" + easyhaproxy.http.plugin.deny_pages.status_code: "403" + networks: + - easyhaproxy +``` + +### Use Case 5: Multiple Services with Load Balancing + +```yaml +version: "3" + +services: + frontend: + image: frontend-app:latest + deploy: + replicas: 2 + labels: + easyhaproxy.http.host: "example.com" + easyhaproxy.http.port: "80" + easyhaproxy.http.localport: "3000" + networks: + - easyhaproxy + + api: + image: api-server:latest + deploy: + replicas: 5 # More replicas for API + labels: + easyhaproxy.http.host: "api.example.com" + easyhaproxy.http.port: "80" + easyhaproxy.http.localport: "8080" + networks: + - easyhaproxy + + admin: + image: admin-panel:latest + deploy: + replicas: 1 + labels: + easyhaproxy.http.host: "admin.example.com" + easyhaproxy.http.port: "80" + easyhaproxy.http.localport: "4000" + # Restrict access + easyhaproxy.http.plugins: "ip_whitelist" + easyhaproxy.http.plugin.ip_whitelist.allowed_ips: "192.168.1.0/24" + networks: + - easyhaproxy + +networks: + easyhaproxy: + external: true +``` + +--- + +## Scaling Services + +Scale services dynamically: + +```bash +# Scale up +docker service scale myapp_webapp=10 + +# Scale down +docker service scale myapp_webapp=2 + +# Check replicas +docker service ls +``` + +EasyHAProxy automatically detects all replicas and load balances across them. + +--- + +## Rolling Updates + +Update services with zero downtime: + +```bash +# Update service image +docker service update --image webapp:v2 myapp_webapp + +# Update with custom settings +docker service update \ + --image webapp:v2 \ + --update-parallelism 2 \ + --update-delay 10s \ + myapp_webapp +``` + +EasyHAProxy continues routing to healthy containers during rollout. + +--- + +## Management Commands + +### View Stacks + +```bash +docker stack ls +``` + +### View Services in Stack + +```bash +docker stack services myapp +``` + +### View Service Details + +```bash +docker service inspect myapp_webapp +``` + +### View Service Logs + +```bash +docker service logs -f myapp_webapp +``` + +### Update Service Labels + +```bash +docker service update \ + --label-add easyhaproxy.http.certbot=true \ + myapp_webapp +``` + +### Remove Stack + +```bash +docker stack rm myapp +``` + +--- + +## SSL Certificates in Swarm + +### Option 1: Let's Encrypt (Recommended) + +Configure in `easyhaproxy.yml`: +```yaml +environment: + EASYHAPROXY_CERTBOT_EMAIL: your-email@example.com +``` + +Enable per-service: +```yaml +deploy: + labels: + easyhaproxy.http.certbot: "true" +``` + +### Option 2: Custom Certificates + +Mount certificates directory: +```yaml +# easyhaproxy.yml +volumes: + - ./certs:/certs/haproxy +``` + +Place certificate files: +```bash +./certs/ + ├── example.com.pem + ├── api.example.com.pem + └── secure.example.com.pem +``` + +### Option 3: Docker Secrets (Production) + +```bash +# Create secret +docker secret create example_com_cert ./example.com.pem + +# Use in stack +version: "3" +services: + haproxy: + secrets: + - example_com_cert + environment: + EASYHAPROXY_SSL_CERT_example_com: /run/secrets/example_com_cert + +secrets: + example_com_cert: + external: true +``` + +--- + +## Monitoring and Stats + +### HAProxy Stats Interface + +Access at: `http://:1936` +- Username: `admin` (configured in `easyhaproxy.yml`) +- Password: `password` (configured in `easyhaproxy.yml`) + +### Service Health + +```bash +# Check service health +docker service ps myapp_webapp + +# View detailed service info +docker service inspect --pretty myapp_webapp +``` + +--- + +## Troubleshooting + +### Service Not Detected + +**Check service labels:** +```bash +docker service inspect myapp_webapp | grep -A 20 Labels +``` + +Ensure labels are under `deploy.labels`, not top-level `labels`. + +**Check EasyHAProxy logs:** +```bash +docker service logs -f easyhaproxy_haproxy +``` + +### Service Unreachable (503) + +**Causes:** +- Service containers not ready yet +- Wrong network configuration +- Service crashed + +**Debug:** +```bash +# Check service is running +docker service ps myapp_webapp + +# Check network +docker network inspect easyhaproxy + +# Test service directly +docker run --rm --network easyhaproxy alpine \ + wget -O- http://myapp_webapp:8080 +``` + +### Overlay Network Issues + +**Create network if missing:** +```bash +docker network create --driver overlay --attachable easyhaproxy +``` + +**Verify service is on network:** +```bash +docker service inspect myapp_webapp | grep -A 5 Networks +``` + +### EasyHAProxy Not Starting + +**Check Docker socket permissions:** +```bash +docker service logs easyhaproxy_haproxy +``` + +**Verify socket is mounted:** +```bash +docker service inspect easyhaproxy_haproxy | grep -A 5 Mounts +``` + +### Certificate Issues + +**Certbot fails:** +- Ensure swarm is publicly accessible +- Check DNS points to swarm IP +- Verify ports 80/443 are open +- Check certbot logs: `docker service logs easyhaproxy_haproxy | grep certbot` + +**Custom cert not found:** +```bash +# Exec into service container +docker exec -it $(docker ps -q -f name=easyhaproxy) sh +ls -la /certs/haproxy/ +``` + +--- + +## High Availability Setup + +### Multiple Manager Nodes + +```bash +# On additional manager nodes +docker swarm join-token manager +# Use token on new nodes +``` + +### EasyHAProxy Constraints + +Run EasyHAProxy on specific node: + +```yaml +services: + haproxy: + deploy: + placement: + constraints: + - node.role == manager + - node.labels.haproxy == true +``` + +Label node: +```bash +docker node update --label-add haproxy=true +``` + +### Multiple EasyHAProxy Replicas + +**Not recommended** - EasyHAProxy should run as single instance because: +- Multiple instances would compete for port binding +- Use external load balancer (cloud LB, keepalived, etc.) for HA + +**Alternative HA pattern:** +``` +Internet → Cloud Load Balancer → Multiple Swarm Nodes + └→ EasyHAProxy (runs on 1 node) + └→ Services (distributed across nodes) +``` + +--- + +## Best Practices + +1. **Use Overlay Networks:** + - Create dedicated network for EasyHAProxy + - Use `--attachable` for flexibility + +2. **Service Labels:** + - Always use `deploy.labels`, never top-level `labels` + - Use clear, descriptive domain names + +3. **Replicas:** + - Start with 2-3 replicas per service + - Scale based on load monitoring + - Use odd number for consensus (3, 5, 7) + +4. **Updates:** + - Use rolling updates for zero downtime + - Set appropriate `update-delay` + - Test in staging first + +5. **Monitoring:** + - Enable HAProxy stats + - Use Portainer for visual management + - Monitor service health regularly + +6. **Security:** + - Use Docker secrets for sensitive data + - Restrict admin panel access + - Use SSL/TLS for production + - Apply IP whitelisting for admin interfaces + +7. **Persistence:** + - Use volumes for certbot certificates + - Backup certificate volumes + - Store custom certs in version control (encrypted) + +--- + +## Further Reading + +- [Docker Swarm Documentation](../../docs/swarm.md) +- [Container Labels Reference](../../docs/container-labels.md) +- [Using Plugins](../../docs/plugins.md) +- [ACME/Let's Encrypt](../../docs/acme.md) +- [Environment Variables](../../docs/environment-variable.md) +- [Official Docker Swarm Docs](https://docs.docker.com/engine/swarm/)