Kubernetes - Headless Service đ§
Description đ
A headless service
is a service that does not have a ClusterIP
. This means that the service will not have a virtual IP address. Instead, the service will return the Pod
IP addresses. This is useful for stateful applications that require a stable IP address for each Pod
.
Examples đ§Š
-
headless service
definitionapiVersion: v1 kind: Service metadata: name: mysql-h spec: ports: - port: 3306 selector: app: mysql clusterIP: None
headless service
does not have aClusterIP
, must setclusterIP
to None
-
pod
usingheadless service
apiVersion: v1 kind: Pod metadata: name: myapp-pod labels: app: mysql spec: containers: - name: mysql image: mysql # pod uses headless service subdomain: mysql-h hostname: mysql-pod
-
stateful set
usingheadless service
apiVersion: apps/v1 kind: StatefulSet metadata: name: mysql-deployment labels: app: mysql spec: serviceName: mysql-h replicas: 3 selector: matchLabels: app: mysql template: metadata: name: myapp-pod labels: app: mysql spec: containers: - name: mysql image: mysql
serviceName
is the name of theheadless service
that thestateful set
will use- the stateful set does not need to specify the
subdomain
andhostname
because thestateful set
will automatically create aheadless service
for eachpod
in thestateful set
-
stateful set
usingheadless service
withpvc
for eachpod
apiVersion: apps/v1 kind: StatefulSet metadata: name: mysql labels: app: mysql spec: replicas: 3 selector: matchLabels: app: mysql template: metadata: labels: app: mysql spec: containers: - name: mysql image: mysql volumeMounts: - name: data-volume mountPath: /var/lib/mysql volumeClaimTemplates: - metadata: name: data-volume spec: accessModes: - ReadWriteOnce storageClassName: google-storage resources: requests: storage: 500Mi
volumeClaimTemplates
is used to create apvc
for eachpod
in thestateful set
stateful sets
do not automatically deletepvc
whenpods
fail or are deleted, instead they ensure that when thepod
is recreated, thepvc
is bound back to thepod
that was recreated.