#############常用命令#################

## kubectl常用参数

  1. help—获取帮助  如,kubectl get pods –help
  2. get— 显示有关一个或多个资源的信息。 可以将get和单个对象一起使用,并添加--watch标志以实时观察更新。
  3. describe—显示关于一个或多个资源的详细信息
  4. logs—显示容器日志 。logs命令需要一个pod名称。当在多个pod中时,使用-c my-container标志来指定一个容器。使用--previous标志来获取不再运行的容器信息
  5. exec—进入容器中一个正在运行的进程。例如,要在my_pod中进入容器并运行Bash,请输入kubectl exec -it my_pod bash。
  6. apply—创建或选择一个资源。 如果资源不存在,apply将创建它;如果它存在,apply将更改
  7. delete—删除一个或多个资源。 kubectl delete pod my_pod这一命令可用于删除名称为my_pod的Pod。要删除所有相同类型的资源,需要使用--all标志。例如,使用kubectl delete rs –all 。 请注意,如果你尝试这一操作,那么要先删除Deployment,否则ReplicaSet将会重新启动。

## 新建命名空间

kubectl create namespace xxx

查看命名空间详情

kubectl describe namespace xxx

## 获得当前命名空间下所有Events的列表

kubectl get events -n xxx

## 查看容器中的根容器 Pause 容器

在容器节点上执行如下命令

docker ps | grep pause

## 查看node的信息

kubectl describe node k8s-n2

## 查看 Nginx Ingress Controller

kubectl get pods -n ingress-nginx -o wide

kubectl get pods -n ingress-nginx-web -o wide

## 服务管理(storageclass)

删除 kubectl delete storageclass [xxxName]

获取 kubectl get storageclass

## 查看pod的网段信息

kubectl get pod -n longzhou -o wide

## 删除statefulset服务

kubectl delete statefulset  xxxx

##查看ingressclass

#>kubectl get ingress -n kb -o yaml kb-service

或者

#>kubectl exec nginx-ingress-controller-8488d74f44-hr2cm -n ingress-nginx-ant-nginx -- grep ''kb" /etc/nginx/nginx.conf

##查看pods

##kubectl get ns

#>kubectl get pods -n <your-namespace>  # 列出某 namespace 中的所有 pod

删除pod

#>kubectl delete pods kb-service-xxx -n kb

强制删除pod

#>kubectl delete pods kb-service-xxx -n kb --grace-period=0 --force

##进入pod命令行

#>kubectl exec -it <pod-name>  -n <your-namespace>  --  /bin/bash

##查看pod日志

#>kubectl logs -f <pod-name> -n <your-namespace>   # 流式输出 pod 的日志(stdout),指定namespace

显示和查找资源

Get commands with basic output

$ kubectl get services # 列出所有 namespace 中的所有 service

$ kubectl get pods --all-namespaces # 列出所有 namespace 中的所有 pod

$ kubectl get pods -o wide # 列出所有 pod 并显示详细信息

$ kubectl get deployment my-dep # 列出指定 deployment

$ kubectl get pods --include-uninitialized # 列出该 namespace 中的所有 pod 包括未初始化的

创建对象

通过yaml文件创建:

kubectl create -f xxx.yaml (不建议使用,无法更新,必须先delete)

kubectl apply -f xxx.yaml (创建+更新,可以重复使用)

删除对象

通过yaml文件删除:

kubectl delete -f xxx.yaml

查看kube-system namespace下面的pod/svc/deployment 等等

(-o wide 选项可以查看存在哪个对应的节点)

kubectl get pod/svc/deployment -n kube-system

查看所有namespace下面的pod/svc/deployment等等

kubectl get pod/svc/deployment --all-namcpaces

重启pod

(无法删除对应的应用,因为存在deployment/rc之类的副本控制器,删除pod也会重新拉起来)

#######################################

> kubectl version

Client Version: version.Info{Major:"1", Minor:"12", GitVersion:"v1.12.10", GitCommit:"e3c134023df5dea457638b614ee17ef234dc34a6", GitTreeState:"clean", BuildDate:"2019-07-08T03:50:59Z", GoVersion:"go1.10.8", Compiler:"gc", Platform:"linux/amd64"}

Server Version: version.Info{Major:"1", Minor:"12+", GitVersion:"v1.12.10-rancher1", GitCommit:"71fde6aadce8b92456b88ee56c21e500f4919f0b", GitTreeState:"clean", BuildDate:"2019-09-03T20:32:01Z", GoVersion:"go1.10.8", Compiler:"gc", Platform:"linux/amd64"}

> 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, Replication Controller, or Job

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

Advanced Commands:

apply          Apply a configuration to a resource by filename or stdin

patch          Update field(s) of a resource using strategic merge patch

replace        Replace a resource by filename or stdin

wait           Experimental: Wait for a specific condition on one or many resources.

convert        Convert config files between different API versions

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:

alpha          Commands for features in alpha

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]

#######################################

kubectl get pod -n kube-system

查看pod描述:

kubectl describe pod XXX -n kube-system

查看pod 日志 (如果pod有多个容器需要加-c 容器名)

kubectl logs xxx -n kube-system

删除应用(先确定是由说明创建的,再删除对应的kind):

kubectl delete deployment xxx -n kube-system

根据label删除:

kubectl delete pod -l app=flannel -n kube-system

扩容

kubectl scale deployment spark-worker-deployment --replicas=8

导出配置文件:

导出proxy

  kubectl get ds -n kube-system -l k8s-app=kube-proxy -o yaml>kube-proxy-ds.yaml

  导出kube-dns

  kubectl get deployment -n kube-system -l k8s-app=kube-dns -o yaml >kube-dns-dp.yaml

  kubectl get services -n kube-system -l k8s-app=kube-dns -o yaml >kube-dns-services.yaml

  导出所有 configmap

  kubectl get configmap -n kube-system -o wide -o yaml > configmap.yaml

查看集群信息

kubectl cluster-info

查看各组件信息

kubectl get componentstatuses

#查看kubelet进程启动参数

ps -ef | grep kubelet

查看日志:

journalctl -u kubelet -f

设为不可调度状态:

kubectl cordon node1

将pod赶到其他节点:

kubectl drain node1

解除不可调度状态

kubectl uncordon node1

master运行pod

kubectl taint nodes master.k8s node-role.kubernetes.io/master-

master不运行pod

kubectl taint nodes master.k8s node-role.kubernetes.io/master=:NoSchedule

使用详细输出来描述命令

$ kubectl describe nodes my-node

$ kubectl describe pods my-pod

$ kubectl get services --sort-by=.metadata.name # List Services Sorted by Name

根据重启次数排序列出 pod

$ kubectl get pods --sort-by=’.status.containerStatuses[0].restartCount’

获取所有具有 app=cassandra 的 pod 中的 version 标签

$ kubectl get pods --selector=app=cassandra rc -o

jsonpath=’{.items[*].metadata.labels.version}’

获取所有节点的 ExternalIP

$ kubectl get nodes -o jsonpath=’{.items[*].status.addresses[?(@.type==“ExternalIP”)].address}’

列出属于某个 PC 的 Pod 的名字

“jq”命令用于转换复杂的 jsonpath,参考 https://stedolan.github.io/jq/

$ sel=KaTeX parse error: Expected '}', got 'EOF' at end of input: {(kubectl get rc my-rc --output=json | jq -j ‘.spec.selector | to_entries | .[] | “(.key)=(.value),”’)%?}

$ echo (kubectlgetpods−−selector= (kubectl get pods --selector=(kubectlgetpods−−selector=sel --output=jsonpath={.items…metadata.name})

查看哪些节点已就绪

$ JSONPATH=’{range .items[]}{@.metadata.name}:{range @.status.conditions[]}{@.type}={@.status};{end}{end}’

&& kubectl get nodes -o jsonpath="$JSONPATH" | grep “Ready=True”

列出当前 Pod 中使用的 Secret

$ kubectl get pods -o json | jq ‘.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name’ | grep -v null | sort | uniq

更新资源

$ kubectl rolling-update frontend-v1 -f frontend-v2.json # 滚动更新 pod frontend-v1

$ kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2 # 更新资源名称并更新镜像

$ kubectl rolling-update frontend --image=image:v2 # 更新 frontend pod 中的镜像

$ kubectl rolling-update frontend-v1 frontend-v2 --rollback # 退出已存在的进行中的滚动更新

$ cat pod.json | kubectl replace -f - # 基于 stdin 输入的 JSON 替换 pod

强制替换,删除后重新创建资源。会导致服务中断。

$ kubectl replace --force -f ./pod.json

为 nginx RC 创建服务,启用本地 80 端口连接到容器上的 8000 端口

$ kubectl expose rc nginx --port=80 --target-port=8000

更新单容器 pod 的镜像版本(tag)到 v4

$ kubectl get pod mypod -o yaml | sed ‘s/(image: myimage):.*$/\1:v4/’ | kubectl replace -f -

$ kubectl label pods my-pod new-label=awesome # 添加标签

$ kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq # 添加注解

$ kubectl autoscale deployment foo --min=2 --max=10 # 自动扩展 deployment “foo”

修补资源

使用策略合并补丁并修补资源。

$ kubectl patch node k8s-node-1 -p ‘{“spec”:{“unschedulable”:true}}’ # 部分更新节点

更新容器镜像; spec.containers[*].name 是必须的,因为这是合并的关键字

$ kubectl patch pod valid-pod -p ‘{“spec”:{“containers”:[{“name”:“kubernetes-serve-hostname”,“image”:“new image”}]}}’

使用具有位置数组的 json 补丁更新容器镜像

$ kubectl patch pod valid-pod --type=‘json’ -p=’[{“op”: “replace”, “path”: “/spec/containers/0/image”, “value”:“new image”}]’

使用具有位置数组的 json 补丁禁用 deployment 的 livenessProbe

$ kubectl patch deployment valid-deployment --type json -p=’[{“op”: “remove”, “path”: “/spec/template/spec/containers/0/livenessProbe”}]’

编辑资源

在编辑器中编辑任何 API 资源。

$ kubectl edit svc/docker-registry # 编辑名为 docker-registry 的 service

$ KUBE_EDITOR=“nano” kubectl edit svc/docker-registry # 使用其它编辑器

Scale 资源

$ kubectl scale --replicas=3 rs/foo # Scale a replicaset named ‘foo’ to 3

$ kubectl scale --replicas=3 -f foo.yaml # Scale a resource specified in “foo.yaml” to 3

$ kubectl scale --current-replicas=2 --replicas=3 deployment/mysql # If the deployment named mysql’s current size is 2, scale mysql to 3

$ kubectl scale --replicas=5 rc/foo rc/bar rc/baz # Scale multiple replication controllers

删除资源

$ kubectl delete -f ./pod.json # 删除 pod.json 文件中定义的类型和名称的 pod

$ kubectl delete pod,service baz foo # 删除名为“baz”的 pod 和名为“foo”的 service

$ kubectl delete pods,services -l name=myLabel # 删除具有 name=myLabel 标签的 pod 和 serivce

$ kubectl delete pods,services -l name=myLabel --include-uninitialized # 删除具有 name=myLabel 标签的 pod 和 service,包括尚未初始化的

$ kubectl -n my-ns delete po,svc --all # 删除 my-ns namespace 下的所有 pod 和 serivce,包括尚未初始化的

与运行中的 Pod 交互

$ kubectl logs my-pod # dump 输出 pod 的日志(stdout)

$ kubectl logs my-pod -c my-container # dump 输出 pod 中容器的日志(stdout,pod 中有多个容器的情况下使用)

$ kubectl logs -f my-pod # 流式输出 pod 的日志(stdout)

$ kubectl logs -f my-pod -c my-container # 流式输出 pod 中容器的日志(stdout,pod 中有多个容器的情况下使用)

$ kubectl run -i --tty busybox --image=busybox – sh # 交互式 shell 的方式运行 pod

$ kubectl attach my-pod -i # 连接到运行中的容器

$ kubectl port-forward my-pod 5000:6000 # 转发 pod 中的 6000 端口到本地的 5000 端口

$ kubectl exec my-pod – ls / # 在已存在的容器中执行命令(只有一个容器的情况下)

$ kubectl exec my-pod -c my-container – ls / # 在已存在的容器中执行命令(pod 中有多个容器的情况下)

$ kubectl top pod POD_NAME --containers # 显示指定 pod 和容器的指标度量

与节点和集群交互

$ kubectl cordon my-node # 标记 my-node 不可调度

$ kubectl drain my-node # 清空 my-node 以待维护

$ kubectl uncordon my-node # 标记 my-node 可调度

$ kubectl top node my-node # 显示 my-node 的指标度量

$ kubectl cluster-info # 显示 master 和服务的地址

$ kubectl cluster-info dump # 将当前集群状态输出到 stdout

$ kubectl cluster-info dump --output-directory=/path/to/cluster-state # 将当前集群状态输出到 /path/to/cluster-state

如果该键和影响的污点(taint)已存在,则使用指定的值替换

$ kubectl taint nodes foo dedicated=special-user:NoSchedule

###########

【科普】Kubectl基本操作命令相关推荐

  1. Kubectl基本操作命令

    创建对象 通过yaml文件创建: kubectl create -f xxx.yaml (不建议使用,无法更新,必须先delete) kubectl apply -f xxx.yaml (创建+更新, ...

  2. Kubectl(完整)基本操作命令

    创建对象 通过yaml文件创建: kubectl create -f xxx.yaml (不建议使用,无法更新,必须先delete)kubectl apply -f xxx.yaml (创建+更新,可 ...

  3. Adb操作命令及详解------全面科普(测试木头人)

    今天给大家整理一下Adb命令,欢迎大家来一起学习 对此内容大家有任何疑惑大家都可以私信木头人哦 目录 一.adb概念 二.adb命令 三.adb文件操作命令 四.Adb设备信息操作命令 五.Adb监控 ...

  4. config kubectl_使用kubectl管理k8s集群(三十)

    前言 Foreword 在搭建k8s集群之前,我们需要先了解下kubectl的使用,以便在集群部署出现问题时进行检查和处理.命令和语法记不住没有关系,但是请记住主要的语法和命令以及帮助命令的使用. 在 ...

  5. Kubernetes(1) kubectl 入门

    继上章的搭建实验环境后,本章节主要介绍一些k8s的日常操作命令以及应用. 首先我们会熟悉一下 kubectl 的API 功能,随后我们会手动通过命令行输入的方式创建 Pod Deployment,且给 ...

  6. 使用kubectl管理k8s集群(三十)

    前言 Foreword 在搭建k8s集群之前,我们需要先了解下kubectl的使用,以便在集群部署出现问题时进行检查和处理.命令和语法记不住没有关系,但是请记住主要的语法和命令以及帮助命令的使用. 在 ...

  7. delete kubectl pod_使用kubectl管理k8s集群(三十)

    原标题:使用kubectl管理k8s集群(三十) 前言 Foreword 在搭建k8s集群之前,我们需要先了解下kubectl的使用,以便在集群部署出现问题时进行检查和处理.命令和语法记不住没有关系, ...

  8. kubectl :命令技巧大全

    目录 kubectl 命令技巧大全 Kubectl命令概览 命令行提示 kube-shell kubectl的身份认证 Kubectl 自动补全 Kubectl 上下文和配置 Kubectl 启动-状 ...

  9. k8s中kubectl命令的使用

    资源管理方式 命令式对象管理:直接使用命令去操作kubernetes资源 [root@master ~]# kubectl run nginx-pod --image=nginx:1.17.1 --p ...

最新文章

  1. linux中断共享程序实现,如何在非实时linux上实现实时应用程序与内核模块之间共享存储器...
  2. 用WPS表格轻松设计工资条
  3. linux usb驱动
  4. Scrapy shell调试网页的信息
  5. 处理器在实施任务切换时的操作——《x86汇编语言:从实模式到保护模式》读书笔记39
  6. IRP和IO_STACK_LOCATION
  7. STM32 定时器输出pwm的频率计算方法 PWM 频率检测方法 直流电机的位置控制
  8. ROS入门-2.Linux系统基础操作
  9. java同步和互斥程序说明(一)
  10. vbs格式编程教程基础
  11. 灰度发布和AB test
  12. apfs扩容_MacBook Pro 2018 评测:这台价值一万四的电脑到底值不值得买?
  13. 2022 年年度最佳开源软件
  14. 健身房有哪些令人讨厌的行为?
  15. 刚开始做斗音掌握这5点至少让你少走半年弯路
  16. MySQL导入Excel表格
  17. 202109-4 收集卡牌
  18. 织梦dedecms网站如何转移搬家
  19. android4.0.3 编译lichee 报错dhd-cdc-sdmmc-gpl-3.0.8问题
  20. java导入xmind的坑及解决方案

热门文章

  1. shell里的json超级工具 jq 高级用法介绍
  2. 最怕你不甘平庸,却又不去行动!
  3. 02 Ajax表单提交
  4. 在线PDF转换PPT,不用安装软件
  5. 逻辑运算符与位运算符的区别
  6. 数据结构JAVA实现——树
  7. 【ICPR 2021】遥感图中的密集小目标检测:Tiny Object Detection in Aerial Images
  8. http、https 等 常用默认端口号
  9. 使用EasyExcel下载,文件名乱码问题处理
  10. 机器学习——从线性回归到逻辑回归【附详细推导和代码】