Pezhman Parsaee
Pezhman Parsaee

Reputation: 1249

Cannot access a Kubernetes NodePort service in Minikube

I am going to access a Kubernetes NodePort service in MacOS in the browser, running on minikube, but I can't.

This is the Service definition file:

apiVersion: v1
kind: Service
metadata:
  name: myapp-service
spec:
  type: NodePort
  ports:
    - port: 80
      targetPort: 80
      nodePort: 30004
  selector:
    app: myapp

And this is the Pod definition file:

apiVersion: v1
kind: Pod
metadata:
  name: nginx-2
  labels:
    env: production
    app: myapp
spec:
  containers:
    - name: nginx
      image: nginx

And this is the Deployment definition file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
  labels:
    tier: frontend
    app: myapp
spec:
  selector:
    matchLabels:
      env: production
  replicas: 6
  template:
    metadata:
      name: nginx-2
      labels:
        env: production
    spec:
      containers:
        - name: nginx
          image: nginx

I cannot access the NodePort service using this URL on the browser: http://localhost:30004

Also by entering minikube ip instead of localhost in the top command, a timeout happens.

And finally, by running the below command:

minikube service myapp-service --url

A sample output like this is generated:

http://127.0.0.1:53751 ❗ Because you are using a Docker driver on darwin, the terminal needs to be open to run it.

But an the below error is shown to the user:

The connection was reset

Update: the issue is because the label app:myapp was not mentioned in the Deployment definition file -> template section

Upvotes: 0

Views: 987

Answers (1)

Ralle Mc Black
Ralle Mc Black

Reputation: 1203

Look, your are not exposing your localhost to the nodePort. You are exposing the NodePort on your Kupernetes cluster.

So you have to access it http://nodeip:nodePort.

Think about what is localhost.

You have localhost on your Pc. You have localhost on the VM (minkube node). You have localhost in each container running inside your cluster.

If you want to use your Pc localhost to access the port inside a container in a Pod you can do this:

kubectl port-forward svc/serviceName reachablePortFromyourPc:containerPort

For example:

kubectl port-forward svc/serviceName 80:80

This starts a port forwarding. As long it is running you can access it from your browser.

This is good only for testing.

To access the NodePort use.

minikubeIp:NodePort

Upvotes: 1

Related Questions