Services

A Service is an abstraction that defines a stable network endpoint for a set of Pods.

Since Pods are ephemeral (they can die, restart, or be rescheduled on another node), their IPs change. If other applications want to talk to those Pods, they’d have to constantly track changing Pod IPs — which is not practical.

A Service solves this by:

  • Giving a stable DNS name and ClusterIP.

  • Acting as a load balancer across the set of Pods that match its label selector.

  • Allowing communication between different parts of the application or from outside the cluster.

Types of Services

ClusterIP

  • Accessible only inside the Cluster.

  • Good for Internal communication between microservices.

NodePort

  • Opens a port on each Node’s IP so you can access it externally (<NodeIP>:<NodePort>).

  • Useful for testing, not production.

LoadBalancer

  • Provisions a cloud provider’s load balancer (AWS ELB, GCP LB, Azure LB).

  • Common for production apps that need external access.

ExternalName

  • Maps a Service to an external DNS name.

  • Useful when you want in-cluster apps to talk to something outside.

Commands

To apply and run Service consigurations:

kubectl apply -f service.yaml

To list the Services:

kubectl get services

To describe a Service:

kubectl describe service <service-name>

To delete a Service:

kubectl delete service <service-name>

To forward port for external access:

kubectl port-forward service/<service-name> 3000:80

Where "3000" is the external port and "80" is the service port.

Example

service.yaml
apiVersion: v1
kind: Service
metadata:
  name: myapp-service
spec:
  # Which Pods will assossiate with the Service by the `matchLabel`
  selector:
    app: myapp
  type: ClusterIP
  ports:
    - name: myapp-tcp  # recommended to fill if multiple ports are exposed
      protocol: TCP
      port: 80         # service port
      targetPort: 8080 # pod port

myapp-tcp will be resolved to the generated cluster IP, so you my use the "name" when accessing the cluster.

If targetPort is not specified, it will assume to be the same as port.

Last updated