How to create Service Using Kubernetes Python Client

code coding computer cyberspace
Reading Time: 2 minutes

Hello Readers! In this blog, we will see how we can create a service using the Kubernetes Python client. As we all know that we use kubectl commands for creating, listing, updating, and deleting the Kubernetes resources.

What is service in Kubernetes?

A cluster’s deployed collection of pods is logically abstracted as a Kubernetes service (which all perform the same function). Since pods are transient, a service allows a collection of pods that perform related tasks (such as web services, image processing, etc.) to be given a name and distinctive IP address (clusterIP).

Installing Python Kubernetes Client :

Before we move forward with creating a service using the K8s python client we have some prerequisites that we need to follow.

Kubernetes library provides us modules such as client and config which we will use here. So, let’s install Kubernetes Python Client:

pip3 install kubernetes

In my case I have already installed it, that’s why it shows us already satisfied.

Now, we have the python-Kubernetes package installed.

Create Service:

Now, I will create one directory and inside this, I will make a file named 

mkdir service
cd service

Now that we have the k8s package installed, we can import it as:

from kubernetes import client, config

My file contains the following code for creating a job using Kubernetes Python Client.

Code for creating Service via Kubernetes Python client :

from kubernetes import client, config

def create_service(core_v1_api):

    body = client.V1Service(







            selector={"app": "redis"},









    core_v1_api.create_namespaced_service(namespace="default", body=body)

def main():


    apps_v1_api = client.AppsV1Api()

    core_v1_api = client.CoreV1Api()

if __name__ == "__main__":


Now, It’s time to create the service. So, I will now run the python code.


Now, if I check whether my service is created or not so I will simply run the command :

kubectl get svc

As you can see here my service named –> redis-test-svc is successfully created.

So, We are successfully done now. This is how we can play with the K8s python client.

Conclusion :

So, in this blog, we have seen how easily we created a service using the k8s python client. I hope this blog will help you. Thank you for sticking to the end. If you liked my blog please do share.

Reference :

Written by 

Ashi Dubey is a Software Intern at Knoldus Inc Software. She has a keen interest toward learning new technologies. Her practice area is Devops. When not working, you will find her with a Book.