- A+
前文我们了解了k8s的架构和基本的工作过程以及测试环境的k8s集群部署,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/14126750.html;今天我们主要来了解下k8s命令行工具kubectl的基础操作;
kubectl简介
kubectl是k8s官方提供的工具,它是一款命令行工具,我们可以使用它来部署k8s集群,管理k8s集群上的资源;kubectl这个工具有很多子命令,每个子命令都有不同的功能,比如创建资源我们可以使用create或apply子命令来实现;不同的是在k8s上创建资源的方式有两种,一种是陈述式接口,一种是声明式接口;所谓声明式接口就是把我们要创建的资源,通过写成一个配置文件,然后使用apply子命令应用指定的配置文件的方式;陈述式接口是指我们要在命令行告诉k8s怎么去创建资源,比如创建pod控制器,使用什么镜像,副本数量等等;通常我们使用create子命令来陈述创建一个资源;当然create子命令也可以指定一个资源清单的方式来创建资源;两者不同的是apply可以多次执行,如果发现对应清单有变化就应用变化部分,没变化就不应用;而create不能多次执行;
kubectl工具使用的语法
kubectl [flags] [options]
提示:flages是用来指定子命令,options是对应子命令的选项;
查看kubectl工具的使用帮助
[root@master01 ~]# kubectl --help kubectl controls the Kubernetes cluster manager. Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/ Basic Commands (Beginner): create Create a resource from a file or from stdin. expose Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service run Run a particular image on the cluster set Set specific features on objects Basic Commands (Intermediate): explain Documentation of resources get Display one or many resources edit Edit a resource on the server delete Delete resources by filenames, stdin, resources and names, or by resources and label selector Deploy Commands: rollout Manage the rollout of a resource scale Set a new size for a Deployment, ReplicaSet or Replication Controller autoscale Auto-scale a Deployment, ReplicaSet, or ReplicationController Cluster Management Commands: certificate Modify certificate resources. cluster-info Display cluster info top Display Resource (CPU/Memory/Storage) usage. cordon Mark node as unschedulable uncordon Mark node as schedulable drain Drain node in preparation for maintenance taint Update the taints on one or more nodes Troubleshooting and Debugging Commands: describe Show details of a specific resource or group of resources logs Print the logs for a container in a pod attach Attach to a running container exec Execute a command in a container port-forward Forward one or more local ports to a pod proxy Run a proxy to the Kubernetes API server cp Copy files and directories to and from containers. auth Inspect authorization debug Create debugging sessions for troubleshooting workloads and nodes Advanced Commands: diff Diff live version against would-be applied version apply Apply a configuration to a resource by filename or stdin patch Update field(s) of a resource replace Replace a resource by filename or stdin wait Experimental: Wait for a specific condition on one or many resources. kustomize Build a kustomization target from a directory or a remote url. Settings Commands: label Update the labels on a resource annotate Update the annotations on a resource completion Output shell completion code for the specified shell (bash or zsh) Other Commands: api-resources Print the supported API resources on the server api-versions Print the supported API versions on the server, in the form of "group/version" config Modify kubeconfig files plugin Provides utilities for interacting with plugins. version Print the client and server version information Usage: kubectl [flags] [options] Use "kubectl <command> --help" for more information about a given command. Use "kubectl options" for a list of global command-line options (applies to all commands). [root@master01 ~]#
查看子命令帮助
[root@master01 ~]# kubectl create --help Create a resource from a file or from stdin. JSON and YAML formats are accepted. Examples: # Create a pod using the data in pod.json. kubectl create -f ./pod.json # Create a pod based on the JSON passed into stdin. cat pod.json | kubectl create -f - # Edit the data in docker-registry.yaml in JSON then create the resource using the edited data. kubectl create -f docker-registry.yaml --edit -o json Available Commands: clusterrole Create a ClusterRole. clusterrolebinding Create a ClusterRoleBinding for a particular ClusterRole configmap Create a configmap from a local file, directory or literal value cronjob Create a cronjob with the specified name. deployment Create a deployment with the specified name. ingress Create an ingress with the specified name. job Create a job with the specified name. namespace Create a namespace with the specified name poddisruptionbudget Create a pod disruption budget with the specified name. priorityclass Create a priorityclass with the specified name. quota Create a quota with the specified name. role Create a role with single rule. rolebinding Create a RoleBinding for a particular Role or ClusterRole secret Create a secret using specified subcommand service Create a service using specified subcommand. serviceaccount Create a service account with the specified name Options: --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. --dry-run='none': Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. --edit=false: Edit the API resource before creating --field-manager='kubectl-create': Name of the manager used to track field ownership. -f, --filename=[]: Filename, directory, or URL to files to use to create the resource -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R. -o, --output='': Output format. One of: json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file. --raw='': Raw URI to POST to the server. Uses the transport specified by the kubeconfig file. --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2) --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. --validate=true: If true, use a schema to validate the input before sending it --windows-line-endings=false: Only relevant if --edit=true. Defaults to the line ending native to your platform. Usage: kubectl create -f FILENAME [options] Use "kubectl <command> --help" for more information about a given command. Use "kubectl options" for a list of global command-line options (applies to all commands). [root@master01 ~]#
提示:create是用来创建一个资源,在k8s上资源有很多类型,使用不同的子命令表示创建不同类型的资源,当然创建不同类型的资源对应的选项也有所不同;
查看创建控制器deploy的帮助
[root@master01 ~]# kubectl create deploy --help Create a deployment with the specified name. Aliases: deployment, deploy Examples: # Create a deployment named my-dep that runs the busybox image. kubectl create deployment my-dep --image=busybox # Create a deployment with command kubectl create deployment my-dep --image=busybox -- date # Create a deployment named my-dep that runs the nginx image with 3 replicas. kubectl create deployment my-dep --image=nginx --replicas=3 # Create a deployment named my-dep that runs the busybox image and expose port 5701. kubectl create deployment my-dep --image=busybox --port=5701 Options: --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. --dry-run='none': Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. --field-manager='kubectl-create': Name of the manager used to track field ownership. --image=[]: Image names to run. -o, --output='': Output format. One of: json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file. --port=-1: The port that this container exposes. -r, --replicas=1: Number of replicas to create. Default is 1. --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. --validate=true: If true, use a schema to validate the input before sending it Usage: kubectl create deployment NAME --image=image -- [COMMAND] [args...] [options] Use "kubectl options" for a list of global command-line options (applies to all commands). [root@master01 ~]#
提示:deploy是pod控制器,创建pod控制器需要指定对应控制器要使用那个镜像来运行pod,其次要指定pod里运行容器的副本数量,默认不指定就表示默认副本为1;
示例:创建一个nginx pod控制器,指定使用nginx:1.14-alpine镜像来运行pod
[root@master01 ~]# kubectl create deploy ngx-dep --image=nginx:1.14-alpine deployment.apps/ngx-dep created [root@master01 ~]#
查看pod创建情况
[root@master01 ~]# kubectl get pod NAME READY STATUS RESTARTS AGE nginx-dep-8967df55d-j8zp7 1/1 Running 0 71m ngx-dep-5c8d96d457-62qd6 1/1 Running 0 33s [root@master01 ~]#
提示:在k8s上资源有两种级别,第一种是集群级别,第二种是名称空间级别;所谓名称空间就是把资源用逻辑的方式隔离的机制;在同一名称空间资源的名称不能相同;默认不指定名称空间,都是default名称空间;
查看长格式pod信息
[root@master01 ~]# kubectl get pod -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES nginx-dep-8967df55d-j8zp7 1/1 Running 0 74m 10.244.2.2 node02.k8s.org <none> <none> ngx-dep-5c8d96d457-62qd6 1/1 Running 0 3m47s 10.244.1.2 node01.k8s.org <none> <none> [root@master01 ~]#
提示:-o用于指定输出格式,常用的有3个值,wide表示显示长格式信息,这种现实方式能够列出对应资源运行在那个node上,ip地址是多少等等信息;yaml表示输出yaml格式的,json表示输出为json配置文件的方式;
创建名称空间
[root@master01 ~]# kubectl create namespace testing namespace/testing created [root@master01 ~]# kubectl create namespace prod namespace/prod created [root@master01 ~]# kubectl create namespace develop namespace/develop created [root@master01 ~]#
查看名称空间
[root@master01 ~]# kubectl get namespaces NAME STATUS AGE default Active 132m develop Active 31s kube-node-lease Active 132m kube-public Active 132m kube-system Active 132m prod Active 41s testing Active 57s [root@master01 ~]#
提示:在k8s中资源类型是有简写格式,比如namespace可以简写为ns,service可以简写为svc;
删除名称空间
[root@master01 ~]# kubectl get ns NAME STATUS AGE default Active 134m develop Active 2m1s kube-node-lease Active 134m kube-public Active 134m kube-system Active 134m prod Active 2m11s testing Active 2m27s [root@master01 ~]# kubectl delete ns testing namespace "testing" deleted [root@master01 ~]# kubectl get ns NAME STATUS AGE default Active 134m develop Active 2m26s kube-node-lease Active 134m kube-public Active 134m kube-system Active 134m prod Active 2m36s [root@master01 ~]#
提示:除了以上方式删除资源,我们也可以使用资源类型/资源名称的方式来指定资源;用空白字符隔开资源类型和名称的方式只能一次删除一个资源,而用斜线隔开的可以一次删除多个资源;
删除develop、prod名称空间
[root@master01 ~]# kubectl get ns NAME STATUS AGE default Active 136m develop Active 4m20s kube-node-lease Active 136m kube-public Active 136m kube-system Active 136m prod Active 4m30s [root@master01 ~]# kubectl delete ns/develop ns/prod namespace "develop" deleted namespace "prod" deleted [root@master01 ~]# kubectl get ns NAME STATUS AGE default Active 137m kube-node-lease Active 137m kube-public Active 137m kube-system Active 137m [root@master01 ~]#
删除pod
[root@master01 ~]# kubectl get pod NAME READY STATUS RESTARTS AGE nginx-dep-8967df55d-j8zp7 1/1 Running 0 85m ngx-dep-5c8d96d457-62qd6 1/1 Running 0 14m [root@master01 ~]# kubectl delete pod nginx-dep-8967df55d-j8zp7 pod "nginx-dep-8967df55d-j8zp7" deleted [root@master01 ~]# kubectl get pod NAME READY STATUS RESTARTS AGE nginx-dep-8967df55d-8fl27 1/1 Running 0 50s ngx-dep-5c8d96d457-62qd6 1/1 Running 0 15m [root@master01 ~]#
提示:可以看到我们删除pod以后,再次查看,pod又重新创建起来了;其原因是我们使用pod控制器创建的pod它有自愈功能;我们知道在k8s上控制器的 作用就是负责创建和监控对应资源状态是否符合我们定义的状态,如果不符合它就会试着重启或重建的方式让其对应资源和我们定义的资源状态保持一致;上述命令我们删除了pod,但对应控制器发现对应pod被删除了,它就会试着重新新建一个pod,让其始终保持和我们期望的状态保持一致;
查看deploy控制器
[root@master01 ~]# kubectl get deploy NAME READY UP-TO-DATE AVAILABLE AGE nginx-dep 1/1 1 1 94m ngx-dep 1/1 1 1 23m [root@master01 ~]# kubectl get deploy -o wide NAME READY UP-TO-DATE AVAILABLE AGE CONTAINERS IMAGES SELECTOR nginx-dep 1/1 1 1 94m nginx nginx:1.14-alpine app=nginx-dep ngx-dep 1/1 1 1 23m nginx nginx:1.14-alpine app=ngx-dep [root@master01 ~]#
删除控制器
[root@master01 ~]# kubectl get deploy -o wide NAME READY UP-TO-DATE AVAILABLE AGE CONTAINERS IMAGES SELECTOR nginx-dep 1/1 1 1 95m nginx nginx:1.14-alpine app=nginx-dep ngx-dep 1/1 1 1 24m nginx nginx:1.14-alpine app=ngx-dep [root@master01 ~]# kubectl delete deploy nginx-dep deployment.apps "nginx-dep" deleted [root@master01 ~]# kubectl get deploy -o wide NAME READY UP-TO-DATE AVAILABLE AGE CONTAINERS IMAGES SELECTOR ngx-dep 1/1 1 1 24m nginx nginx:1.14-alpine app=ngx-dep [root@master01 ~]# kubectl get pod NAME READY STATUS RESTARTS AGE ngx-dep-5c8d96d457-62qd6 1/1 Running 0 24m [root@master01 ~]#
提示:删除控制器它会连同控制器所创建的资源一并删除;
创建service
在k8s中,service资源是用来访问pod资源而存在的;我们知道删除一个pod资源后,由于控制的原因,它会重新创建一个pod,那么新建的pod怎么让外部访问到呢?如果直接访问podip,那么每次访问我们都需要查看对应的podip才会访问到对应的pod,很显然这种不是我们想要的方式;对于service资源来说,它可以帮助我们自动的关联对应的pod,从而实现我们只需要访问对应service就可以访问到pod;通常service的ip地址不会怎么改变,或者变更没有pod变更的快,service的作用就是帮助我们关联对应名称的pod,从而实现我们访问serviceip就可以反代到对应的pod上;对于创建service来说,它有几种类型;第一种clusterip,这种service能够实现访问service的ip地址+pod监听端口就能访问到对应pod,可以在k8s集群任意节点访问serviceip+podport从而访问到对应pod;第二种是nodeport类型,这种service可以实现把外部任何主机访问节点k8s任何一个节点的ip地址+一个固定端口就能访问到pod;
示例:创建clusterip类型的service,并关联ngx-dep控制器
[root@master01 ~]# kubectl create service clusterip ngx-dep --tcp=80 service/ngx-dep created [root@master01 ~]#
提示:关联pod只需要将service的名称和对应控制器的名称写成一样即可;
查看ngx-dep service详细信息
[root@master01 ~]# kubectl describe svc/ngx-dep Name: ngx-dep Namespace: default Labels: app=ngx-dep Annotations: <none> Selector: app=ngx-dep Type: ClusterIP IP Families: <none> IP: 10.101.104.228 IPs: 10.101.104.228 Port: 80 80/TCP TargetPort: 80/TCP Endpoints: 10.244.1.2:80 Session Affinity: None Events: <none> [root@master01 ~]#
提示:可以看到ngx-dep service的ip地址为10.101.104.228;对应关联的后端pod的地址为10.244.1.2:80
访问servcieip看看是否能够访问到对应pod?
[root@master01 ~]# curl 10.101.104.228 <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br/> Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p> </body> </html> [root@master01 ~]#
在node01上访问serviceip看看是否能够访问到对应pod呢?
[root@node01 ~]# curl 10.101.104.228 <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br/> Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p> </body> </html> [root@node01 ~]#
提示:这个service地址只能在k8s集群节点上访问,外部其他主机不能够正常访问到;
测试:删除pod,看看对应service中endpoint关联的地址是否会变成对应pod的地址呢?
[root@master01 ~]# kubectl get pod -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES ngx-dep-5c8d96d457-62qd6 1/1 Running 0 57m 10.244.1.2 node01.k8s.org <none> <none> [root@master01 ~]# kubectl delete pod ngx-dep-5c8d96d457-62qd6 pod "ngx-dep-5c8d96d457-62qd6" deleted [root@master01 ~]# kubectl get pod -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES ngx-dep-5c8d96d457-w6nss 1/1 Running 0 19s 10.244.2.3 node02.k8s.org <none> <none> [root@master01 ~]# kubectl describe svc/ngx-dep Name: ngx-dep Namespace: default Labels: app=ngx-dep Annotations: <none> Selector: app=ngx-dep Type: ClusterIP IP Families: <none> IP: 10.101.104.228 IPs: 10.101.104.228 Port: 80 80/TCP TargetPort: 80/TCP Endpoints: 10.244.2.3:80 Session Affinity: None Events: <none> [root@master01 ~]#
提示:可以看到删除了pod以后,新建的pod地址变为了10.244.2.3,对应service中endpoint关联的地址也变为了对应pod的ip地址;
访问service看看是否能够访问到pod呢?
[root@master01 ~]# kubectl describe svc/ngx-dep Name: ngx-dep Namespace: default Labels: app=ngx-dep Annotations: <none> Selector: app=ngx-dep Type: ClusterIP IP Families: <none> IP: 10.101.104.228 IPs: 10.101.104.228 Port: 80 80/TCP TargetPort: 80/TCP Endpoints: 10.244.2.3:80 Session Affinity: None Events: <none> [root@master01 ~]# [root@master01 ~]# curl 10.101.104.228 <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br/> Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p> </body> </html> [root@master01 ~]#
提示:之所以我们在k8s节点上访问serviceip能够访问到对应pod,原因是我们在创建service时,其实就是在k8s所有节点上生成iptables规则或ipvs规则;
删除service
[root@master01 ~]# kubectl delete svc/ngx-dep service "ngx-dep" deleted [root@master01 ~]# kubectl get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 3h24m [root@master01 ~]#
创建nodeport类型的service
[root@master01 ~]# kubectl create svc nodeport ngx-dep --tcp=80 service/ngx-dep created [root@master01 ~]# kubectl get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 3h24m ngx-dep NodePort 10.107.14.221 <none> 80:30492/TCP 11s [root@master01 ~]# kubectl describe svc/ngx-dep Name: ngx-dep Namespace: default Labels: app=ngx-dep Annotations: <none> Selector: app=ngx-dep Type: NodePort IP Families: <none> IP: 10.107.14.221 IPs: 10.107.14.221 Port: 80 80/TCP TargetPort: 80/TCP NodePort: 80 30492/TCP Endpoints: 10.244.2.3:80 Session Affinity: None External Traffic Policy: Cluster Events: <none> [root@master01 ~]#
提示:可以看到现在创建nodeport类型的service后,对应port不再是80:80而变成了80:30492,后面的30492这个端口不是pod端口,它是k8s集群节点所监听的一个固定端口;现在我们直接访问k8s集群任意一个节点的30492端口,就能访问到对应的pod;
[root@docker_registry ~]# curl 192.168.0.41:30492 <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br/> Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p> </body> </html> [root@docker_registry ~]# curl 192.168.0.44:30492 <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br/> Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p> </body> </html> [root@docker_registry ~]#
提示:可以看到我们用其他主机访问对应k8s任意节点的30492端口都能访问到对应的pod;
使用名称访问service
我知道当k8s中的pod删除以后,重新被创建以后可以使用访问serviceip地址来实现访问对应pod,那么问题来了,假如service被删除又重建以后,我们怎么来访问对应pod呢?使用serviceip我们要先查看serviceip地址,很显然这个问题又回到了pod删除怎么访问对应pod;在k8s上除了运行的有几个核心的pod以外,还有一个dns,名叫kube-dns,这个pod主要用来解析对应的名称到对应服务ip,它可以实现服务的动态注册;所谓服务动态注册是指在对应的服务发生以后,它能够及时的将变化结果反映到对应的解析记录上,使得我们访问对应服务不被服务变得而受影响;
查看kube-dns的地址
[root@master01 ~]# kubectl get svc -n kube-system NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kube-dns ClusterIP 10.96.0.10 <none> 53/UDP,53/TCP,9153/TCP 3h45m [root@master01 ~]#
修改maser端节点dns服务器为kube-dns的地址
[root@master01 ~]# cat /etc/resolv.conf # Generated by NetworkManager search k8s.org nameserver 10.96.0.10 [root@master01 ~]#
访问服务名称看看是否能够访问到对应服务呢?
[root@master01 ~]# curl ngx-dep curl: (6) Could not resolve host: ngx-dep; Unknown error [root@master01 ~]#
提示:这里显示不能解析ngx-dep,原因是本机的搜索域为k8s.org;我们在初始化master时没有指定--service-dns-domain的值为k8s.org,所以默认搜索域为cluster.local;所以我们访问时需要指定绝对名称
使用完全绝对名称访问服务
[root@master01 ~]# curl ngx-dep.default.svc.cluster.local. <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br/> Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p> </body> </html> [root@master01 ~]#
提示:有了这个绝对的名称以后,我们在删除有重建service就可以直接使用名称访问服务即可;
验证:删除ngx-dep服务,再重新建ngx-dep服务,看看使用名称能够访问到对应的服务?
[root@master01 ~]# kubectl get svc/ngx-dep NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE ngx-dep NodePort 10.107.14.221 <none> 80:30492/TCP 33m [root@master01 ~]# kubectl delete svc/ngx-dep service "ngx-dep" deleted [root@master01 ~]# kubectl create svc clusterip ngx-dep --tcp=80:80 service/ngx-dep created [root@master01 ~]# kubectl get svc/ngx-dep NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE ngx-dep ClusterIP 10.106.196.39 <none> 80/TCP 6s [root@master01 ~]# curl ngx-dep.default.svc.cluster.local <!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>Welcome to nginx!</h1> <p>If you see this page, the nginx web server is successfully installed and working. Further configuration is required.</p> <p>For online documentation and support please refer to <a href="http://nginx.org/">nginx.org</a>.<br/> Commercial support is available at <a href="http://nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p> </body> </html> [root@master01 ~]#
提示:可以看到新建的ngx-dep和以前的服务ip地址不一样,但我们可以通过访问同一名称访问到对应的pod;
pod动态扩展
新建pod控制器
[root@master01 ~]# kubectl create deploy myapp-dep --image=ikubernetes/myapp:v1 deployment.apps/myapp-dep created [root@master01 ~]# kubectl get pod NAME READY STATUS RESTARTS AGE myapp-dep-5bc4d8cc74-zcrwz 1/1 Running 0 10s ngx-dep-5c8d96d457-w6nss 1/1 Running 0 60m [root@master01 ~]#
新建myapp-dep服务
[root@master01 ~]# kubectl create svc clusterip myapp-dep --tcp=80:80 service/myapp-dep created [root@master01 ~]# kubectl get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 4h3m myapp-dep ClusterIP 10.96.196.189 <none> 80/TCP 7s ngx-dep ClusterIP 10.106.196.39 <none> 80/TCP 5m16s [root@master01 ~]# kubectl describe svc/myapp-dep Name: myapp-dep Namespace: default Labels: app=myapp-dep Annotations: <none> Selector: app=myapp-dep Type: ClusterIP IP Families: <none> IP: 10.96.196.189 IPs: 10.96.196.189 Port: 80-80 80/TCP TargetPort: 80/TCP Endpoints: 10.244.1.3:80 Session Affinity: None Events: <none> [root@master01 ~]#
扩展pod
[root@master01 ~]# kubectl get deploy NAME READY UP-TO-DATE AVAILABLE AGE myapp-dep 1/1 1 1 4m16s ngx-dep 1/1 1 1 122m [root@master01 ~]# kubectl scale --replicas=5 deploy/myapp-dep deployment.apps/myapp-dep scaled [root@master01 ~]# kubectl get pod NAME READY STATUS RESTARTS AGE myapp-dep-5bc4d8cc74-fpfvj 1/1 Running 0 7s myapp-dep-5bc4d8cc74-gqhh5 0/1 ContainerCreating 0 7s myapp-dep-5bc4d8cc74-j827z 0/1 ContainerCreating 0 7s myapp-dep-5bc4d8cc74-s5ftj 0/1 ContainerCreating 0 7s myapp-dep-5bc4d8cc74-zcrwz 1/1 Running 0 5m17s ngx-dep-5c8d96d457-w6nss 1/1 Running 0 65m [root@master01 ~]#
提示:可以看到现在myapp-dep运行的pod变成了5个;
缩减pod
[root@master01 ~]# kubectl scale --replicas=3 deploy/myapp-dep deployment.apps/myapp-dep scaled [root@master01 ~]# kubectl get pod -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES myapp-dep-5bc4d8cc74-cvkbc 1/1 Running 0 76s 10.244.1.5 node01.k8s.org <none> <none> myapp-dep-5bc4d8cc74-gmt7w 1/1 Running 0 76s 10.244.3.5 node03.k8s.org <none> <none> myapp-dep-5bc4d8cc74-gqhh5 1/1 Running 0 6m54s 10.244.2.4 node02.k8s.org <none> <none> ngx-dep-5c8d96d457-w6nss 1/1 Running 0 72m 10.244.2.3 node02.k8s.org <none> <none> [root@master01 ~]#
提示:动态扩缩减pod数量只需要把对应的replicas数量进行修改即可;默认不指定就是为1;
现在再次查看service对应的endpoint地址是否是上述三个地址呢?
[root@master01 ~]# kubectl describe svc/myapp-dep Name: myapp-dep Namespace: default Labels: app=myapp-dep Annotations: <none> Selector: app=myapp-dep Type: ClusterIP IP Families: <none> IP: 10.96.196.189 IPs: 10.96.196.189 Port: 80-80 80/TCP TargetPort: 80/TCP Endpoints: 10.244.1.5:80,10.244.2.4:80,10.244.3.5:80 Session Affinity: None Events: <none> [root@master01 ~]#
提示:可以看到对应service后端endpoint地址已经关联到以上3个pod地址;这也意味着我们访问service,它会把我们的请求调度到对应的pod上进行响应,具体会这么调度呢?
访问myapp-dep服务
[root@master01 ~]# curl myapp-dep.default.svc.cluster.local/hostname.html myapp-dep-5bc4d8cc74-gmt7w [root@master01 ~]# curl myapp-dep.default.svc.cluster.local/hostname.html myapp-dep-5bc4d8cc74-gmt7w [root@master01 ~]# curl myapp-dep.default.svc.cluster.local/hostname.html myapp-dep-5bc4d8cc74-gqhh5 [root@master01 ~]# curl myapp-dep.default.svc.cluster.local/hostname.html myapp-dep-5bc4d8cc74-cvkbc [root@master01 ~]# curl myapp-dep.default.svc.cluster.local/hostname.html myapp-dep-5bc4d8cc74-gmt7w [root@master01 ~]# curl myapp-dep.default.svc.cluster.local/hostname.html myapp-dep-5bc4d8cc74-gmt7w [root@master01 ~]# curl myapp-dep.default.svc.cluster.local/hostname.html myapp-dep-5bc4d8cc74-cvkbc [root@master01 ~]# curl myapp-dep.default.svc.cluster.local/hostname.html myapp-dep-5bc4d8cc74-gqhh5 [root@master01 ~]# curl myapp-dep.default.svc.cluster.local/hostname.html myapp-dep-5bc4d8cc74-gqhh5 [root@master01 ~]#
提示:的确service能够调度请求,从上面访问结果看,service调度是随机调度,没有什么规律;
以上就是k8s集群环境中使用kubectl命令行工具来操作k8s上的名称空间,控制器,服务相关演示和说明;从上面的演示可以知道,在k8s上所有的操作都在master端进行,因为master端有证书,默认情况k8s的aipserver会双向认证,所谓双向认证是指,不仅客户端要验证服务端证书,同时服务端也要验证客户端证书;在k8s上的所有操作都要先和apiserver打交道;其次创建pod控制器,只要控制器不被删除,里面定义的pod它就会一直处于我们期望的数量和状态存在,即便我们手动删除pod它也会自动重建;对于service来说,在k8s上创建service,从本质上讲就是创建iptables或ipvs规则;不同类型的service访问途径略有不同,clusterip类型的service只能在k8s节点上实现访问,nodeport类型的service可以实现从外部主机访问k8s节点ip+对应创建service自动生成的固定端口就可以访问到对应服务;除此之外,在k8s上我们可以通过kubectl scale来对pod控制器做动态扩缩减pod数量;如果一个service后端对应多个pod时,service还能起到调度的作用;