kubectl全部命令用法示例

1 kubectl命令总结

首先来看看kubectl有哪些命令,使用 kubectl --help ,这里总结如下:

命令作用解释
开始的基本命令
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 将rc,svc.deploy资源暴露为新的服务
run Run a particular image on the cluster 在集群上运行特点的镜像
set Set specific features on objects在对象上设置特定的功能
运行过程中的命令
explainGet documentation for a resource获取资源的文档
get Display one or many resources展示一个或多个资源
edit Edit a resource on the server 在服务器上编辑资源
delete Delete resources by file names, stdin, resources and names, or by resources and label selector按文件名、标准输入、资源和名称或按资源与标签选择器删除资源
deploy相关命令
rollout Manage the rollout of a resource管理资源的滚动更新
scale Set a new size for a deployment, replica set, or replication controller 为deploy、rs或rc设置新的大小
autoscale Auto-scale a deployment, replica set, stateful set, or replication controller自动扩展deploy、rs、sts 或rc
集群管理命令
certificate Modify certificate resources修改资源的证书
cluster-info Display cluster information展示集群信息
top Display resource (CPU/memory) usage 展示资源(CPU/内存)使用情况
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 更新一个或多个节点上的污染
故障处理和Debug命令
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 将一个或多个本地端口转发到一个pod
proxy Run a proxy to the Kubernetes API server 运行Kubernetes API服务器的监听
cp Copy files and directories to and from containers 从容器中复制文件和目录
auth Inspect authorization 检查授权
debug Create debugging sessions for troubleshooting workloads and nodes 创建调试会话以排除工作负载和节点的故障
更进一步的命令
diff Diff the live version against a would-be applied version 将实际版本与潜在的应用版本进行比较
apply Apply a configuration to a resource by file name or stdin 根据文件名或标准输入对资源应用配置
patch Update fields of a resource 更新资源的字段
replace Replace a resource by file name or stdin 用文件名或标准输入替换资源
wait Experimental: Wait for a specific condition on one or many resources 实验性:在一个或多个资源上等待特定的条件
kustomize Build a kustomization target from a directory or URL. 从目录或URL构建kustomization目标
设置命令
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) 输出指定shell (bash或zsh)的shell完成代码
其他的命令
api-resources Print the supported API resources on the server API -resources打印服务器上支持的API资源
api-versions Print the supported API versions on the server, in the form of "group/version" 以“group/version”的形式在服务器上打印支持的API版本
config Modify kubeconfig files 修改kubeconfig文件
plugin Provides utilities for interacting with plugins 提供与插件交互的实用程序
version Print the client and server version information 打印客户端和服务器的版本信息

在这里插入图片描述

2 kubectl命令用法测试

每个命令详细的用法可以使用–help查看,这里不详细记录了,我觉得还是使用的时候查看help方便,记具体的参数含义意义不大。

create

通过文件名或控制台输入,创建资源。 先创建一个文件file.yaml, 使用create创建一个pod

# 创建一个file.yaml 
[root@nginx k8shandbook] #cat > file.yaml << EOF 
apiVersion: v1
kind: Pod
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  containers:
  - name: nginx
    image: nginx
    ports:
    - containerPort: 80
EOF

[root@nginx k8shandbook]# kubectl create -f file.yaml 
pod/nginx created
expose

启动暴露刚才pod的端口的svc,让外部可以访问。

[root@nginx k8shandbook]# kubectl expose po  nginx --port=80 --target-port=80 --type=NodePort
service/nginx exposed
run

删除刚建pod,通过run 直接启动一个pod

[root@nginx k8shandbook]# kubectl run --image=nginx:alpine nginx-app --port=80
pod/nginx-app created
set

将pod nginx-app中容器niginx-app的镜像版本调整为:1.9.1

[root@nginx k8shandbook]# kubectl set image pod/nginx-app  nginx-app=nginx:1.9.1
pod/nginx-app image updated
explain
[root@nginx k8shandbook]#  kubectl explain pods
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

FIELDS:
   apiVersion	<string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

   kind	<string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

   metadata	<Object>
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   spec	<Object>
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

   status	<Object>
     Most recently observed status of the pod. This data may not be up to date.
     Populated by the system. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

get
[root@nginx k8shandbook]# kubectl get pods 
NAME        READY   STATUS    RESTARTS   AGE
nginx-app   1/1     Running   1          33m
edit

使用默认编辑器 编辑服务器上定义的资源。

[root@nginx k8shandbook]# kubectl edit pod/nginx-app 
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
kind: Pod
metadata:
  annotations:
    cni.projectcalico.org/podIP: 10.42.1.11/32
    cni.projectcalico.org/podIPs: 10.42.1.11/32
  creationTimestamp: "2021-10-29T10:09:18Z"
  labels:
    run: nginx-app
  name: nginx-app
  namespace: default
  resourceVersion: "263525"
  selfLink: /api/v1/namespaces/default/pods/nginx-app
  uid: f4f16540-eeb5-4ae5-97a3-e8180c59d873
spec:
"/tmp/kubectl-edit-2758602883.yaml" 100L, 2855C
delete

通过配置文件名、stdin、资源名称或label选择器来删除资源。

[root@nginx k8shandbook]# kubectl delete pods nginx-app  
pod "nginx-app" deleted
[root@nginx k8shandbook]# kubectl delete -f file.yaml 
rollout

对资源deployments, daemonsets进行管理
子命令

  • history(查看历史版本)
  • pause(暂停资源)
  • resume(恢复暂停资源)
  • status(查看资源状态)
  • undo(回滚版本)
cat > nginx-deploy.yaml << EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    run: nginx-app
  name: nginx-app
  namespace: default
spec:
  replicas: 1
  selector:
    matchLabels:
      run: nginx-app
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      labels:
        run: nginx-app
    spec:
      containers:
      - image: nginx
        name: nginx-app
        ports:
        - containerPort: 80
          protocol: TCP
      dnsPolicy: ClusterFirst
      restartPolicy: Always
EOF
[root@nginx k8shandbook]# kubectl apply -f nginx-deploy.yaml 
deployment.apps/nginx-app created
[root@nginx k8shandbook]# kubectl rollout history deploy/nginx-app
deployment.apps/nginx-app 
REVISION  CHANGE-CAUSE
1         <none>
[root@nginx k8shandbook]# kubectl rollout status deploy/nginx-app 
deployment "nginx-app" successfully rolled out
[root@nginx k8shandbook]# kubectl rollout pause  deploy/nginx-app 
deployment.apps/nginx-app paused
[root@nginx k8shandbook]# kubectl rollout resume  deploy/nginx-app 
deployment.apps/nginx-app resumed
scale

扩容或缩容 Deployment、ReplicaSet、Replication Controller或 Job 中Pod数量。
scale也可以指定多个前提条件,如:当前副本数量或 --resource-version ,进行伸缩比例设置前,系统会先验证前提条件是否成立。
[root@nginx k8shandbook]# kubectl scale --replicas=3 deploy/nginx-app
deployment.apps/nginx-app scaled

autoscale

使用 autoscaler 自动设置在kubernetes集群中运行的pod数量(水平自动伸缩)。
指定Deployment、ReplicaSet或ReplicationController,并创建已经定义好资源的自动伸缩器。使用自动伸缩器可以根据需要自动增加或减少系统中部署的pod数量。

[root@nginx k8shandbook]# kubectl autoscale deployment nginx-app --min=2 --max=10 --cpu-percent=80
horizontalpodautoscaler.autoscaling/nginx-app autoscaled
certificate

kubectl certificate用来修改证书资源,可选approve/deny同意与拒绝审批。

cluster-info

显示集群信息

[root@nginx k8shandbook]# kubectl cluster-info
Kubernetes control plane is running at https://81.68.101.212:6443
CoreDNS is running at https://81.68.101.212:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
top

查看node、pod 的实时资源使用情况:如CPU、内存。

[root@nginx k8shandbook]# kubectl top node 
NAME            CPU(cores)   CPU%   MEMORY(bytes)   MEMORY%   
81.68.101.212   102m         10%    1234Mi          71%       
81.68.229.215   113m         11%    1172Mi          67%       
[root@nginx k8shandbook]# kubectl top pod
NAME                         CPU(cores)   MEMORY(bytes)   
nginx-app-69ff7df578-hn22r   0m           5Mi             
nginx-app-69ff7df578-q7bsn   0m           1Mi             
nginx-app-69ff7df578-s4zsm   0m           1Mi     
cordon

将node标记为不可调度的状态,这样就不会让新创建的pod在此node上运行。

[root@nginx k8shandbook]# kubectl get node
NAME            STATUS   ROLES                      AGE   VERSION
81.68.101.212   Ready    controlplane,etcd,worker   7d    v1.17.9
81.68.229.215   Ready    controlplane,etcd,worker   7d    v1.17.9
[root@nginx k8shandbook]# kubectl cordon 81.68.101.212
node/81.68.101.212 cordoned
uncordon

恢复node为可调度的状态。

[root@nginx k8shandbook]# kubectl uncordon 81.68.101.212
node/81.68.101.212 uncordoned
drain

可以让node在维护期间排除节点。drain本意排水,意思是将出问题的node下的pod转移到其它node下运行。

[root@nginx k8shandbook]# kubectl drain 81.68.101.212 --ignore-daemonsets --delete-local-data  
Flag --delete-local-data has been deprecated, This option is deprecated and will be deleted. Use --delete-emptydir-data.
node/81.68.101.212 already cordoned
WARNING: ignoring DaemonSet-managed Pods: ingress-nginx/nginx-ingress-controller-lh6qm, kube-system/canal-s92dx
evicting pod kube-system/rke-network-plugin-deploy-job-v5glb
evicting pod default/nginx-app-69ff7df578-hn22r
evicting pod kube-system/coredns-7c5566588d-rhdtx
evicting pod kube-system/coredns-autoscaler-65bfc8d47d-4mdt5
evicting pod kube-system/metrics-server-6b55c64f86-zlz4l
evicting pod kube-system/rke-coredns-addon-deploy-job-gv65p
evicting pod kube-system/rke-ingress-controller-deploy-job-htvk8
evicting pod kube-system/rke-metrics-addon-deploy-job-cdcgn
pod/rke-ingress-controller-deploy-job-htvk8 evicted
pod/rke-metrics-addon-deploy-job-cdcgn evicted
pod/rke-network-plugin-deploy-job-v5glb evicted
pod/rke-coredns-addon-deploy-job-gv65p evicted
pod/nginx-app-69ff7df578-hn22r evicted
pod/coredns-7c5566588d-rhdtx evicted
pod/coredns-autoscaler-65bfc8d47d-4mdt5 evicted
pod/metrics-server-6b55c64f86-zlz4l evicted
node/81.68.101.212 evicted

evicted: 驱逐

taint

taint用来更新一个或多个节点上的taint,节点亲和性是pod的一种属性(偏好或硬性要求),它使pod被吸引到一类特定的节点。taint 则相反,它使节点能够排斥一类特定的pod。taint和toleration相互配合,可以用来避免pod被分配到不合适的节点上。每个节点上都可以应用一个或多个taint ,这表示对于那些不能容忍这些 taint 的 pod,是不会被该节点接受的。如果将 toleration 应用于 pod 上,则表示这些 pod 可以(但不要求)被调度到具有匹配 taint 的节点上。

# 为节点添加污染
[root@nginx k8shandbook]# kubectl taint nodes 81.68.101.212 key=value:NoSchedule
node/81.68.101.212 tainted
#为节点解除污染
[root@nginx k8shandbook]# kubectl taint nodes 81.68.101.212 key:NoSchedule-
node/81.68.101.212 untainted
describe

输出指定的一个/多个资源的详细信息。

[root@nginx k8shandbook]# kubectl describe pods nginx-app-69ff7df578-b2crq
Name:         nginx-app-69ff7df578-b2crq
Namespace:    default
Priority:     0
Node:         81.68.229.215/81.68.229.215
Start Time:   Fri, 29 Oct 2021 19:30:22 +0800
Labels:       pod-template-hash=69ff7df578
              run=nginx-app
Annotations:  cni.projectcalico.org/podIP: 10.42.1.17/32
              cni.projectcalico.org/podIPs: 10.42.1.17/32
Status:       Running
IP:           10.42.1.17
IPs:
  IP:           10.42.1.17
Controlled By:  ReplicaSet/nginx-app-69ff7df578
Containers:
  nginx-app:
    Container ID:   docker://cdbd1536d991c99b7c4c9ccb8d925f00e468b0c13ade7ccd0bed94179c262e34
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:644a70516a26004c97d0d85c7fe1d0c3a67ea8ab7ddf4aff193d9f301670cf36
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Fri, 29 Oct 2021 19:30:39 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-bbb98 (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-bbb98:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-bbb98
    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  7m23s  default-scheduler  Successfully assigned default/nginx-app-69ff7df578-b2crq to 81.68.229.215
  Normal  Pulling    7m21s  kubelet            Pulling image "nginx"
  Normal  Pulled     7m6s   kubelet            Successfully pulled image "nginx"
logs

输出指定资源的日志信息。

[root@nginx k8shandbook]# kubectl logs --tail=5 nginx-app-69ff7df578-b2crq 
2021/10/29 11:30:39 [notice] 1#1: built by gcc 8.3.0 (Debian 8.3.0-6) 
2021/10/29 11:30:39 [notice] 1#1: OS: Linux 3.10.0-1160.11.1.el7.x86_64
2021/10/29 11:30:39 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/10/29 11:30:39 [notice] 1#1: start worker processes
2021/10/29 11:30:39 [notice] 1#1: start worker process 30
attach

连接到容器

[root@nginx k8shandbook]#  kubectl attach nginx-app-69ff7df578-b2crq
If you don't see a command prompt, try pressing enter.
exec

执行容器命令

[root@nginx k8shandbook]# kubectl exec nginx-app ps aux
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
PID   USER     TIME  COMMAND
    1 root      0:00 nginx: master process nginx -g daemon off;
   31 nginx     0:00 nginx: worker process
   32 root      0:00 ps aux
port-forward

中文文档解释

proxy

中文文档解释

cp
# 容器中要有tar
[root@nginx k8shandbook]# kubectl exec -it cloud-786d84 /bin/bash
bash-4.2# yum -y install tar
# 从Pod容器中copy文件至本地
[root@nginx k8shandbook]kubectl cp -c cloud-loan-gate uat/cloud-786d84:app/logs/app/cloud.log cloud.log
auth

用于身份验证检查授权。该命令不常用。
可以检查一个动作是否被允许,协调RBAC角色、角色绑定、集群角色和集群角色绑定对象的规则。

debug

参考

diff

显示yaml文件中资源的差异

[root@nginx k8shandbook]# kubectl diff -f file.yaml 
diff -u -N /tmp/LIVE-489520927/v1.Pod.default.nginx /tmp/MERGED-948858866/v1.Pod.default.nginx
--- /tmp/LIVE-489520927/v1.Pod.default.nginx	2021-10-29 21:09:47.697993162 +0800
+++ /tmp/MERGED-948858866/v1.Pod.default.nginx	2021-10-29 21:09:47.697993162 +0800
apply

通过文件名或控制台输入,对资源进行配置。

[root@nginx k8shandbook]# kubectl apply -f file.yaml 
pod/nginx created

与create的差别:

  • kubectl create命令可创建新资源。 因此,如果再次运行该命令,则会抛出错误,因为资源名称在名称空间中应该是唯一的。
  • kubectl apply命令将配置应用于资源。 如果资源不在那里,那么它将被创建。 kubectl apply命令可以第二次运行,因为它只是应用如下所示的配置。 在这种情况下,配置没有改变。 所以,pod没有改变。
patch

使用(patch)补丁修改、更新资源的字段。

[root@nginx k8shandbook]# kubectl patch node 81.68.101.212 -p '{"spec":{"unschedulable":true}}'
node/81.68.101.212 patched
replace

使用配置文件或stdin来替换资源。支持JSON和YAML格式。如果替换当前资源,则必须提供完整的资源规范。

[root@nginx k8shandbook]# kubectl replace --force -f file.yaml 
pod "nginx" deleted
pod/nginx replaced
wait

kubectl wait在一个或多个资源上等待一个条件

kustomize

参考:https://blog.csdn.net/kozazyh/article/details/89092839

label

更新(增加、修改或删除)资源上的标签

  • label 必须以字母或数字开头,可以使用字母、数字、连字符、点和下划线,最长63个字符。
  • 如果–overwrite 为 true,则可以覆盖已有的 label,否则尝试覆盖 label 将会报错。
  • 如果指定了–resource-version,则更新将使用此资源版本,否则将使用现有的资源版本。
# 新增标签
[root@nginx k8shandbook]# kubectl label po nginx unhealthy=true
pod/nginx labeled
# 修改标签
[root@nginx k8shandbook]# kubectl label --overwrite=true po nginx unhealthy=false
pod/nginx labeled
# 删除标签
[root@nginx k8shandbook]# kubectl label po nginx unhealthy-
pod/nginx labeled
annotate

更新一个或多个资源的Annotations信息。

  • Annotations由key/value组成。
  • Annotations的目的是存储辅助数据,特别是通过工具和系统扩展操作的数据,更多介绍在这里。
  • 如果–overwrite为true,现有的annotations可以被覆盖,否则试图覆盖annotations将会报错。
  • 如果设置了–resource-version,则更新将使用此resource version,否则将使用原有的resource version。
# 添加注释
[root@nginx k8shandbook]# kubectl annotate pod nginx descripotion="this is a pod" 
pod/nginx annotated
# 修改注释
[root@nginx k8shandbook]# kubectl annotate --overwrite=true pod nginx descripotion="this is not a pod" 
pod/nginx annotated
# 删除注释
[root@nginx k8shandbook]# kubectl annotate  pod nginx descripotion-
pod/nginx annotated
completion

不常用

api-resources

显示k8s集群中的所有api资源信息

[root@nginx k8shandbook]# 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/v1beta1       false        CertificateSigningRequest
leases                                         coordination.k8s.io/v1            true         Lease
bgpconfigurations                              crd.projectcalico.org/v1          false        BGPConfiguration
bgppeers                                       crd.projectcalico.org/v1          false        BGPPeer
blockaffinities                                crd.projectcalico.org/v1          false        BlockAffinity
clusterinformations                            crd.projectcalico.org/v1          false        ClusterInformation
felixconfigurations                            crd.projectcalico.org/v1          false        FelixConfiguration
globalnetworkpolicies                          crd.projectcalico.org/v1          false        GlobalNetworkPolicy
globalnetworksets                              crd.projectcalico.org/v1          false        GlobalNetworkSet
hostendpoints                                  crd.projectcalico.org/v1          false        HostEndpoint
ipamblocks                                     crd.projectcalico.org/v1          false        IPAMBlock
ipamconfigs                                    crd.projectcalico.org/v1          false        IPAMConfig
ipamhandles                                    crd.projectcalico.org/v1          false        IPAMHandle
ippools                                        crd.projectcalico.org/v1          false        IPPool
networkpolicies                                crd.projectcalico.org/v1          true         NetworkPolicy
networksets                                    crd.projectcalico.org/v1          true         NetworkSet
endpointslices                                 discovery.k8s.io/v1beta1          true         EndpointSlice
events                            ev           events.k8s.io/v1beta1             true         Event
ingresses                         ing          extensions/v1beta1                true         Ingress
nodes                                          metrics.k8s.io/v1beta1            false        NodeMetrics
pods                                           metrics.k8s.io/v1beta1            true         PodMetrics
ingresses                         ing          networking.k8s.io/v1beta1         true         Ingress
networkpolicies                   netpol       networking.k8s.io/v1              true         NetworkPolicy
runtimeclasses                                 node.k8s.io/v1beta1               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/v1beta1            false        CSIDriver
csinodes                                       storage.k8s.io/v1                 false        CSINode
storageclasses                    sc           storage.k8s.io/v1                 false        StorageClass
volumeattachments                              storage.k8s.io/v1                 false        VolumeAttachment
api-versions

以“组/版本”的格式输出服务端支持的API版本

[root@nginx k8shandbook]# kubectl api-versions 
admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1
coordination.k8s.io/v1beta1
crd.projectcalico.org/v1
discovery.k8s.io/v1beta1
events.k8s.io/v1beta1
extensions/v1beta1
metrics.k8s.io/v1beta1
networking.k8s.io/v1
networking.k8s.io/v1beta1
node.k8s.io/v1beta1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1
config

config命令,生成集群信息,集群用户和用户权限并把这些内容写入kubectl读取的配置文件

# 设置集群参数
[root@k8s-master admin]# kubectl config set-cluster kubernetes --certificate-authority=/etc/kubernetes/cert/ca.pem --embed-certs=true --server=${KUBE_APISERVER} --kubeconfig=kubectl.kubeconfig
#设置客户端认证参数
[root@k8s-master admin]# kubectl config set-credentials admin --client-certificate=admin.pem --client-key=admin-key.pem --embed-certs=true --kubeconfig=kubectl.kubeconfig
#设置上下文参数,包含集群名称和访问集群的用户名字
[root@k8s-master admin]# kubectl config set-context kubernetes --cluster=kubernetes --user=admin --kubeconfig=kubectl.kubeconfig
#使用默认上下文
[root@k8s-master admin]# kubectl config use-context kubernetes --kubeconfig=kubectl.kubeconfig
Switched to context "kubernetes".
plugin

提供与插件交互的实用程序,插件提供了不属于主要命令行发行版的扩展功能。

version

输出服务端和客户端的版本信息。

[root@nginx k8shandbook]# kubectl version  
Client Version: version.Info{Major:"1", Minor:"22", GitVersion:"v1.22.2", GitCommit:"8b5a19147530eaac9476b0ab82980b4088bbc1b2", GitTreeState:"clean", BuildDate:"2021-09-15T21:38:50Z", GoVersion:"go1.16.8", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"17", GitVersion:"v1.17.9", GitCommit:"4fb7ed12476d57b8437ada90b4f93b17ffaeed99", GitTreeState:"clean", BuildDate:"2020-07-15T16:10:45Z", GoVersion:"go1.13.9", Compiler:"gc", Platform:"linux/amd64"}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用 `kubectl` 创建 Pod 的命令如下: ``` kubectl create -f path/to/pod.yaml ``` 其中 `path/to/pod.yaml` 是你的 Pod 描述文件的路径。Pod 描述文件应包含以下信息: ``` apiVersion: v1 kind: Pod metadata: name: my-pod spec: containers: - name: my-container image: my-image ``` 其中 `apiVersion` 和 `kind` 指定了资源的类型(在这种情况下是 Pod),`metadata` 中的 `name` 属性指定了 Pod 的名称,`spec` 中的 `containers` 数组描述了 Pod 中运行的容器,包括容器的名称和镜像。 运行 `kubectl create` 命令后,Kubernetes 会在集群中创建一个新的 Pod。 你也可以使用 `kubectl run` 命令来直接创建 Pod,而无需提供 Pod 描述文件。例如,以下命令会在集群中创建一个名为 `my-pod` 的 Pod,并运行 `nginx` 镜像: ``` kubectl run my-pod --image=nginx ``` ### 回答2: 使用kubectl命令创建pod是一种直接在Kubernetes集群上创建和管理容器的方法。以下是使用kubectl创建pod的步骤: 1. 在本地或远程的终端中打开命令行。 2. 确保kubectl命令已正确配置并与Kubernetes集群连接。可以通过运行`kubectl version`来验证kubectl的版本和集群连接状态。 3. 使用以下命令创建pod,并指定pod配置的YAML文件路径: ``` kubectl create -f <pod-配置-YAML-文件路径> ``` 在该命令中,`<pod-配置-YAML-文件路径>`应替换为要创建的Pod配置的YAML文件的路径。 4. 执行此命令后,kubectl将发送请求到Kubernetes API服务器,创建pod,并返回创建结果。 例如: ``` pod/pod-example created ``` 5. 可以使用`kubectl get pods`命令来验证Pod的创建状态和详细信息。 ``` kubectl get pods ``` 此命令将返回集群中所有已创建的Pod的列表。 通过使用kubectl命令和Pod配置的YAML文件,我们可以直接在Kubernetes集群上创建和管理我们的容器。这种方法非常灵活和方便,可以满足运行不同类型应用程序的需求。 ### 回答3: 使用kubectl创建pod的命令是`kubectl create pod`。 创建pod时,可以通过指定参数来定义pod的属性。例如,可以使用`--image`参数来指定pod所使用的容器镜像,使用`--name`参数来为pod指定一个名称。 以下是一个示例命令: ``` kubectl create pod my-pod --image=nginx:latest ``` 这个命令会创建一个名为my-pod的pod,并使用最新的nginx镜像。 除了指定镜像,还可以通过其他参数来自定义pod的属性,比如指定端口、环境变量等。 不过需要注意的是,直接创建pod可能并不是最佳实践。通常情况下,我们更推荐使用其他资源对象,如Deployment或StatefulSet来创建和管理pod。这些资源对象可以提供更高级的功能,比如自动回滚、扩缩容等。因此,在实际使用中,我们更常见使用类似以下命令来创建pod: ``` kubectl create deployment my-deployment --image=nginx:latest ``` 这个命令会创建一个名为my-deployment的Deployment对象,并在该Deployment下创建一个pod。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值