0
0
KubernetesHow-ToBeginner · 4 min read

How to Expose Service Externally in Kubernetes: Simple Guide

To expose a service externally in Kubernetes, use a Service of type LoadBalancer or NodePort. Alternatively, use an Ingress resource to manage external access with routing rules and TLS support.
📐

Syntax

To expose a service externally, you define a Service resource with a specific type. The main types are:

  • LoadBalancer: Creates an external load balancer (cloud provider dependent).
  • NodePort: Opens a static port on each node to forward traffic to the service.
  • Ingress: Manages external HTTP(S) access with routing rules.

Each type has a specific YAML structure to configure.

yaml
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: my-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: LoadBalancer
💻

Example

This example shows how to expose a simple web app externally using a LoadBalancer service. It forwards external port 80 to the app's port 8080 inside the cluster.

yaml
apiVersion: v1
kind: Service
metadata:
  name: webapp-service
spec:
  selector:
    app: webapp
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: LoadBalancer
Output
service/webapp-service created EXTERNAL-IP will be assigned by cloud provider
⚠️

Common Pitfalls

1. No External IP Assigned: When using LoadBalancer, the external IP may take time or fail if your cluster is not on a supported cloud provider.

2. Using NodePort without firewall rules: External traffic won't reach the node port if firewall blocks it.

3. Forgetting selector labels: The service won't route traffic if selectors don't match pod labels.

yaml
apiVersion: v1
kind: Service
metadata:
  name: wrong-service
spec:
  selector:
    app: wrong-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: LoadBalancer

---
# Correct selector example
apiVersion: v1
kind: Service
metadata:
  name: correct-service
spec:
  selector:
    app: webapp
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: LoadBalancer
📊

Quick Reference

Service TypeDescriptionUse Case
LoadBalancerCreates external load balancer with public IPCloud environments with LB support
NodePortOpens fixed port on all nodesSimple external access or on-prem clusters
IngressManages HTTP/S routing and TLSComplex routing and multiple services

Key Takeaways

Use Service type LoadBalancer to get an external IP automatically in supported clouds.
NodePort exposes service on a static port on each node but may need firewall rules.
Ingress provides flexible HTTP/S routing and TLS termination for multiple services.
Always ensure service selectors match pod labels to route traffic correctly.
External IP assignment may take time or fail if cloud provider support is missing.