kuberneteskubernetes-podkubernetes-service

Cannot connect to Kubernetes NodePort Service


I have a running pod that was created with the following pod-definition.yaml:

apiVersion: v1
kind: Pod
metadata:
    name: microservice-one-pod-name
    labels:
        app: microservice-one-app-label
        type: front-end
spec:
    containers:
    - name: microservice-one
      image: vismarkjuarez1994/microserviceone
      ports:
      - containerPort: 2019

I then created a Service using the following service-definition.yaml:

kind: Service
apiVersion: v1
metadata:
  name: microserviceone-service
spec:
  ports:
    - port: 30008
      targetPort: 2019
      protocol: TCP
  selector:
    app: microservice-one-app-label
  type: NodePort

I then ran kubectl describe node minikube to find the Node IP I should be connecting to -- which yielded:

Addresses:
  InternalIP:  192.168.49.2
  Hostname:    minikube

But I get no response when I run the following curl command:

curl 192.168.49.2:30008

The request also times out when I try to access 192.168.49.2:30008 from a browser.

The pod logs show that the container is up and running. Why can't I access my Service?


Solution

  • The problem is that you are trying to access your service at the port parameter which is the internal port at which the service will be exposed, even when using NodePort type.

    The parameter you were searching is called nodePort, which can optionally be specified together with port and targetPort. Quoting the documentation:

    By default and for convenience, the Kubernetes control plane will allocate a port from a range (default: 30000-32767)

    Since you didn't specify the nodePort, one in the range was automatically picked up. You can check which one by:

    kubectl get svc -owide
    

    And then access your service externally at that port.

    As an alternative, you can change your service definition to be something like:

    kind: Service
    apiVersion: v1
    metadata:
      name: microserviceone-service
    spec:
      ports:
        - port: 30008
          targetPort: 2019
          nodePort: 30008
          protocol: TCP
      selector:
        app: microservice-one-app-label
      type: NodePort
    

    But take in mind that you may need to delete your service and create it again in order to change the nodePort allocated.