Kubernetes Clusterip Service Example
Kubernetes ClusterIP Service Example
Kubernetes ClusterIP
cluster ip is the default type of a Kubernetes service. clusterip makes the service only reachable from within the cluster. we can not reach this service from out side the cluster. drawback of using ‘ClusterIp’ is that you cannot call the services from the outside of the cluster without using a proxy. to overcome this issue we have to some proxy. using Kubernetes ingress controller we can expose ClusterIP services to outside the network.
to create a service first we need pods. after creating pods we can expose service with particular labelled pods.
Create Pods:
using kubectl commands we can create pods.
kubectl run mypod --generator=run-pod/v1 --image=nginx --port=80 --labels="myapp=mynginxapp"
here i created pod name called 'mypod' with label 'myapp=mynginxapp'.
Creating ClusterIP Service:
To create a service we can use kubectl expose command or we can create service with yml file.
apiVersion: v1 kind: Service metadata: name: mynginxsvc spec: type: ClusterIP ports: - port: 80 name: http - port: 443 name: https selector: myapp: mynginxapp
List services
list kubernetes services with kubectl get command
master $ kubectl get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 20m mynginxsvc ClusterIP 10.111.129.81 <none> 80/TCP,443/TCP 13s
Here you can see the cluster ip and ports, you can access the nginx app from <clusterip>:<cluster port> i,e 10.111.129.81:80.
from above service of type Cluster-IP is created which would accept traffic on port 80(cluster port) from other pods and forward the traffic on port 80 of the pods with mynginxapp label.
Verify the ClusterIP Service:
kubectl exec -it mypod curl 10.111.129.81:80
using above command you can curl output of nginx app. most of the times curl is not available in nginx pod. so install curl command in your 'mypod'
kubectl exec -it mypod sh you will enter into shell of mypod, after entering into shell install curl. apt update -y apt install curl -y
after installing curl in the pod execute curl <clusterip>:<cluster port>
# curl 10.111.129.81:80 <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style>
Tip: we can expose a headless service by setting --cluster-ip=None
ClusterIP exposes the service on a cluster-internal IP. This IP address makes the service only reachable from within the cluster.