Technology Sharing

Types and usage of Service exposure in k8s

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

1. Description
In Kubernetes, there are several different ways to expose a Service to external traffic. These ways are determined by the spec.type field that defines the Service.
2. Detailed explanation
1. ClusterIP
Definition: The default type, the service can only be accessed within the cluster.
Purpose: Expose services through cluster internal IP addresses.
Example:

spec:
  type: ClusterIP
  ports:
    - port: 80
      targetPort: 8080
  • 1
  • 2
  • 3
  • 4
  • 5

2.NodePort
Definition: Open a high port (usually 30000-32767) on each node to allow external traffic to access the service.
Function: Access the service through the IP address and nodePort of any node.
Example:

spec:
  type: NodePort
  ports:
    - port: 80
      targetPort: 8080
      nodePort: 30007
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3. LoadBalancer

Definition: The load balancer provided by the cloud platform assigns an external IP address to the service.
Function: Access the service through this IP address, which is suitable for situations where external traffic load balancing is required.
Example:

spec:
  type: LoadBalancer
  ports:
    - port: 80
      targetPort: 8080
  selector:
    app: my-app
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

4. ExternalName

Definition: Maps a service to an external domain name (such as a database service).
Purpose: Access the service through the specified external domain name instead of the cluster internal IP or node IP.
Example:

spec:
  type: ExternalName
  externalName: example.com
  • 1
  • 2
  • 3

2. Conclusion
ClusterIP: The default service type, accessible only within the cluster.
NodePort: Opens a port on each node to allow external traffic to access the service.
LoadBalancer: The load balancer provided by the cloud platform allocates an external IP address and is suitable for situations where load balancing is required.
ExternalName: Maps the service to an external domain name, which is suitable for scenarios where external services need to be accessed.