Multi-Port Services
What you'll learn: How to expose multiple ports from a single Kubernetes Service and use named ports for clarity.
Why Multiple Ports?
So far, you've seen Services exposing a single port. But what if your application listens on multiple ports? For example, a web server might serve HTTP on port 8080 and a metrics endpoint on port 9090. Rather than creating two separate Services, you can expose both ports through one Service.
How It Works
A Service can define multiple ports in its ports array. Each port gets its own configuration with port (the Service's port), targetPort (the Pod's port), and optionally protocol.
The key feature: named ports. Instead of just numbers, you give each port a descriptive name. This makes your configuration self-documenting and easier to maintain.
Named Ports for Clarity
Think of named ports like labeled outlets on a power strip. Instead of remembering "plug your laptop into outlet 3," you see a label that says "LAPTOP." Similarly, instead of remembering "port 8080 is HTTP," you name it http.
Here's the pattern in a Service spec:
ports:
- name: http
port: 80
targetPort: 8080
protocol: TCP
- name: metrics
port: 9090
targetPort: 9090
protocol: TCP
Now other resources or documentation can refer to the http port by name instead of number. If you ever change the port numbers, the names remain stable.
When to Use This
Multi-port Services are ideal when:
- One application serves different functions on different ports
- You want to keep related ports grouped under one Service name
- You need clearer configuration through named ports
Key Takeaway: Multi-port Services let you expose several ports from a single Service, and naming those ports makes your configuration more maintainable and self-documenting.