kubectl命令非常多。如果死记硬背是很难记得住的

我们需要多看帮助文档 --help以及找规律

显示k8s版本信息

kubectl version

显示集群信息

[root@master ~]# kubectl  cluster-info
Kubernetes control plane is running at https://10.0.4.9:6443
CoreDNS is running at https://10.0.4.9:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.

查看cpu

需要安装 metrics-server 我们没有安装就不展示了

kubectl top node
kubectl top pod

查看资源对象

k8s中以资源对象来描述组件,比如 node pod service等都叫做资源对象

通过api-resources可以列出所有的资源对象以及别名

使用 KuboardSpray 图形化安装kubernetes集群详情 kubectl cluster-info_命名空间

经常用到的别名

componentstatuses 		cs  	组件状态
namespaces 				ns  	命名空间
deployments 			deploy	deploy
services				svc		svc
ingresses				ing
cronjobs				cj
events					ev
replicationcontrollers 	rc

通过get命令可以查看这些资源信息

查看node状态

[root@node01 ~]# kubectl get node
NAME     STATUS   ROLES                  AGE   VERSION
master   Ready    control-plane,master   25h   v1.23.9
node01   Ready    <none>                 23h   v1.23.9
node02   Ready    <none>                 23h   v1.23.9

查看组件状态

[root@node01 ~]# kubectl get cs
Warning: v1 ComponentStatus is deprecated in v1.19+
NAME                 STATUS    MESSAGE                         ERROR
scheduler            Healthy   ok                              
controller-manager   Healthy   ok                              
etcd-0               Healthy   {"health":"true","reason":""}

查看apiservice注册信息

[root@node01 ~]# kubectl get apiservice
NAME                                   SERVICE   AVAILABLE   AGE
v1.                                    Local     True        25h
v1.admissionregistration.k8s.io        Local     True        25h
v1.apiextensions.k8s.io                Local     True        25h
v1.apps                                Local     True        25h
v1.authentication.k8s.io               Local     True        25h
v1.authorization.k8s.io                Local     True        25h
v1.autoscaling                         Local     True        25h
v1.batch                               Local     True        25h
v1.certificates.k8s.io                 Local     True        25h
v1.coordination.k8s.io                 Local     True        25h
v1.discovery.k8s.io                    Local     True        25h
v1.events.k8s.io                       Local     True        25h
v1.networking.k8s.io                   Local     True        25h
v1.node.k8s.io                         Local     True        25h
v1.policy                              Local     True        25h
v1.rbac.authorization.k8s.io           Local     True        25h
v1.scheduling.k8s.io                   Local     True        25h
v1.storage.k8s.io                      Local     True        25h
v1beta1.batch                          Local     True        25h
v1beta1.discovery.k8s.io               Local     True        25h
v1beta1.events.k8s.io                  Local     True        25h
v1beta1.flowcontrol.apiserver.k8s.io   Local     True        25h
v1beta1.node.k8s.io                    Local     True        25h
v1beta1.policy                         Local     True        25h
v1beta1.storage.k8s.io                 Local     True        25h
v1beta2.flowcontrol.apiserver.k8s.io   Local     True        25h
v2.autoscaling                         Local     True        25h
v2beta1.autoscaling                    Local     True        25h
v2beta2.autoscaling                    Local     True        25h

查看api的版本

[root@node01 ~]# kubectl api-versions
admissionregistration.k8s.io/v1
apiextensions.k8s.io/v1
apiregistration.k8s.io/v1
apps/v1
authentication.k8s.io/v1
authorization.k8s.io/v1
autoscaling/v1
autoscaling/v2
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1
coordination.k8s.io/v1
discovery.k8s.io/v1
discovery.k8s.io/v1beta1
events.k8s.io/v1
events.k8s.io/v1beta1
flowcontrol.apiserver.k8s.io/v1beta1
flowcontrol.apiserver.k8s.io/v1beta2
networking.k8s.io/v1
node.k8s.io/v1
node.k8s.io/v1beta1
policy/v1
policy/v1beta1
rbac.authorization.k8s.io/v1
scheduling.k8s.io/v1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1

查看所有的命名空间

不指定命名空间默认都会在 default

kube-public 中的资源可以被所有人访问

[root@node01 ~]# kubectl get ns
NAME                   STATUS   AGE
default                Active   25h
kube-flannel           Active   25h
kube-node-lease        Active   25h
kube-public            Active   25h
kube-system            Active   25h
kubernetes-dashboard   Active   23h

查看指定的命名空间

-o 可以指定输出的格式

wide 会显示更多的信息

json 显示成json格式

yaml yaml格式

命名空间的 kind 为 Namespace

[root@node01 ~]# kubectl get ns kube-flannel -o json
{
    "apiVersion": "v1",
    "kind": "Namespace",
    "metadata": {
        "annotations": {
            "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Namespace\",\"metadata\":{\"annotations\":{},\"labels\":{\"pod-security.kubernetes.io/enforce\":\"privileged\"},\"name\":\"kube-flannel\"}}\n"
        },
        "creationTimestamp": "2022-10-31T17:41:14Z",
        "labels": {
            "kubernetes.io/metadata.name": "kube-flannel",
            "pod-security.kubernetes.io/enforce": "privileged"
        },
        "name": "kube-flannel",
        "resourceVersion": "4021",
        "uid": "744fece7-1e97-45af-a59d-84ec3830337e"
    },
    "spec": {
        "finalizers": [
            "kubernetes"
        ]
    },
    "status": {
        "phase": "Active"
    }
}
[root@node01 ~]# kubectl get ns kube-flannel -o yaml
apiVersion: v1
kind: Namespace
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"Namespace","metadata":{"annotations":{},"labels":{"pod-security.kubernetes.io/enforce":"privileged"},"name":"kube-flannel"}}
  creationTimestamp: "2022-10-31T17:41:14Z"
  labels:
    kubernetes.io/metadata.name: kube-flannel
    pod-security.kubernetes.io/enforce: privileged
  name: kube-flannel
  resourceVersion: "4021"
  uid: 744fece7-1e97-45af-a59d-84ec3830337e
spec:
  finalizers:
  - kubernetes
status:
  phase: Active

创建以及删除命名空间

[root@node01 ~]#  kubectl create ns web
namespace/web created
[root@node01 ~]# kubectl get ns web
NAME   STATUS   AGE
web    Active   14s
[root@node01 ~]#  kubectl delete ns web      
namespace "web" deleted

查看pod

查看所有pod

kubectl get pods --all-namespaces
 kubectl get pods -A

指定某个命名空间下的pod

[root@node01 ~]# kubectl get pods -n kube-flannel
NAME                    READY   STATUS    RESTARTS   AGE
kube-flannel-ds-7vbkn   1/1     Running   0          24h
kube-flannel-ds-lpfvv   1/1     Running   0          25h
kube-flannel-ds-vtrk8   1/1     Running   0          24h

查看资源详情

查看node详情

使用 KuboardSpray 图形化安装kubernetes集群详情 kubectl cluster-info_nginx_02

node的基本信息 名称、标签、创建时间
node当前的运行状态 NetworkUnavailable 网络是不是不正常、MemoryPressure 内存是否不足、DiskPressure磁盘是否不足、PIDPressure PID资源是否不足,任意一个不足 Ready会为false。
node的主机地址与主机名
node可用的系统资源 cpu 内存 最大可以调度的pod数
主机系统信息

查看namespace详情

[root@node01 ~]# kubectl describe ns kube-flannel
Name:         kube-flannel
Labels:       kubernetes.io/metadata.name=kube-flannel
              pod-security.kubernetes.io/enforce=privileged
Annotations:  <none>
Status:       Active

No resource quota.

No LimitRange resource.

查看pod详情

kubectl describe pod etcd-master -n kube-system

这里会发现一个问题,想要查看ns时不晓得具体有哪些,还得通过 get ns 查看,如果可以自动提示出来就好了

自动补全

kubectl命令繁多,不太好记,需要安装一个自动补全工具

#yum 安装
yum -y install bash-completion
source /usr/share/bash-completion/bash_completion
echo "source <(kubectl completion bash)" >> ~/.bashrc
source ~/.bashrc

这个时候按空格就会提示可以执行的命令

[root@node01 ~]# kubectl get ns 
default               kube-flannel          kube-node-lease       kube-public           kubernetes-dashboard  kube-system 
[root@node01 ~]# kubectl get ns kube-
kube-flannel     kube-node-lease  kube-public      kube-system

创建一个ns 并起一个pod

Basic Commands (Beginner):
# 从文件或者标准输入中创建资源 值的时可以通过yaml方式创建,也可以直接命令行
  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
  # 起一个pod
  run           Run a particular image on the cluster
  set           Set specific features on objects
# 创建namespace dev
kubectl create ns dev

[root@node01 ~]# kubectl run nginx --image=nginx --port=80 --namespace dev       
pod/nginx created
[root@node01 ~]# kubectl get pod -n dev -o wide 
NAME    READY   STATUS    RESTARTS   AGE   IP           NODE     NOMINATED NODE   READINESS GATES
nginx   1/1     Running   0          62s   10.244.1.4   node01   <none>           <none>

[root@node01 ~]# curl 10.244.1.4
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
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>

删除pod

kubectl delete pod nginx --namespace=dev

通过yaml方式创建 ns pod

创建一个ns.yml 内容如下

apiVersion: v1
kind: Namespace
metadata:
  name: tomcat
# 创建ns
[root@node01 mnt]# kubectl create -f ns.yml 
namespace/tomcat created
[root@node01 mnt]# kubectl get ns tomcat
NAME     STATUS   AGE
tomcat   Active   40s

准备一个tomcat.yml内容如下

apiVersion: v1
kind: Pod #现在创建的时pod,后面还会有service等,创建ns时使用Namespace,kubectl create就是通过这个kind判断需要创建什么资源。因此它能一个命令通用
metadata:
  name: tomcat8
  namespace: tomcat # 归属命名空间
  labels: #添加一个label标签
    tag: tomcat
spec:
  containers:
  - image: tomcat:8
    imagePullPolicy: IfNotPresent # 这里不用yaml创建的时候默认时always
    name: tomcat
    ports:
    - name: tomcat-port
      containerPort: 8080
      protocol: TCP
[root@node01 mnt]# kubectl create -f tomcat.yml 
pod/tomcat8 created

[root@node01 mnt]# kubectl get pod tomcat8 -n tomcat -o wide
NAME      READY   STATUS    RESTARTS   AGE     IP           NODE     NOMINATED NODE   READINESS GATES
tomcat8   1/1     Running   0          5m19s   10.244.1.5   node01   <none>           <none>

[root@node01 mnt]# curl 10.244.1.5:8080

通过yaml删除

通过yaml创建的同时也是可以指定当初的yaml删除,与create一样,delete 命令对ns还是pod都通用

[root@node01 mnt]# kubectl delete -f tomcat.yml       
pod "tomcat8" deleted
[root@node01 mnt]# kubectl delete -f ns.yml 
namespace "tomcat" deleted
[root@node01 mnt]# kubectl get pod tomcat8 -n tomcat
Error from server (NotFound): namespaces "tomcat" not found

查看日志

前面的文章里讲了docker如何查看容器日志,这里k8s也是可以查看pod的日志

注意没有关闭防火墙需要开放node节点kubelet端口10250

kubectl logs podname

-c 指定容器 不指定为第一个容器

[root@node01 ~]# kubectl get pod nginx -n dev
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          23h
[root@node01 ~]# kubectl logs nginx -c nginx -n dev
/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
2022/11/01 19:21:54 [notice] 1#1: using the "epoll" event method
2022/11/01 19:21:54 [notice] 1#1: nginx/1.21.5
2022/11/01 19:21:54 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2022/11/01 19:21:54 [notice] 1#1: OS: Linux 3.10.0-1160.71.1.el7.x86_64
2022/11/01 19:21:54 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2022/11/01 19:21:54 [notice] 1#1: start worker processes
2022/11/01 19:21:54 [notice] 1#1: start worker process 31
2022/11/01 19:21:54 [notice] 1#1: start worker process 32
10.244.1.1 - - [01/Nov/2022:19:22:55 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.29.0" "-"

在pod里执行命令

kubectl exec

-c 指定容器 不指定为第一个容器

– 后面执行命令

[root@node01 ~]# kubectl exec nginx -n dev -- date
Wed Nov  2 18:30:54 UTC 2022

[root@node01 ~]# kubectl exec nginx -n dev -c nginx -- date
Wed Nov  2 18:31:35 UTC 2022

进入容器

与docker一样可以交互式的方式进入容器

[root@node01 ~]# kubectl exec -it nginx -n dev -- /bin/bash
root@nginx:/# date
Wed Nov  2 18:34:40 UTC 2022

在线编辑资源

kubectl edit

会展示yaml文件,直接可以像vim一样编辑,保存后会自动更新

kubectl edit pod tomcat8 -n tomcat

kubectl的命令就先介绍到这。后续文章会详细分析pod,service,deployment等重要资源。