The way to scale up containerized applications in Kubernetes is to create multiple pods. However, Kubernetes pods are not permanent resources and they are created and destroyed dynamically. Each pod created from the same template has it’s own unique ID and IP address. That poses a challenge to the consumers of the functionality provided by a set of pods. How do they keep tracking the IP addresses of the pods and know which pods to connect to?
The Answer is Kubernetes Service.
Kubernetes service provides an abstraction to a set of pods that provide the same functionality in a cluster and exposes an interface to these pods. A service has a DNS name and a unique IP address (clusterIP) and the IP address will not change as long as the service is running, regardless pods are added to or deleted from the pod set the service represents. The service is responsible to keep tracking the set of pods, provide loading balance and routing traffic among them.
Like Kubernetes pods, A Kubernetes service is a REST object, so you can create an instance by posting the service definition to Kubernetes API server. Below is an example of service specification that a set of pods listen on port 8080 with a label app=your_app
:
apiVersion: v1
kind: Service
metadata:
name: you-service
labels:
name: your-service
spec:
selector:
app: your_app
ports:
- protocol: TCP
port: 80
targetPort: 8080
name: http
Kubernetes service supports multiple ports as well. Each port definition in the service can have the same protocol or different one. The supported protocols are TCP, HTTP, UDP, SCTP and PROXY protocol. TCP is the default protocol.
You can specify what type of your service is using ServiceType
field. The default type is ClusterIP
. Below are types supported:
ClusterIP
: Exposes the service that is only reachable from within the cluster. This is the default type.NodePort
: Exposes the service via a static port on each Node’s IP. TheNodePort
Service can be reached from outside the cluster by requesting<NodeIP>:<NodePort>
. When this type is chosen, Kubernetes control plane chooses a port from a range specified by--service-node-port-range
flag (default: 30000-32767) and each Node will use that port for your service. You can specify your service to use a particular port withnodePort
field.LoadBalancer
: Exposes the service via a cloud provider's load balancer.NodePort
andClusterIP
Services are automatically created.ExternalName
: Maps the service to a predefinedexternalName
field (e.g.foo.bar.example.com
) by returning aCNAME
record with its value.
If you don’t need single IP and load balancing, you can create headless services by set clusterIP
field to None.