Docker 与 K8S学习笔记(十六)—— kubectl命令行工具使用

kubectl作为客户端命令行工具,可以让用户通过命令行方式对kubernetes集群进行操作,这一篇将对其使用进行说明。

一、语法结构

kubectl [command] [TYPE] [NAME] [flags]

command:指对一种资源索要执行的操作,如create、get、describe、delete。

TYPE:资源类型,资源类型不区分大小写, 可以指定单数、复数或缩写形式如:pod、deployment、service。下表是目前支持的资源类型(通过kubectl api-resources即可获取):

$ sudo kubectl api-resources
NAME                              SHORTNAMES   APIVERSION                             NAMESPACED   KIND
bindings                                       v1                                     true         Binding
componentstatuses                 cs           v1                                     false        ComponentStatus
configmaps                        cm           v1                                     true         ConfigMap
endpoints                         ep           v1                                     true         Endpoints
events                            ev           v1                                     true         Event
limitranges                       limits       v1                                     true         LimitRange
namespaces                        ns           v1                                     false        Namespace
nodes                             no           v1                                     false        Node
persistentvolumeclaims            pvc          v1                                     true         PersistentVolumeClaim
persistentvolumes                 pv           v1                                     false        PersistentVolume
pods                              po           v1                                     true         Pod
podtemplates                                   v1                                     true         PodTemplate
replicationcontrollers            rc           v1                                     true         ReplicationController
resourcequotas                    quota        v1                                     true         ResourceQuota
secrets                                        v1                                     true         Secret
serviceaccounts                   sa           v1                                     true         ServiceAccount
services                          svc          v1                                     true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io/v1        false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io/v1        false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io/v1                false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io/v1              false        APIService
controllerrevisions                            apps/v1                                true         ControllerRevision
daemonsets                        ds           apps/v1                                true         DaemonSet
deployments                       deploy       apps/v1                                true         Deployment
replicasets                       rs           apps/v1                                true         ReplicaSet
statefulsets                      sts          apps/v1                                true         StatefulSet
tokenreviews                                   authentication.k8s.io/v1               false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io/v1                true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io/v1                false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io/v1                false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io/v1                false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling/v1                         true         HorizontalPodAutoscaler
cronjobs                          cj           batch/v1beta1                          true         CronJob
jobs                                           batch/v1                               true         Job
certificatesigningrequests        csr          certificates.k8s.io/v1                 false        CertificateSigningRequest
leases                                         coordination.k8s.io/v1                 true         Lease
endpointslices                                 discovery.k8s.io/v1beta1               true         EndpointSlice
events                            ev           events.k8s.io/v1                       true         Event
ingresses                         ing          extensions/v1beta1                     true         Ingress
flowschemas                                    flowcontrol.apiserver.k8s.io/v1beta1   false        FlowSchema
prioritylevelconfigurations                    flowcontrol.apiserver.k8s.io/v1beta1   false        PriorityLevelConfiguration
ingressclasses                                 networking.k8s.io/v1                   false        IngressClass
ingresses                         ing          networking.k8s.io/v1                   true         Ingress
networkpolicies                   netpol       networking.k8s.io/v1                   true         NetworkPolicy
runtimeclasses                                 node.k8s.io/v1                         false        RuntimeClass
poddisruptionbudgets              pdb          policy/v1beta1                         true         PodDisruptionBudget
podsecuritypolicies               psp          policy/v1beta1                         false        PodSecurityPolicy
clusterrolebindings                            rbac.authorization.k8s.io/v1           false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io/v1           false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io/v1           true         RoleBinding
roles                                          rbac.authorization.k8s.io/v1           true         Role
priorityclasses                   pc           scheduling.k8s.io/v1                   false        PriorityClass
csidrivers                                     storage.k8s.io/v1                      false        CSIDriver
csinodes                                       storage.k8s.io/v1                      false        CSINode
storageclasses                    sc           storage.k8s.io/v1                      false        StorageClass
volumeattachments                              storage.k8s.io/v1                      false        VolumeAttachment

NAME:资源名称,区分大小写如果省略名称,则显示所有资源的详细信息,这里支持两种资源指定方式:

  • 按类型和名称指定资源,例如:kubectl get pod nginx

  • 使用文件指定资源,例如:kubectl get -f ./nginx_pod.yaml

flags:指定可选的参数。例如,可以使用 -s 或 -server 参数指定 Kubernetes API 服务器的地址和端口。

二、操作示例

1、创建资源对象

我们根据yaml配置文件创建Nginx的Deployment,yaml文件内容下:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80

创建资源:

$ sudo kubectl create -f nginx_deployment.yaml
deployment.apps/nginx-deployment created

2、查看资源对象:

$ sudo kubectl get pods
NAME                               READY   STATUS    RESTARTS   AGE
nginx-deployment-585449566-28gxs   1/1     Running   0          31s
nginx-deployment-585449566-f7vnt   1/1     Running   0          31s
nginx-deployment-585449566-jpc2z   1/1     Running   0          31s
$ sudo kubectl get deployments
NAME               READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   3/3     3            3           66s

3、查看资源对象描述信息

$ sudo kubectl describe pod nginx-deployment-585449566-28gxs
Name:         nginx-deployment-585449566-28gxs
Namespace:    default
Priority:     0
Node:         ayato/172.16.194.135
Start Time:   Thu, 23 Dec 2021 02:12:57 +0000
Labels:       app=nginx
              pod-template-hash=585449566
Annotations:  <none>
Status:       Running
IP:           172.17.0.7
IPs:
  IP:           172.17.0.7
Controlled By:  ReplicaSet/nginx-deployment-585449566
Containers:
  nginx:
    Container ID:   docker://49099a8d907ff1c28f557de3c3ee84d90113c33578caddfd70d3bd0e72da67d5
    Image:          nginx:latest
    Image ID:       docker-pullable://nginx@sha256:366e9f1ddebdb844044c2fafd13b75271a9f620819370f8971220c2b330a9254
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Thu, 23 Dec 2021 02:13:15 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-pcr2h (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  default-token-pcr2h:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-pcr2h
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  98s   default-scheduler  Successfully assigned default/nginx-deployment-585449566-28gxs to ayato
  Normal  Pulling    97s   kubelet            Pulling image "nginx:latest"
  Normal  Pulled     82s   kubelet            Successfully pulled image "nginx:latest" in 15.804248355s
  Normal  Created    81s   kubelet            Created container nginx
  Normal  Started    81s   kubelet            Started container nginx

4、查看容器内日志

$ sudo kubectl logs nginx-deployment-585449566-28gxs
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2021/12/23 02:13:15 [notice] 1#1: using the "epoll" event method
2021/12/23 02:13:15 [notice] 1#1: nginx/1.21.4
2021/12/23 02:13:15 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
2021/12/23 02:13:15 [notice] 1#1: OS: Linux 4.15.0-163-generic
2021/12/23 02:13:15 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/12/23 02:13:15 [notice] 1#1: start worker processes
2021/12/23 02:13:15 [notice] 1#1: start worker process 31
2021/12/23 02:13:15 [notice] 1#1: start worker process 32

这里也可以加上-f参数即:sudo kubectl logs -f nginx-deployment-585449566-28gxs,其效果和tail -f一样能够持续跟踪查看日志。

5、登陆到指定pod的容器中,需要指定pod和容器名,容器名在刚才的yaml中有定义,也可以通过describe命令查看

$ sudo kubectl exec -it nginx-deployment-585449566-28gxs -c nginx /bin/bash
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
root@nginx-deployment-585449566-28gxs:/#

 

PS:在进行操作时,大家可能会遇到集群拉取镜像失败问题导致pod起不来,这个需要在启动minikube时指定国内的镜像仓库:

minikube start --vm-driver=none --registry-mirror=https://registry.docker-cn.com

 

posted @ 2022-01-21 20:34  阿拉懒神灯  阅读(432)  评论(0编辑  收藏  举报