Daniel
Daniel

Reputation: 151

how to enable port-forward in a k8s service yaml

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

Upvotes: 7

Views: 20058

Answers (3)

DT.
DT.

Reputation: 3551

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
metadata:
  labels:
    name: app1
  name: app1
spec:
  ports:
  - name: "80"
    port: 8888
    targetPort: 80
  selector:
    name: app1
  type: NodePort

Upvotes: 7

Kushal Arya
Kushal Arya

Reputation: 364

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

Upvotes: 3

P Ekambaram
P Ekambaram

Reputation: 17615

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

Upvotes: 0

Related Questions