How to create a Service

In this notebook, we show you how to create a Service. A service is a key Kubernetes API resource. It defines a networking abstraction to route traffic to a particular set of Pods using a label selection.


In [ ]:
from kubernetes import client, config

Load config from default location


In [ ]:
config.load_kube_config()

Create API endpoint instance


In [ ]:
api_instance = client.CoreV1Api()

Create API resource instances


In [ ]:
service = client.V1Service()

Fill required Service fields (apiVersion, kind, and metadata)


In [ ]:
service.api_version = "v1"
service.kind = "Service"
service.metadata = client.V1ObjectMeta(name="my-service")

Provide Service .spec description

Set Service object named my-service to target TCP port 9376 on any Pod with the 'app'='MyApp' label. The label selection allows Kubernetes to determine which Pod should receive traffic when the service is used.


In [ ]:
spec = client.V1ServiceSpec()
spec.selector = {"app": "MyApp"}
spec.ports = [client.V1ServicePort(protocol="TCP", port=80, target_port=9376)]
service.spec = spec

Create Service


In [ ]:
api_instance.create_namespaced_service(namespace="default", body=service)

Delete Service


In [ ]:
api_instance.delete_namespaced_service(name="my-service", namespace="default")

In [ ]: