通过这篇文章,我们要用到不同的kubectl命令,一些要在pod在运行,其他的需要在kubernetes node上执行。
一、准备阶段:
-
创建一个pod, 这里有两种方式创建pod, 一种直接使用命令行,一种是通过yaml文件:
a)kubectl run hostnames --image=k8s.gcr.io/serve_hostname \ --labels=app=hostnames \ --port=9376 \ --replicas=3 deployment.apps/hostnames created
这种方式等同于下面用yaml文件创建一个delpoyment对象
b)
apiVersion: apps/v1
kind: Deployment
metadata:
name: hostnames
spec:
selector:
matchLabels:
app: hostnames
replicas: 3
template:
metadata:
labels:
app: hostnames
spec:
containers:
- name: hostnames
image: k8s.gcr.io/serve_hostname
ports:
- containerPort: 9376
protocol: TCP
完成后确认一下pod是否正在运行:
kubectl get pods -l app=hostnames
NAME READY STATUS RESTARTS AGE
hostnames-632524106-bbpiw 1/1 Running 0 2m
hostnames-632524106-ly40y 1/1 Running 0 2m
hostnames-632524106-tlaok 1/1 Running 0 2m
二、检查service是否存在
到目前为止,我们并没有创建service. 如果我们现在访问一个不存在的service会发生什么?假定你有另一个pod正在通过service name 访问这个hostnames service.
u@pod$ wget -O- hostnames
Resolving hostnames (hostnames)... failed: Name or service not known.
wget: unable to resolve host address 'hostnames'
因此第一件事情我们要检查service是否真正存在:
kubectl get svc hostnames
No resources found.
Error from server (NotFound): services "hostnames" not found
下面我们创建一个service, 有两种方式可以创建,一种通过kubectl命令行和通过yaml文件
命令行创建service方式如下:
kubectl expose deployment hostnames --port=80 --target-port=9376
service/hostnames exposed
yaml文件方式创建service方式如下:
apiVersion: v1
kind: Service
metadata:
name: hostnames
spec:
selector:
app: hostnames
ports:
- name: default
protocol: TCP
port: 80
targetPort: 9376
现在我们查看一下service是否存在:
kubectl get svc hostnames
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
hostnames ClusterIP 10.0.1.175 <none> 80/TCP 5s
三、检查service是否可以被DNS 解析
a) 从同一个namespace下的pod检查:
u@pod$ nslookup hostnames
Address 1: 10.0.0.10 kube-dns.kube-system.svc.cluster.local
Name: hostnames
Address 1: 10.0.1.175 hostnames.default.svc.cluster.local
如果上面命令失败了, 有可能你的pod和service是在不同的namespace. 试一下service name上加上命名空间:
u@pod$ nslookup hostnames.default
Address 1: 10.0.0.10 kube-dns.kube-system.svc.cluster.local
Name: hostnames.default
Address 1: 10.0.1.175 hostnames.default.svc.cluster.local
如果上面命令运行成功,你需要调整你的app 使用servicename+ namespace 调用方式,或者让app和service 在同一个namespace下调用。
如果上面命令还是运行失败,试一下全限定的service name.
u@pod$ nslookup hostnames.default.svc.cluster.local
Address 1: 10.0.0.10 kube-dns.kube-system.svc.cluster.local
Name: hostnames.default.svc.cluster.local
Address 1: 10.0.1.175 hostnames.default.svc.cluster.local
注意service串的含义, “default.svc.cluster.local”, “default”是“namespace”. "svc“表示这是一个service. “cluster.local” 是你的cluster domain.
你还可以从cluster的node上执行此命令:(注意:下面10.0.0.10是我的dns service地址。)
u@node$ nslookup hostnames.default.svc.cluster.local 10.0.0.10
Server: 10.0.0.10
Address: 10.0.0.10#53
Name: hostnames.default.svc.cluster.local
Address: 10.0.1.175