A Service is an abstraction of a logical set of pods and a policy that defines inbound and network access. A service uses a selector to target pods by the pods’ label. A service exposes a logical set of pods as a network service providing a single IP address, DNS name, or load balancing to access the pods.
The Service type is defined in the manifest. The following are available Service types:
- ClusterIP – exposes the Service on an internal IP in the Kubernetes cluster (default)
- NodePort – exposes the Service on the same port of each node in the Kubernetes cluster
- LoadBalancer – creates an external load balancer with a cloud provider (e.g. GCE ForwardingRules, AWS Elastic Load Balancer, Azure Load Balancer) and assigns a public IP to the Service
- ExternalName – exposes the Service using an arbitrary name
Services can be created imperatively for a running resource. At minimum the resource type, resource name, and the service’s exposed proxy port are required e.g.
kubectl expose <resource> <resource_name> --port=<port number>.
$ kubectl create deploy webserver --image nginx deployment.apps/webserver created $ kubectl expose deploy webserver --port 80 service/webserver exposed $ kubectl get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 443/TCP 33d webserver ClusterIP 10.103.175.171 80/TCP 4s $
Services select pods using labels, and for each pod creates an endpoint resource. The endpoint resource describes all active network targets (pods) that the service routes traffic to. Each endpoint object in a cluster places an additional iptables rule with a target pod’s IP. An alternative to endpoints are EndpointSlices. EndpointSlices are conceptually and functionally similar to endpoints, but are restricted to up to 100 endpoints to improve management at scale.
$ kubectl get endpoints webserver NAME ENDPOINTS AGE webserver 10.32.0.8:80 43s $ kubectl get pods -o wide -l app=webserver NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES webserver-d698d7bd6-ktxvn 1/1 Running 0 83s 10.32.0.8 ubuntu $
Ingresses are another resource that interact with Services. Ingresses bind Services to external endpoints that an Ingress controller on the cluster then exposes to the outside world. Ingresses reference Services directly in their manifests, as shown here:
apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: name: webserver-ingress annotations: spec: rules: - http: paths: - path: /testpath backend: serviceName: webserver servicePort: 80
Learn more about: