DEV Community

DevCorner
DevCorner

Posted on

Understanding Kubernetes Networking: Exposing Pods Inside and Outside the Cluster🚀

In Kubernetes, a pod can be exposed in different ways depending on where the traffic is coming from:

1️⃣ Port Inside the Container

Each container inside a pod listens on a specific containerPort. This is defined in the pod spec.

spec:
  containers:
  - name: my-container
    image: my-image
    ports:
    - containerPort: 8080
Enter fullscreen mode Exit fullscreen mode

🔹 containerPort → The port where the application inside the container listens.


2️⃣ Port Exposed to Other Pods (Cluster Communication)

To allow other pods in the cluster to access this pod, you need a Service.

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: my-app
  ports:
  - protocol: TCP
    port: 80       # Service port
    targetPort: 8080  # Container port
  type: ClusterIP
Enter fullscreen mode Exit fullscreen mode

🔹 ClusterIP is the default service type and allows other pods in the cluster to communicate using my-service:80.


3️⃣ Port Exposed Outside the Cluster (External Access)

If you need external access, you can use NodePort or LoadBalancer:

🔸 NodePort (Exposing on Every Node’s IP)

apiVersion: v1
kind: Service
metadata:
  name: my-nodeport-service
spec:
  selector:
    app: my-app
  ports:
  - protocol: TCP
    port: 80        # Service port inside cluster
    targetPort: 8080 # Container port
    nodePort: 30080 # Exposed on every node
  type: NodePort
Enter fullscreen mode Exit fullscreen mode

📌 The pod will be accessible at http://<NodeIP>:30080.

🔸 LoadBalancer (Cloud Provider External IP)

apiVersion: v1
kind: Service
metadata:
  name: my-loadbalancer-service
spec:
  selector:
    app: my-app
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8080
  type: LoadBalancer
Enter fullscreen mode Exit fullscreen mode

📌 The cloud provider will assign an external IP to access the service.


🔹 Summary

Scope Port Configuration
Inside Pod (Container) containerPort
Between Pods (Cluster) ClusterIP Service (port & targetPort)
External Access NodePort or LoadBalancer

Let me know if you need further clarification! 🚀

Top comments (0)