Kubernetes Services
- Kubernetes Service is a type of controller
- Kubernetes service benefits:
- It has a stable IP address compared to pod which is ephemeral and can die easily
- It has loadbalancing
- can be within or outside the cluster
- Service Communication:
- Each request to k8s service is forwarded to one of the pods replica
- we can specify selector to select the pods replica
- Generally we perform API request to service which in turn goes to one of the pod replica
Selector and Labels
- Define a deployment for nodes
apiVersion: apps/v1
kind: Deployment
metadata:
name: microservice-one
...
spec:
replicas: 2
template:
metadata:
labels:
app: microservice-one
- Define the service which will register the nodes using selector
apiVersion: v1
kind: Service
metadata:
name: microservice-one-service
spec:
selector:
app: microservice-one
port:
- protocol: TCP
port: 3200
targetPort: 3000
targetPort defines which container’s port inside the pod request needs to be forwarded
- Whenever a service is created, kubernetes creates an EndPoint object automatically
Types of Services
- Types:
- ClusterIP
- NodePort
- LoadBalancer
type attribute define the service type
ClusterIP
- It is default
type if not provided
apiVersion: v1
kind: Service
metadata:
name: microservice-one-service-one
spec:
type: ClusterIP # can be omitted
selector:
app: microservice-one
ports:
- protocol: TCP
port: 3200 # ClusterIP port
targetPort: 3000 # Pod port
NodePort
- It exposes a Node with a static port which is accessible
- External Traffic can access the Worker node
- NodePort automatically creates a
ClusterIP inside the node which points to the Pod
- Generally not used on production, might be used for testing
apiVersion: v1
kind: Service
# ...
spec:
type: NodePort
# ....
ports:
- protocol: TCP
port: 3200 # ClusterIP port
targetPort: 3000 # Pod port
nodePort: 30008 # Node port, between 30000 to 32767
LoadBalancer
- Each cloud provider has its own native
LoadBalancer service implementation
- LoadBalancer automatically creates
NodePort and ClusterIP for you
- So
ClusterIP < NodePort < LoadBalancer (each is extension of previous one)
- We generally use
LoadBalancer service or Ingress in production
Headless
- Useful in database pods, or in case where different pods can be differentiated by state (stateful pods)
- In case of DB, we generally keep one master pod and other as worker pod which has to continuously sync with master
- We should not randomly select pod and only master should be read/write
- we can achieve it by
clusterIP: None to have pod IP as cluster IP