Working with Services in Kubernetes
What are Services in K8s
In Kubernetes (K8s), a service is an abstraction that defines a logical set of pods and a policy by which to access them. It provides a stable endpoint (IP address and port) that can be used to interact with the pods, abstracting away the complexity of managing individual pod IPs and dynamic changes in the cluster.
Key points about Kubernetes services
- Stable Network Endpoint:A service is assigned a stable IP address and port, allowing clients to connect to it without needing to know the specific IP addresses of the individual pods.
- Pod Selection:A service selects pods based on labels. Pods with matching labels are part of the service.
- Types of Services:Kubernetes supports various types of services, including ClusterIP, NodePort, LoadBalancer, and ExternalName. Each type has its own use case and characteristics.ClusterIP: Exposes the service on a cluster-internal IP. This type makes the service only accessible from within the cluster.NodePort: Exposes the service on each node's IP at a static port. This makes the service accessible externally, not just within the cluster.LoadBalancer: Creates an external load balancer that forwards traffic to the service. This is useful when you need to expose the service to the internet.ExternalName: Maps the service to the contents of the externalName field (e.g., a DNS name).
- Service Discovery:Services enable service discovery within the Kubernetes cluster. Other applications or services can discover and communicate with each other using the service's stable IP and port.
- Load Balancing:For services with multiple pods, Kubernetes automatically load-balances the traffic among the selected pods.
- Session Affinity:Services can be configured to use session affinity, ensuring that requests from a client are always directed to the same pod, which can be useful for maintaining state.
领英推è
Headless Service:
In addition to the common service types, Kubernetes also supports headless services. A headless service is used when you don't need a stable IP and you want direct communication with the individual pods.
Service for your todo-app Deployment
apiVersion: v1
kind: Service
metadata:
name: todo-app-service
spec:
selector:
app: todo-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: ClusterIP
- metadata.name: Specifies the name of the service, in this case, todo-app-service.
- spec.selector: Defines the labels that the service will use to select pods. In this example, it selects pods with the label app: todo-app. Ensure that your todo-app deployment pods have this label.
- spec.ports: Specifies the ports configuration. In this case, it exposes port 80 on the service, which will be internally forwarded to port 8080 on the pods.
- spec.type: Defines the type of service. Here, it's set to ClusterIP, which means the service will get an internal IP within the cluster.
kubectl apply -f todo-app-service.yaml