This article shows how to perform basic operations with k8s Services
Service is a k8s entity for providing reliable network endpoint for pods (since pods` IP addresses are not reliable - addresses are changed when pods are restarted/recreated etc.) . Moreover Services provide with basic load-balancing capabilities.
Services are coupled with pods using labels - the same technology as for pods and ReplicaSets.
For the example lets say we have a ReplicaSet named web-rs already created and containing several pods.
Imperative way of creating a service for ReplicaSet (not recommended):
kubectl expose rs web-rs --name=hello-svc --target-port=8080 --type=NodePort
Now let`s inspect newly created Service:
kubectl describe svc hello-svc
Deleting Service:
kubectl delete svc hello-svc
Declarative way of creating Services (preferred):
Create example service.yml file:
apiVersion: v1
kind: Service
metadata:
name: hello-svc
labels:
app: hello-world
spec:
type: NodePort
ports:
- port: 8080
nodePort: 30001
protocol: TCP
selector:
app: hello-world
kind: Service
metadata:
name: hello-svc
labels:
app: hello-world
spec:
type: NodePort
ports:
- port: 8080
nodePort: 30001
protocol: TCP
selector:
app: hello-world
There are 3 types of Service types:
ClusterIP. This is the default option, and gives the Service a stable IP address internally within the cluster. It will not make the Service available outside of the cluster.
NodePort. This builds on top of ClusterIP and adds a cluster-wide TCP or UDP port. It makes the Service available outside of the cluster on this port.
LoadBalancer. This builds on top of NodePort and integrates with cloud- native load-balancers.
NodePort. This builds on top of ClusterIP and adds a cluster-wide TCP or UDP port. It makes the Service available outside of the cluster on this port.
LoadBalancer. This builds on top of NodePort and integrates with cloud- native load-balancers.
Create Service:
kubectl create -f ./service.yml
Inspect service:
kubectl get svc hello-svc
kubectl get svc hello-svc -o=yaml
kubectl describe svc hello-svc
While creating Service object one more object is automatically created behind the scenes - Endpoint. This object is capable of monitoring pods which should be coupled with the service according to labels.
kubectl get ep hello-svc