How Do You Define a Kubernetes Service TargetPort as a String?
A simple example of defining the targetPort as string is to first define it in the Deployment before you can refer to it as a string in targetPort in a service. Below is the simple example to show how to map "http" ( port name) from deployment in a service targetPort spec.
Deployment:
apiVersion: apps/v1kind: Deploymentmetadata: name: backendspec: selector: matchLabels: app: hello tier: backend track: stable replicas: 3 template: metadata: labels: app: hello tier: backend track: stable spec: containers: - name: hello image: "gcr.io/google-samples/hello-go-gke:1.0" ports: - name: http containerPort: 80
Service:
apiVersion: v1kind: Servicemetadata: name: hellospec: selector: app: hello tier: backend ports: - protocol: TCP port: 80 targetPort: http
You can set targetPort to an integer value or a name.
If you refer to it by name, that name has to be defined within the pod(s) in spec > containers[n] > ports[n] > name
If you refer by integer, there is no need to define ports in pods at all, although it's reasonable to still do it for clarity.
By providing a matching port name in the Deployment, things appear to work properly:
ports:- name: web containerPort: 80