Many sites like this says that the benefit of Headless Service is direct detection of the pod’s IP address and direct access to the pod. However, this explanation does not make sense to me. The reason is that even if we don’t use the Headless Service, we can still access the pod directly.
I think the following example:
apiVersion: v1
kind: Service
metadata:
name: my-headless-service
spec:
type: ClusterIP
clusterIP: None
selector:
app: my-app
ports:
- name: http
port: 80
targetPort: 8080
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: my-statefulset
spec:
serviceName: my-headless-service
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-container
image: nginx
ports:
- name: http
containerPort: 8080
---
# Client Pod
apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
labels:
name: myapp
spec:
containers:
- name: myapp
image: willfarrell/ping
ports:
- containerPort: 8080
From the Pod named myapp-pod, we can access each Pods managed by StatefulSet like the following
ping my-statefulset-0.my-headless-service
ping my-statefulset-1.my-headless-service
ping my-statefulset-2.my-headless-service
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
type: ClusterIP
selector:
app: my-app
ports:
- name: http
port: 80
targetPort: 8080
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: my-statefulset
spec:
serviceName: my-service
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-container
image: nginx
ports:
- name: http
containerPort: 8080
---
# Client Pod
apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
labels:
name: myapp
spec:
containers:
- name: myapp
image: willfarrell/ping
ports:
- containerPort: 8080
From the Pod named myapp-pod, we can also access each Pods managed by StatefulSet like the following
ping my-statefulset-0.my-service
ping my-statefulset-1.my-service
ping my-statefulset-2.my-service
Like this we can access Pods managed by StatefulSet without headless service.
Is there any difference between 1(using headless service) and 2(without headless service)?
Great article for further exploration: https://www.goglides.dev/bkpandey/headless-services-in-kubernetes-what-why-and-how-39fl