Question format
expose a existing pod called nginxpod, service name as nginnodeportsvc, service should access through Nodeport Nodeport= 30200
Prerequisites
A running Kubernetes cluster.
An existing pod named nginxpod (e.g., using the nginx image).
kubectl configured to interact with the cluster.
Step 1: Verify the Existing Pod
First, confirm that the pod nginxpod is running and note its labels. Labels are critical for the service to route traffic to the correct pod.
kubectl get pods --show-labels
Example output:
NAME READY STATUS LABELS
nginxpod 1/1 Running app=nginx
If the pod lacks labels, add them using:
kubectl label pod nginxpod app=nginx
Step 2: Create the NodePort Service
Create a YAML file (e.g., nginx-nodeport-svc.yaml) to define the NodePort service. The service will target the pod via its labels and expose port 30200 on all cluster nodes.
apiVersion: v1
kind: Service
metadata:
name: nginnodeportsvc
spec:
type: NodePort
selector:
app: nginx # Must match the pod's label
ports:
- protocol: TCP
port: 80 # Service port (accessible internally)
targetPort: 80 # Pod's container port (nginx default: 80)
nodePort: 30200 # Exposed on all nodes at port 30200
Make sure:
selector: Matches the pod’s label (app=nginx).
nodePort: The static port (30200) assigned to the service.
Step 3: Deploy the Service
Apply the YAML configuration to create the service:
kubectl apply -f nginx-nodeport-svc.yaml
Verify the service and its assigned NodePort:
kubectl get svc nginnodeportsvc
Example output:
NAME TYPE CLUSTER-IP PORT(S) AGE
nginnodeportsvc NodePort 10.96.123.45 80:30200/TCP 10s
Step 4: Test Access to the Pod
The pod is now accessible through any node’s IP address on port 30200.
Get the IP address of a node in your cluster:
kubectl get nodes -o wide
Use curl or a browser to access the service:
curl http://<NODE_IP>:30200
Replace <NODE_IP> with the actual IP of any cluster node.
If successful, you’ll see the default NGINX welcome page.
Troubleshooting
Service not accessible:
Ensure the pod’s label (app=nginx) matches the service’s selector.
Check if the pod is running:
kubectl describe pod nginxpod
Firewall issues:
Ensure port 30200 is open in your cloud provider’s firewall or local network.
Port conflicts:
Confirm no other service is using 30200 (NodePort range: 30000-32767).