容器编排系统k8s之Kubectl工具的基础使用

  前文我们了解了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,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 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,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,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,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,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,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,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,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还能起到调度的作用;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


文章浏览阅读942次。kube-controller-manager 和 kubelet 是异步工作的,这意味着延迟可能包括任何的网络延迟、apiserver 的延迟、etcd 延迟,一个节点上的负载引起的延迟等等。当 Kubernetes 中 Node 节点出现状态异常的情况下,节点上的 Pod 会被重新调度到其他节点上去,但是有的时候我们会发现节点 Down 掉以后,Pod 并不会立即触发重新调度,这实际上就是和 Kubelet 的状态更新机制密切相关的,Kubernetes 提供了一些参数配置来触发重新调度的时间。_node-monitor-period
文章浏览阅读3.8k次。上篇文章详细介绍了弹性云混部的落地历程,弹性云是滴滴内部提供给网约车等核心服务的容器平台,其基于 k8s 实现了对海量 node 的管理和 pod 的调度。本文重点介绍弹性云的调度能力,分为以下部分:调度链路图:介绍当前弹性云调度体系链路,对架构体系有一个初步的认知k8s 调度能力的运用:整体介绍弹性云现在用到的 k8s 调度能力和对其的增强k8s 版本的升级:介绍到从 k8s 1.12 到 1...._滴滴机房 腾讯
文章浏览阅读897次。对于cpu来说,这种分配方式并不会有太大问题,因为cpu可以灵活调度,numa调度时我们只计算绑定了numa cpu的pod是可以接受的,但是对于内存来说,numa node上申请了的内存无法做到随时迁移,这就会导致调度器视角numa node的mem资源足够,但是等到pod真正使用时,由于没有绑定numa node的pod申请的内存,导致numa node的mem资源不足,造成swap中断或者远端内存申请,这会对绑定mem的pod来带来性能损耗。忽略了没有绑定numa node的pod资源。_kubectl numa
文章浏览阅读796次,点赞17次,收藏15次。只要在Service定义中设置了ClusterIp:None,就定义了一个HeadLess Service, 它与普通的Service关键区别在于它没有ClusterIp地址,如果解析HeadLess Service的DNS域名,则会返回该Service对应的全部Pod的EndPoint列表,这就意味着客户端是直接与后端的pod建立了TCP/IP链接进行通信的。一个Label是一个键值对。注解:属于资源对象的元数据,可以被理解为一种特殊的标签,不过更多的是与程序挂钩,通常用于实现资源对象属性的自定义扩展。
文章浏览阅读763次。但是此时如果配置成 NONE, 租户创建成功了,但是无法创建资源文件,也就是无法上传文件,可能 dolphinscheduler 团队就想着将文件上传到 hdfs,暂不支持本地。需要将 resource.storage.type 置为 NONE, 因为我之前用的 1.3.6 版本的时候,即使资源文件存在本地文件也需要配置成 hdfs。_[error] 2023-10-24 18:10:43.762 +0800 org.apache.dolphinscheduler.api.servic
文章浏览阅读2.7k次,点赞2次,收藏13次。公司使用的是交老的k8s版本(1.16),由于老版本的K8s对于现在很多新特性不支持,所以需要升级到新版本。目前2023年7月11日最新版本的k8s是v1.27.3。通过参考官方文档进行k8s部署工作。其中涉及到操作系统配置、防火墙配置、私有镜像仓库等。_k8s最新版本
文章浏览阅读1.8w次,点赞14次,收藏27次。能节省你在kubeadm init 时遇到问题的排错时间⌚️。整合了网上大佬
文章浏览阅读1.1k次,点赞2次,收藏7次。具体操作步骤可以参考之前的教程,建议是先安装一台,然后克隆虚拟机,这样速度快。注意:在克隆时记得修改Mac地址、IP地址、UUID和主机名。(最后别忘了保存下快照~)_部署k8s集群
文章浏览阅读863次,点赞23次,收藏16次。当部署完 Kubernetes,便拥有了一个完整的集群。一组工作机器,称为节点, 会运行容器化应用程序。每个集群至少有一个工作节点。工作节点会 托管Pod ,而 Pod 就是作为应用负载的组件。控制平面管理集群中的工作节点和Pod。说人话版本:集群:cluster,多个几点被组织到一起共同为系统提供服务过程称之为集群。本质上是将承载同一个软件服务节点组织到一起,称之为该软件(服务)的集群,当然集群中的节点身份地位是不一样的。k8s集群也是如此,他也是多个节点组成。
文章浏览阅读943次。Rancher是一个开源的企业级多集群Kubernetes管理平台,实现了Kubernetes集群在混合云+本地数据中心的集中部署与管理,以确保集群的安全性,加速企业数字化转型。Rancher 1.0版本在2016年就已发布,时至今日,Rancher已经成长为企业在生产环境中运行容器和Kubernetes的首要选择。_rancher管理k8s
文章浏览阅读742次,点赞2次,收藏3次。本篇来讲解如何在centos下安装部署高可用k8s集群。_kubeadm ha keepalived + nginx
文章浏览阅读1.9k次,点赞21次,收藏25次。那么这个空间设置成内存的2倍大小。点击IPv4设置--手动--添加--设置ip--设置DNS服务器,最后点击--“保存”;首先选中--“本地标准磁盘”,存储配置--自定义分区,点击--“完成”;在--主机名--设置主机名:(例如k8s-master01),点击--点击+,设置--挂载点/boot--期望容量,点击--添加挂载点;点击--+--挂载点swap--期望容量,点击--“添加挂载点”;默认选择--亚洲--上海,并调整日期和时间,点击--“完成”;设备类型--确认--LVM,卷组--选择“修改”;_euler 服务器搭建
文章浏览阅读1k次。在1.25版本的k8s集群中部署gpu-manage时,虽然显示gpu节点上gpu-manage的pod实例都是running状态,但是给pod申领。既可以用源码的Makefile自动编译打包成新的镜像,但是源码的。说明gpu-manager和容器运行时接口通信失败了。编译后的镜像在1.25版本的k8s中可以正常使用。,但是在k8s1.23版本之后,接口路径已经改为。资源时,却始终找不到有资源的节点。,另外有一些依赖需要国际上的支持。可以看到这里用的运行时接口是。查看节点的详情时,返回的。_launch gpu manager 报错 can't create container runtime manager: context dead
文章浏览阅读1k次,点赞18次,收藏16次。SelfLink:API的资源对象之一,表示资源对象在集群当中自身的一个连结,self-Link是一个唯一的标识号,可以用于标识k8s集群当中的每个资源的对象。容器里使用的配置,在provisioner当中定义好环境变量,传给容器,storageclass的名称,NFS服务器的地址,NFS的目录。NFS的provisionner的客户端以pod的方式运行在集群当中,监听k8s集群当中PV的请求,然后动态的创建于NFS相关的PV。命名为 nfs-client-provisioner-clusterrole。
文章浏览阅读6.3k次,点赞2次,收藏20次。k8s证书过期解决方案之替换证书_k8s证书过期如何更换
文章浏览阅读1k次。KMS,Key Management Service,即密钥管理服务,在K8S集群中,以驱动和插件的形式启用对Secret,Configmap进行加密。以保护敏感数据
文章浏览阅读888次。exporter对于云服务的监控还是很不完美,毕竟每家都有自己的护城河。自动发现多实例这样的借助consul 阿波罗这样的会简单一些。aws可以借助cloudwatch这样的导入模板到grafana中。还是希望能将类似腾讯云云监控中的这些指标采集到prometheus中,但是这过程应该还很遥远grafana出图 prometheus查询语法这些东西有时间的好好研究一下。报警有必要进行分级别,收敛配置一下!_command: - "-redis.password-file=/redis_passwd.json
文章浏览阅读1k次。可以在此处(https://cloud.google.com/kubernetes-engine/docs/how-to/kube-dns)和此处(https://www.digitalocean.com/community/tutorials/an-introduction-to-the-kubernetes-dns-service)找到更多的详细信息。-or-ipvs/)和此处(https://arthurchiao.art/blog/cracking-k8s-node-proxy/)。_k8s默认命名空间
文章浏览阅读4.9k次,点赞11次,收藏32次。如果运行runc命令时提示:runc: error while loading shared libraries: libseccomp.so.2: cannot open shared object file: No such file or directory,则表明runc没有找到libseccomp,需要检查libseccomp是否安装,本次安装默认就可以查询到。所有主机均需要操作。所有主机均需要操作。所有主机均需要操作。所有主机均需要操作。所有主机均需要操作。所有主机均需要操作。_kubernetes 1.28
文章浏览阅读3.6w次,点赞118次,收藏144次。Canal 提供了网络功能,使得 Kubernetes 集群中的 Pod 可以相互通信,并与集群外部的服务进行通信。它通过网络插件的方式,为每个 Pod 分配唯一的 IP 地址,并管理网络流量的路由和转发。此外,Canal 还支持网络策略,用于定义 Pod 之间的通信规则和安全策略。Canal 基于 Calico 和 Flannel 项目,结合了二者的优点。它使用 Calico 的数据平面,提供高性能的网络转发和安全特性,同时使用 Flannel 的控制平面,实现 IP 地址管理和网络策略的配置。_k8s canal