Configuring Kubernetes Service Ports
Kubernetes Service ports are a crucial aspect of connecting Pods to the network and exposing applications to clients. Understanding how to configure Service ports is essential for effectively deploying and managing applications in a Kubernetes cluster.
Service Ports and Target Ports
When defining a Kubernetes Service, you need to configure two types of ports:
- Service Port: This is the port on which the Service will listen for incoming traffic.
- Target Port: This is the port on the target Pods that the Service will forward traffic to.
Here's an example Service configuration:
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
ports:
- port: 80
targetPort: 8080
selector:
app: my-app
In this example, the Service will listen on port 80 and forward traffic to port 8080 on the target Pods.
Port Mapping
Kubernetes allows you to configure different port numbers for the Service port and the target port. This is known as port mapping, and it's useful when you need to expose an application on a specific port, but the application itself is running on a different port inside the container.
Here's an example of port mapping:
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
ports:
- port: 80
targetPort: 8080
selector:
app: my-app
In this case, the Service will listen on port 80 and forward traffic to port 8080 on the target Pods.
Multiple Ports
Kubernetes Services can expose multiple ports simultaneously. This is useful when you have an application that provides multiple services or protocols, each running on a different port.
Here's an example of a Service with multiple ports:
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
ports:
- port: 80
targetPort: 8080
- port: 443
targetPort: 8443
selector:
app: my-app
In this example, the Service exposes two ports: port 80 (forwarding to 8080) and port 443 (forwarding to 8443) on the target Pods.