Skip to content

NodePort — Cross-Namespace Service & Selector Mistakes

Reference: https://kubernetes.io/docs/concepts/services-networking/service/

See also: nodeport.md.md for full NodePort reference, port model, and debugging.


The Exercise

Create a NodePort service named app-service-cka in namespace nginx-app-space to expose deployment nginx-app-cka: - port and targetPort: 80 - protocol: TCP - nodePort: 31000


The Selector Problem — Same Mistake as Ingress

From the raw notes — what was written:

spec:
  selector:
    app.kubernetes.io/name: app-service-cka   # WRONG — this is YOUR service name

Same mistake as ingressClassName: nginx-ingress-resource (using your own resource's name). app-service-cka is the Service name — it has nothing to do with the pod labels on the deployment.

Before writing any service YAML, always check pod labels first:

kubectl get pods -n nginx-app-space --show-labels

Output might be:

NAME                             LABELS
nginx-app-cka-5b4f9c-abc12       app=nginx-app-cka,pod-template-hash=5b4f9c

The selector must match the pod labels on the deployment — app: nginx-app-cka here, not app.kubernetes.io/name: app-service-cka.


Correct YAML

apiVersion: v1
kind: Service
metadata:
  name: app-service-cka
  namespace: nginx-app-space
spec:
  type: NodePort
  selector:
    app: nginx-app-cka        # must match pod labels — verify with --show-labels first
  ports:
  - port: 80
    targetPort: 80
    protocol: TCP
    nodePort: 31000
kubectl apply -f app-service-cka.yml
kubectl get endpoints app-service-cka -n nginx-app-space   # verify pods are selected

If endpoints shows <none>, the selector is wrong. Fix it.


The -n Flag Is Required

The deployment is in nginx-app-space — not default. Every command needs -n nginx-app-space:

kubectl get pods -n nginx-app-space --show-labels
kubectl apply -f app-service-cka.yml           # namespace is in the YAML
kubectl describe svc app-service-cka -n nginx-app-space
kubectl get endpoints app-service-cka -n nginx-app-space

Forgetting -n and running against the default namespace = seeing nothing, or seeing the wrong resources.


Where to Get the Template

From the docs: kubernetes.io/docs/concepts/services-networking/service → Ctrl+F nodePort. Copy the NodePort example, change 4 fields: - metadata.name - metadata.namespace - spec.selector - spec.ports

Do not copy the template's selector blindly — it uses app.kubernetes.io/name: MyApp as a placeholder. Replace it with your actual pod labels from --show-labels.


Quick Reference

# Check pod labels before writing selector
kubectl get pods -n nginx-app-space --show-labels

# Apply
kubectl apply -f app-service-cka.yml

# Verify endpoints populated (not <none>)
kubectl get endpoints app-service-cka -n nginx-app-space

# Test access via nodePort
curl <NodeIP>:31000