how to enable port-forward in a k8s service yaml

2/13/2020

I'm trying to automate a pod deployment and can't seem to figure out how to forward traffic from outside the cluster to the pod from the yaml config.

Access is only possible from localhost but not when accessing the master IP. When separately applying 'kubectl port-forward --address 0.0.0.0 POD LISTEN_PORT:DEST_PORT' it works.

apiVersion: v1
kind: Service
type:
metadata:
  labels:
    name: app1
  name: app1
spec:
  ports:
  - name: "80"
    port: 8888
    targetPort: 80
  selector:
    name: app1
---
apiVersion: v1
kind: Pod
metadata:
  labels:
    name: app1
  name: app1
spec:
  containers:
  - image: nginx
    name: app1
    ports:
    - containerPort: 80
    resources:
      limits:
        cpu: 500m
        memory: "52428800"
      requests:
        cpu: 250m
        memory: "20971520"
  nodeSelector:
    slave: "one"
  restartPolicy: Never
-- Daniel
kubectl
kubernetes

3 Answers

2/13/2020

Ingress: exposes HTTP and HTTPS routes from outside the cluster to services within the cluster. Traffic routing is controlled by rules defined on the Ingress resource.

    internet
        |
   [ Ingress ]
   --|-----|--
   [ Services ]

Ingress isn’t a type of Service, but rather an object that acts as a reverse proxy and single entry-point to your cluster that routes the request to different services.

To create basic ingress,

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: test-ingress
spec:
  backend:
    serviceName: testsvc
    servicePort: 80
-- Kushal Arya
Source: StackOverflow

2/13/2020

You need to update the service type to NodePort.

type: NodePort

And then you would be able to access the service from using http://NODE_HOST:NODE_PORT

-- P Ekambaram
Source: StackOverflow

2/13/2020

Kubernetes ServiceTypes allow you to specify what kind of Service you want. The default is ClusterIP.

ClusterIP: Exposes the Service on a cluster-internal IP. Choosing this value makes the Service only reachable from within the cluster. This is the default ServiceType.

NodePort: Exposes the Service on each Node’s IP at a static port (the NodePort). A ClusterIP Service, to which the NodePort Service routes, is automatically created. You’ll be able to contact the NodePort Service, from outside the cluster, by requesting <NodeIP>:<NodePort>.

You should updated service yaml as below to createa NodePort to access by NodePort

apiVersion: v1
kind: Service
type:
metadata:
  labels:
    name: app1
  name: app1
spec:
  ports:
  - name: "80"
    port: 8888
    targetPort: 80
  selector:
    name: app1
  type: NodePort
-- DT.
Source: StackOverflow