Search code examples
kuberneteskubectlkubeadmkube-apiserver

How can I access to services outside the cluster using kubectl proxy?


When we spin up a cluster with kubeadm in kubernetes, and the service's .yaml file looks like this :

apiVersion: v1
kind: Service
metadata:
  name: neo4j
  labels:
    app: neo4j
    component: core
spec:
  clusterIP: None
  ports:
    - port: 7474
      targetPort: 7474
      name: browser
    - port: 6362
      targetPort: 6362
      name: backup
  selector:
    app: neo4j
    component: core

After all pods and services run, I do kubectl proxy and it says :

Starting to serve on 127.0.0.1:8001

So when I want to access to this service like :

curl localhost:8001/api/

it's just reachable inside the cluster! How can I reach to services outside the cluster?


Solution

  • You should expose your service using NodePort:

    apiVersion: v1
    kind: Service
    metadata:
      name: neo4j
      labels:
        app: neo4j
        component: core
    spec:
      externalTrafficPolicy: Local
      type: NodePort
      ports:
        - port: 7474
          targetPort: 7474
          name: browser
        - port: 6362
          targetPort: 6362
          name: backup
      selector:
        app: neo4j
        component: core
    

    Now if you describe your service using

     kubectl describe svc neo4j
    

    You will get a nodeport value which will be in between 30000-32767 and you can access your service from outside the cluster using

    curl http://<node_ip>:<node_port>
    

    Hope this helps.

    EDIT: Yes you can't directly use clusterIP: None in case of exposing service through NodePort. Now clusterIP: None means there is no internal load balancing done by kubernetes and for that we can also use externalTrafficPolicy=Local in service definition.

    Alternatively, you might be able to use an ingress to route traffic to the correct Service.