Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create a service in Kubernetes that exposes individual pods through a NodePort that corresponds with the node they are scheduled on, you can follow these steps:

  1. Create a deployment that defines the pods you want to expose. For example, let's say you want to deploy nginx pods:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80
  1. Create a service that exposes the pods with a NodePort:
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app: nginx
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
  type: NodePort
  1. Create a custom script that uses Kubernetes API to get the nodes and their addresses, and then maps each pod to the corresponding node port. For example, you can use Python with the 'kubernetes' library:
from kubernetes import client, config

# Load Kubernetes config
config.load_kube_config()

# Create Kubernetes API client
api = client.CoreV1Api()

# Get all nodes and their addresses
nodes = api.list_node()
node_addrs = {}
for node in nodes.items:
    node_addrs[node.metadata.name] = node.status.addresses[0].address

# Get all pods and their node name
pods = api.list_pod_for_all_namespaces()
pod_nodes = {}
for pod in pods.items:
    pod_nodes[pod.metadata.name] = pod.spec.node_name

# Map each pod to the corresponding node port
for pod_name, node_name in pod_nodes.items():
    node_addr = node_addrs[node_name]
    node_port = int(pod_name[-5:]) + 30000 # calculate node port from pod name
    endpoints = [client.V1EndpointAddress(ip=node_addr, target_ref=client.V1ObjectReference(kind='Pod', name=pod_name))]
    subset = client.V1EndpointSubset(addresses=endpoints)
    api.patch_namespaced_endpoints(name='nginx-service', namespace='default', body=client.V1Endpoints(subsets=[subset]), subresource='')

  1. Run the script as a Kubernetes job or as a standalone process on a schedule.

This script retrieves all the nodes in the cluster and their addresses. It then retrieves all the pods in the cluster, and for each pod, it retrieves the name of the node on which the pod is scheduled. It then calculates the node port from the last 5 digits of the pod name (assuming the pod name ends with a 5-digit random string), and patches the endpoints of the 'nginx-service' service to map the pod to the correct node IP and port. This will effectively expose each pod through a NodePort that corresponds with the node they are scheduled on.