简体   繁体   中英

Not able to access service by service name on kubernetes

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.

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

您需要在集群内部,这意味着您可以从另一个 pod 访问它。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM