Advanced Port Mapping
Introduction: Real-World Port Mapping Challenges
In the previous lesson, you learned how NodePort Services expose applications externally using a three-port system: targetPort (where your container listens), port (for internal cluster access), and nodePort (for external access). Those examples used single containers with single ports, which works great for simple applications. However, real-world applications are rarely that simple. You might run a web server alongside a metrics exporter in the same Pod, or expose both an HTTP API and an admin interface on different ports. You might need to standardize your Service ports across different applications while each application uses different internal ports.
This lesson teaches you advanced port mapping patterns that handle these complex scenarios. You'll learn how to expose multiple ports from multi-container Pods, use named port references to decouple configuration from implementation, and debug port misconfigurations when things don't work as expected. By the end, you'll be able to design flexible Service architectures that support sidecars, observability tools, and multiple protocols running together.
Multi-Container Pods with Multiple Ports
Let's start with a common real-world scenario: you have a web application that needs to expose both its main HTTP interface and a metrics endpoint for monitoring. The best practice is to run these as separate containers in the same Pod — your main application container and a sidecar container that exports metrics. Each container listens on its own port, and you need a Service that can route traffic to both ports. This is where multi-port Services come in. A multi-port Service defines multiple port entries, each with its own targetPort that routes to a specific container in your Pods.
Let's build this step by step. First, we'll create a Pod with two containers: an nginx web server and a Prometheus node exporter for metrics. The nginx container will listen on port 80, and the metrics exporter will listen on port 9100. Save this as deployment-multi-container.yaml:
We're creating a Pod (not a Deployment) to keep the example simple, but the same principles apply to Deployments. The app: multi-demo label is crucial — our Service will use this to find the Pod.
The first container runs nginx on port 80. The containerPort: 80 declaration tells Kubernetes that this container exposes port 80. While this declaration is technically optional for numeric port routing (the container will listen on port 80 regardless), it's a best practice because it documents which ports your container uses and enables named port references.
The second container runs the Prometheus node exporter, which exposes system metrics on port 9100 by default. Now we have a Pod with two containers listening on two different ports. Let's create it:
Let's verify both containers are running:
The READY column shows 2/2, confirming both containers are running.
