Skip to content

Kubernetes headless service

A Kubernetes headless service is a specific type of Service configuration that is defined by setting the clusterIP field to None in its specification.^[400-devops-06-kubernetes-out-network-k8s.md][400-devops__06-Kubernetes__out-network__k8s中引入外部服务.md]

Characteristics

Unlike a standard service which abstracts backend Pods behind a single virtual IP address (ClusterIP), a headless service does not provide this single IP.^[400-devops-06-kubernetes-out-network-k8s.md][400-devops__06-Kubernetes__out-network__k8s中引入外部服务.md] Instead, it allows a client to connect directly to the backend Pods or external IPs by returning the IP addresses of the individual targets.

Usage

Headless services are frequently employed to introduce external services into a Kubernetes cluster.^[400-devops-06-kubernetes-out-network-k8s.md][400-devops__06-Kubernetes__out-network__k8s中引入外部服务.md] By pairing a headless Service definition (specifying clusterIP: None) with a custom Endpoints resource, administrators can map a Kubernetes Service name to a specific external IP address.

Example Configuration

The following example demonstrates a headless service named mysql-svc mapped to an external IP via Endpoints^[400-devops-06-kubernetes-out-network-k8s.md][400-devops__06-Kubernetes__out-network__k8s中引入外部服务.md]:

apiVersion: v1
kind: Service
metadata:
  name: mysql-svc
  namespace: default
spec:
  clusterIP: None # Defines the service as headless
  ports:
    - name: default-ep
      port: 3306
      protocol: TCP
      targetPort: 3306
  type: ClusterIP
---
apiVersion: v1
kind: Endpoints
metadata:
  name: mysql-ep
  namespace: default
subsets:
  - addresses:
      - ip: 114.32.146.154 # External IP address
    ports:
      - name: mysql
        port: 3306
        protocol: TCP

Clients within the cluster can then access the external service using the standard Kubernetes DNS name (e.g., mysql-svc.default.svc.cluster.local) even though the traffic routes to an endpoint outside the cluster.^[400-devops-06-kubernetes-out-network-k8s.md][400-devops__06-Kubernetes__out-network__k8s中引入外部服务.md]

  • Kubernetes
  • [[Endpoints]]
  • [[Service (Kubernetes)]]

Sources

  • 400-devops-06-kubernetes-out-network-k8s.md
  • 400-devops__06-Kubernetes__out-network__k8s中引入外部服务.md