haproxy
A Helm chart for HAProxy on Kubernetes
About this chart
HAProxy Helm Chart
Introduction
This chart bootstraps an HAProxy load balancer as deployment/daemonset on a Kubernetes cluster using the Helm package manager. As opposed to HAProxy Kubernetes Ingress Controller Chart, HAProxy is installed as a regular application and not as an Ingress Controller.
Prerequisites
- Kubernetes 1.17+ (recommended 1.20+)
- Helm 3.6+ (recommended 3.7+)
Before you begin
Setup a Kubernetes Cluster
The quickest way to setup a Kubernetes cluster is with Azure Kubernetes Service, AWS Elastic Kubernetes Service or Google Kubernetes Engine using their respective quick-start guides.
For setting up Kubernetes on other cloud platforms or bare-metal servers refer to the Kubernetes getting started guide.
Install Helm
Get the latest Helm release.
Add Helm chart repo
Once you have Helm installed, add the haproxytech Chart Repository as follows:
helm repo add haproxytech https://haproxytech.github.io/helm-charts
helm repo update
Alternatively if you want to proceed with just OCI-based repository, skip this step and follow the installation with OCI.
Install the chart
To install the chart as my-release deployment:
helm install my-release haproxytech/haproxy
Alternatively also have OCI-based repository available for simplified access (add --version X.Y.Z to pin a chart version):
helm install my-release oci://ghcr.io/haproxytech/helm-charts/haproxy
Installing with unique name
To auto-generate resource names when installing, use the following:
helm install haproxytech/haproxy \
--generate-name
Installing from a private registry
To install the chart using a private registry for HAProxy (for instance to use a HAProxy Enterprise image) into a separate namespace prod.
NOTE: The namespace must exist; add --create-namespace to have Helm create it (eg. instead of kubectl create namespace prod)
helm install my-haproxy haproxytech/haproxy \
--namespace prod \
--create-namespace \
--set image.tag=latest \
--set image.repository=myregistry.domain.com/imagename \
--set imageCredentials.registry=myregistry.domain.com \
--set imageCredentials.username=MYUSERNAME \
--set imageCredentials.password=MYPASSWORD
Alternatively, use a pre-configured (existing) imagePullSecret in the same namespace:
helm install my-haproxy haproxytech/haproxy \
--namespace prod \
--set image.tag=SOMETAG \
--set existingImagePullSecret=name-of-existing-image-pull-secret
NOTE: Enterprise images using S6 overlay need default CMD arguments disabled (more about YAML configuration file for Helm can be found in a separate paragraph below):
args:
enabled: false
Installing as DaemonSet
Default image mode is Deployment, but it is possible to use DaemonSet as well:
helm install my-haproxy2 haproxytech/haproxy \
--set kind=DaemonSet
Installing with Horizontal Pod Autoscaler
HPA automatically scales number of replicas in a Deployment. When autoscaling (or KEDA) is enabled the chart leaves replicas unset, so the HPA owns the replica count and replicaCount is ignored:
helm install my-haproxy3 haproxytech/haproxy \
--set kind=Deployment \
--set autoscaling.enabled=true \
--set autoscaling.targetCPUUtilizationPercentage=80
NOTE: Make sure to look into other tunable values for HPA documented in values.yaml.
Installing with service annotations
On some environments like EKS and GKE there might be a need to pass service annotations. Syntax can become a little tedious however:
helm install my-haproxy4 haproxytech/haproxy \
--set kind=DaemonSet \
--set service.type=LoadBalancer \
--set service.annotations."service\.beta\.kubernetes\.io/aws-load-balancer-internal"="0.0.0.0/0" \
--set service.annotations."service\.beta\.kubernetes\.io/aws-load-balancer-cross-zone-load-balancing-enabled"="true"
NOTE: With helm --set it is needed to put quotes and escape dots in the annotation key and commas in the value string.
Selecting a LoadBalancer implementation
When more than one load balancer controller runs in a cluster, service.loadBalancerClass picks which one reconciles the Service. Leaving it unset uses the cluster's default implementation:
helm install my-haproxy5 haproxytech/haproxy \
--set service.type=LoadBalancer \
--set service.loadBalancerClass="example.com/internal-lb" \
--set service.loadBalancerSourceRanges[0]="192.0.2.0/24"
NOTE: loadBalancerClass renders only when service.type is LoadBalancer and the cluster is Kubernetes 1.21 or newer (the field is GA as of 1.24). On older clusters it is omitted.
NOTE: loadBalancerClass is immutable while the Service stays type LoadBalancer. Kubernetes rejects a change on an existing Service, so helm upgrade cannot alter it in place - the Service has to be recreated.
Using values from YAML file
As opposed to using many --set invocations, much simpler approach is to define value overrides in a separate YAML file and specify them when invoking Helm.
The config block can also support using helm templates to populate dynamic values, e.g. {{ .Release.Name }} or a value of your own such as {{ .Values.global.serverTimeout }} below.
mylb.yaml:
kind: DaemonSet
global:
serverTimeout: 60s
config: |
global
log stdout format raw local0
daemon
maxconn 1024
defaults
log global
timeout client 60s
timeout connect 60s
timeout server {{ .Values.global.serverTimeout }}
frontend fe_main
bind :80
default_backend be_main
backend be_main
server web1 10.0.0.1:8080 check
server web2 {{ .Release.Name }}-web:8080 check
service:
type: LoadBalancer
annotations:
service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: "true"
service.beta.kubernetes.io/aws-load-balancer-internal: 0.0.0.0/0
And invoking Helm becomes (compare to the previous example):
helm install my-haproxy5 -f mylb.yaml haproxytech/haproxy
Using secrets in additional volume mounts
In order to e.g. support SSL certificates, you can mount additional volumes from secrets:
mylb.yaml:
service:
type: LoadBalancer
config: |
global
log stdout format raw local0
daemon
maxconn 1024
ssl-load-extra-del-ext
defaults
log global
timeout client 60s
timeout connect 60s
timeout server 60s
frontend fe_main
mode http
bind :80
bind :443 ssl crt /usr/local/etc/ssl/tls.crt
http-request redirect scheme https code 301 unless { ssl_fc }
default_backend be_main
backend be_main
mode http
server web1 10.0.0.1:8080 check
mountedSecrets:
- volumeName: ssl-certificate
secretName: star-example-com
mountPath: /usr/local/etc/ssl
The above example assumes a TLS Secret called star-example-com (for example created with kubectl create secret tls star-example-com --cert=... --key=...), which holds the certificate in key tls.crt and the private key in key tls.key. HAProxy looks for a key that is not in the certificate file at <file>.key, i.e. tls.crt.key; ssl-load-extra-del-ext makes it look for tls.key instead, so the Secret can be mounted as is.
Using additional volumes and volumeMounts
In order to load data from other sources (e.g. to preload something inside an init-container) you can mount additional volumes to the container:
extraVolumes:
- name: tls
emptyDir: {}
- name: tmp
emptyDir:
medium: Memory
extraVolumeMounts:
- name: tls
mountPath: /etc/tls
- name: tmp
mountPath: /tmp
Using additional environment variables
In order to expose extra data (e.g. node and pod IP addresses) to haproxy, you can populate extra environment variables on the container:
extraEnvs:
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
Automatic configuration reloading
In some cases, configuration changes are frequent and constantly restarting HAProxy is not optimal. For those cases the HAProxy hot-reload feature can be used.
In master-worker mode, sending a USR2 signal to the HAProxy process will trigger a configuration reload.
config: |
global
log stdout format raw local0
master-worker
daemon
maxconn 1024
defaults
log global
timeout client 60s
timeout connect 60s
timeout server 60s
frontend fe_main
mode http
bind :80
default_backend be_main
backend be_main
mode http
server web1 10.0.0.1:8080 check
Make sure you are not specifying subPath for any of your volumeMounts so that Kubernetes will automatically update the volumes created from ConfigMaps.
And finally, use some sidecar container which will be delivering the signal to the process. The shareProcessNamespace Pod property is required for the sidecars to be able to access other containers' processes.
shareProcessNamespace:
enabled: true
sidecarContainers:
- name: reflex
image: acim/go-reflex:1.17.3
command: ["reflex", "-d", "fancy"]
workingDir: /usr/local/etc/haproxy
args:
- -svr
- "..data"
- --
- bash
- -c
- 'pkill -SIGUSR2 "haproxy|hapee-lb"'
volumeMounts:
- name: haproxy-config
mountPath: /usr/local/etc/haproxy
resources:
limits:
memory: 128Mi
requests:
cpu: 50m
memory: 64Mi
Installing as non-root with binding to privileged ports
To bind privileged ports such as tcp/80 and tcp/443 without root privileges (UID and GID are set to 1000 in the examples, as the HAProxy Docker image has UID/GID 1000 reserved for HAProxy), lower the start of the unprivileged port range for the pod. net.ipv4.ip_unprivileged_port_start is a namespaced, safe sysctl since Kubernetes 1.22, so it can be set through podSecurityContext without any privileged container:
podSecurityContext:
sysctls:
- name: net.ipv4.ip_unprivileged_port_start
value: "0"
securityContext:
enabled: true
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
With daemonset.useHostNetwork: true the pod shares the node's network namespace, where Kubernetes does not allow pod sysctls. The only option there is a privileged init container, and it changes the setting for the whole node, not just for HAProxy:
kind: DaemonSet
containerPorts:
http: 80
https: 443
stat: 1024
daemonset:
useHostNetwork: true
useHostPort: true
hostPorts:
http: 80
https: 443
stat: 1024
dnsPolicy: ClusterFirstWithHostNet
config: |
global
log stdout format raw local0
maxconn 1024
defaults
log global
timeout client 60s
timeout connect 60s
timeout server 60s
frontend fe_main
bind :80
default_backend be_main
backend be_main
server web1 127.0.0.1:8080 check
securityContext:
enabled: true
runAsUser: 1000
runAsGroup: 1000
initContainers:
- name: sysctl
image: "busybox:musl"
command:
- /bin/sh
- -c
- sysctl -w net.ipv4.ip_unprivileged_port_start=0
securityContext:
privileged: true
Memory limits
The chart sets memory and CPU requests but no limits by default:
resources:
requests:
cpu: 250m
memory: 128Mi
A request only influences scheduling. Without a limit the container may use as much memory as the node has, and under memory pressure the node's OOM killer chooses which pod to evict, which may be an unrelated workload, instead of this pod being restarted against a ceiling of its own. A limit also contains runaway growth, such as stick tables or maps growing unchecked.
How much HAProxy needs depends entirely on its configuration: buffers, concurrent connections, stick table size, map and ACL files, and SSL session caches all contribute. Size a limit against your own configuration under load, for example:
resources:
limits:
memory: 256Mi
requests:
cpu: 250m
memory: 128Mi
Note that this chart runs the haproxytech/haproxy-alpine image, which starts
HAProxy directly. The limit is a cap and nothing more. This differs from the
kubernetes-ingress and haproxy-unified-gateway charts, whose image derives
HAProxy's and the controller's memory budgets from the container limit, so
that leaving it unset changes how those processes size themselves.
Prometheus monitoring
HAProxy has a built-in Prometheus exporter, which needs a frontend in config. The default serviceMonitor.endpoints scrape a Service port named prometheus; a containerPorts entry of that name creates both the container port and the Service port:
containerPorts:
prometheus: 8405
serviceMonitor:
enabled: true
extraLabels:
release: prometheus # match your Prometheus serviceMonitorSelector
config: |
global
log stdout format raw local0
maxconn 1024
defaults
lo
Deploy haproxy with OpenTenant
Each tenant gets its own release of this chart, with its own namespace, secrets and domain. The builder below already has haproxy on a Hetzner server. Change the host, add apps from the marketplace, then copy the generated files. Providers and prices are samples, and nothing here is sent anywhere.
- Pick a serverConnect Hetzner, OVHcloud or AWS. The builder starts on Hetzner, the cheapest sample rate.
- Place the charthaproxy is pinned at v1.31.2 in opentenant.yaml. Drag more apps from the marketplace onto a rack.
- ApplySave opentenant.yaml and main.tf from the console, then run the commands below.
# opentenant.yaml, main.tf and dns.tf come from the builder below opentenant validate opentenant.yaml terraform init && terraform apply