Services help to enable communication to a pod or group of pods. Calls are made to a service, and then one or more pods sit behind that service and handle requests made to that particular service.
This type of service will create internal cluster IP Addresses for each service inside the cluster. This allows communication between the individual services via IP address. This is the default service type and will be created if no TYPE is specified.
apiVersion: v1
kind: Service
metadata:
name: back-end
spec:
type: ClusterIP
ports:
- port: 80
targetPort: 80
selector:
app: my-app
tier: back-end
k get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
back-end ClusterIP 10.111.141.23 <none> 80/TCP 38s
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 33d
One type of service is called a NodePort service. This type of service listens on a specific port of the kubernetes node and listens for requests and forwards them to any pods associated with that service. This sort of acts as a service and ingress all in one.
There are several ports to be aware of with the NodePort service.
To call this service from outside the cluster, you would need to specify the node_ipaddress:NodePort (192.168.1.2:30008)
. From inside the clusters, to access this service, you woud use the service_ip:service_port. (10.106.1.12:80)
apiVersion: v1
kind: Service
metadata:
name: myapp-service
spec:
type: NodePort
ports:
- name: http
targetPort: 80
port: 80
nodePort: 30008
- name: https
targetPort: 443
port: 443
nodePort: 30009
selector:
app: my-app
type: front-end
Sample pod def that will use this service:
apiVersion: v1
kind: Pod
metadata:
name: my-app
labels:
app: my-app #used in service selector
type: front-end #used in service selector
spec:
containers:
- name: my-app-front-end
image: nginx
ports:
- name: http
containerPort: 80
- name: https
containerPort: 443
kubectl create -f service.yml
service "myapp-service" created
$ kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 30d
myapp-service NodePort 10.105.188.150 <none> 80:30008/TCP,443:30009/TCP 49s
As additional pods are added with the same labels as in the service selector section, traffic will also be routed to them from the service. It makes the service a built in load balancer across all the pods.
The NodePort service is made available across all nodes in the clusters, so you can access the service using any node ip address and the nodePort port number: