Table of contents
What are Services in K8s
In Kubernetes, Services are objects that provide stable network identities to Pods and abstract away the details of Pod IP addresses. Services allow Pods to receive traffic from other Pods, Services, and external clients.
Task-1:
Create a Service for your todo-app Deployment from Day-32
Create a Service definition for your todo-app Deployment in a YAML file.
apiVersion: v1
kind: Service
metadata:
name: django-todo-service
namespace: django-todo-ns
spec:
type: NodePort
selector:
app: django-todo
ports:
# By default and for convenience, the `targetPort` is set to the same value as the `port` field.
- port: 80
targetPort: 8000
# Optional field
# By default and for convenience, the Kubernetes control plane will allocate a port from a range (default: 30000-32767)
nodePort: 30007
- Apply the Service definition to your K8s (minikube) cluster using the
kubectl apply -f service.yml -n <namespace-name>
command.
kubectl apply -f service.yml -n django-todo-ns
- Verify that the Service is working by accessing the todo-app using the Service's IP and Port in your Namespace.
Task-2:
Create a ClusterIP Service for accessing the todo-app from within the cluster
Create a ClusterIP Service definition for your todo-app Deployment in a YAML file.
Apply the ClusterIP Service definition to your K8s (minikube) cluster using the
kubectl apply -f cluster-ip-service.yml -n <namespace-name>
command.Verify that the ClusterIP Service is working by accessing the todo-app from another Pod in the cluster in your Namespace.
Create file vim cluster-ip-service.yml
Apply kubectl apply -f cluster-ip-service.yml
Check whether service is running -
kubectl get svc -n django-todo-ns
Step-4 Deploy another Pod in the django-todo-ns
namespace to test the service. You can use the following YAML definition to create a simple Pod:
apiVersion: v1
kind: Pod
metadata:
name: test-pod
namespace: django-todo-ns
spec:
containers:
- name: busybox
image: busybox
command: ['sh', '-c', 'while true; do wget -q -O- django-todo-cluster-ip-service:8000; done']
This Pod runs a simple busybox
container that repeatedly accesses the todo-app
service using wget
. The Pod should be able to access the django-todo-cluster-ip-service
service using its name and port number.
Apply the Pod definition using the following command:
kubectl apply -f test-pod.yml -n django-todo-ns
Now execute the pod
kubectl exec -it test-pod -n django-todo-ns -- /bin/sh
Test Todo app
wget -qO- http://10.96.190.151:8000
Now you sucessfuly Access it through another Port