Service K8 object - rajeshamdev/containers-orchestration GitHub Wiki

service object: a k8 Service object is used to expose a set of Pods as a network service. It can be used to load-balance traffic across multiple Pods and make them accessible from other services or external clients.

apiVersion: v1
kind: Service
metadata:
  name: example-service
  labels:
    app: example-app
spec:
  type: ClusterIP  # Other types: NodePort, LoadBalancer, ExternalName
  selector:
    app: example-app
  ports:
  - protocol: TCP
    port: 80         # Port the service will expose
    targetPort: 80   # Port on the container to route traffic to

Breakdown of the Specification:

  • apiVersion: v1: Defines the API version used to manage the Service.
  • kind: Service: Specifies that this is a Service resource.
  • metadata: Contains metadata about the Service, such as its name and labels.
  • spec: Defines the desired state of the Service.
    • type: Specifies the type of Service. Options include:
    • ClusterIP: Exposes the Service on a cluster-internal IP. This is the default type and is only accessible within the cluster.
    • NodePort: Exposes the Service on each Node's IP at a static port. Accessible externally via :.
    • LoadBalancer: Exposes the Service externally using a cloud provider’s load balancer (if supported).
    • ExternalName: Maps the Service to a DNS name (not a typical use case for exposing Pods directly).
  • selector: Defines how the Service finds which Pods to route traffic to. It matches Pods with the app: example-app label.
  • ports: List of ports that the Service will expose.
    • protocol: Protocol to use (e.g., TCP, UDP).
    • port: Port on which the Service will be accessible.
    • targetPort: Port on the container that the traffic will be forwarded to.

This example defines a ClusterIP service, which is suitable for internal communication within the cluster. If you need external access, you might choose NodePort or LoadBalancer based on your requirements and the environment where Kubernetes is running.

⚠️ **GitHub.com Fallback** ⚠️