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: LoadBalancerExample
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: LoadBalancerOutput
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: LoadBalancerQuick Reference
| Service Type | Description | Use Case |
|---|---|---|
| LoadBalancer | Creates external load balancer with public IP | Cloud environments with LB support |
| NodePort | Opens fixed port on all nodes | Simple external access or on-prem clusters |
| Ingress | Manages HTTP/S routing and TLS | Complex 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.