Not able to access service by service name on kubernetes

1/20/2020

I am using below manifest. I am having a simple server which prints pod name on /hello. Here, I was going through kubernetes documentation and it mentioned that we can access service via service name as well. But that is not working for me. As this is a service of type NodePort, I am able to access it using IP of one of the nodes. Is there something wrong with my manifest?

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myhttpserver
  labels:
    day: zero
    name: httppod
spec:
  replicas: 1
  selector:
    matchLabels:
      name: httppod
      day: zero
  template:
    metadata:
      labels:
        day: zero
        name: httppod
    spec:
      containers:
        - name: myappcont
          image: agoyalib/trial:tryit
          imagePullPolicy: IfNotPresent
---
apiVersion: v1
kind: Service
metadata:
  name: servit
  labels:
    day: zeroserv
spec:
  type: NodePort
  selector:
    day: zero
    name: httppod
  ports:
    - name: mine
      port: 8080
      targetPort: 8090

Edit: I created my own mini k8s cluster and I am doing these operations on the master node.

-- Gauranga
kubernetes

2 Answers

1/20/2020

From what I understand when you say

As this is a service of type NodePort, I am able to access it using IP of one of the nodes

You're accessing your service from outside your cluster. That's why you can't access it using its name.

To access a service using its name, you need to be inside the cluster.

Below is an example where you use a pod based on centos in order to connect to your service using its name :

# Here we're just creating a pod based on centos
$ kubectl run centos --image=centos:7 --generator=run-pod/v1 --command sleep infinity

# Now let's connect to that pod 
$ kubectl exec centos -ti bash
[root@centos /]# curl servit:8080/hello
-- Marc ABOUCHACRA
Source: StackOverflow

1/20/2020

You need to be inside cluster meaning you can access it from another pod.

kubectl run --generator=run-pod/v1 test-nslookup --image=busybox:1.28 --rm -it -- nslookup servit
-- Arghya Sadhu
Source: StackOverflow