kubectl命令_kubectl的即用型命令和技巧

kubectl命令

Kubectl is the most important Kubernetes command-line tool that allows you to run commands against clusters. We at Flant internally share our knowledge of using it via formal wiki-like instructions as well as Slack messages (we also have a handy and smart search engine in place — but that’s a whole different story…). Over the years, we have accumulated a large number of various kubectl tips and tricks. Now, we’ve decided to share some of our cheat sheets with a wider community.

Kubectl是最重要的Kubernetes命令行工具,可让您对集群运行命令。 我们在Flant内部通过类似Wiki的正式说明以及Slack消息来分享我们使用它的知识(我们还拥有一个方便,智能的搜索引擎-但这是另一个完全不同的故事……) 。 多年来,我们已经积累了大量的各种kubectl技巧和窍门。 现在,我们决定与更广泛的社区分享我们的一些备忘单。

I am sure our readers might be familiar with many of them. But still, I hope you will learn something new and, thereby, improve your productivity.

我相信我们的读者可能对其中的很多人熟悉。 但是,我仍然希望您能学到新东西,从而提高生产力。

NB: While some of the commands & techniques listed below were compiled by our engineers, others were found on the Web. In the latter case, we checked them thoroughly and found them useful.

注意 :虽然下面列出的某些命令和技术是由我们的工程师编译的,但其他命令和技术是在网络上找到的。 对于后一种情况,我们进行了彻底检查,发现它们很有用。

Well, let’s get started!

好吧,让我们开始吧!

获取吊舱和节点列表 (Getting lists of pods and nodes)

1. I guess you are all aware of how to get a list of pods across all Kubernetes namespaces using the --all-namespaces flag. Many people are so used to it that they have not noticed the emergence of its shorter version, -A (it exists since at least Kubernetes 1.15).

1.我想你们都知道如何使用--all-namespaces标志获取所有Kubernetes命名空间中的Pod列表。 许多人已经习惯了它,以至于没有注意到它的较短版本-A (至少从Kubernetes 1.15开始存在)

2. How do you find all non-running pods (i.e., with a state other than Running)?

2.如何查找所有非运行的Pod(即状态为Running以外的状态)?

kubectl get pods -A --field-selector=status.phase!=Running | grep -v Complete
Image for post

By the way, examining the --field-selector flag more closely (see the relevant documentation) might be a good general recommendation.

顺便说一句,更仔细地检查--field-selector标志(请参阅 相关文档 )可能是一个很好的一般建议。

3. Here is how you can get the list of nodes and their memory size:

3.以下是获取节点列表及其内存大小的方法:

kubectl get no -o json | \
jq -r '.items | sort_by(.status.capacity.memory)[]|[.metadata.name,.status.capacity.memory]| @tsv'
Image for post

4. Getting the list of nodes and the number of pods running on them:

4.获取节点列表和在其上运行的容器的数量:

kubectl get po -o json --all-namespaces | \
jq '.items | group_by(.spec.nodeName) | map({"nodeName": .[0].spec.nodeName, "count": length}) | sort_by(.count)'
Image for post

5. Sometimes, DaemonSet does not schedule a pod on a node for whatever reason. Manually searching for them is a tedious task, so here is a mini-script to get a list of such nodes:

5.有时,无论出于何种原因, DaemonSet都不会在节点上调度Pod。 手动搜索它们是一项繁琐的任务,因此,这里有一个迷你脚本来获取此类节点的列表:

ns=my-namespace
pod_template=my-pod
kubectl get node | grep -v \"$(kubectl -n ${ns} get pod --all-namespaces -o wide | fgrep ${pod_template} | awk '{print $8}' | xargs -n 1 echo -n "\|" | sed 's/[[:space:]]*//g')\"

6. This is how you can use kubectl top to get a list of pods that eat up CPU and memory resources:

6.这是使用kubectl top来获取消耗CPU和内存资源的Pod列表的方式:

# cpu
kubectl top pods -A | sort --reverse --key 3 --numeric
# memory
kubectl top pods -A | sort --reverse --key 4 --numeric

7. Sorting the list of pods (in this case, by the number of restarts):

7.对Pod列表排序(在这种情况下,按重新启动次数排序):

kubectl get pods --sort-by=.status.containerStatuses[0].restartCount
Image for post

Of course, you can sort them by other fields, too (see PodStatus and ContainerStatus for details).

当然,您也可以按其他字段对它们进行排序( 有关详细信息请参见 PodStatus ContainerStatus )

获取其他数据 (Getting other data)

1. When tuning the Ingress resource, we inevitably go down to the service itself and then search for pods based on its selector. I used to look for this selector in the service manifest, but later switched to the -o wide flag:

1.调整Ingress资源时,我们不可避免地要转到服务本身,然后根据其选择器搜索pod。 我曾经在服务清单中查找此选择器,但后来切换到-o wide标志:

kubectl -n jaeger get svc -o wide
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTORjaeger-cassandra ClusterIP None <none> 9042/TCP 77d app=cassandracluster,cassandracluster=jaeger-cassandra,cluster=jaeger-cassandra

As you can see, in this case, we get the selector used by our service to find the appropriate pods.

如您所见,在这种情况下,我们获得了服务使用的选择器来查找适当的Pod。

2. Here is how you can easily print limits and requests of each pod:

2.以下是您可以轻松打印每个吊舱的限制要求的方法:

kubectl get pods -n my-namespace -o=custom-columns='NAME:spec.containers[*].name,MEMREQ:spec.containers[*].resources.requests.memory,MEMLIM:spec.containers[*].resources.limits.memory,CPUREQ:spec.containers[*].resources.requests.cpu,CPULIM:spec.containers[*].resources.limits.cpu'
Image for post

3. The kubectl run command (as well as create, apply, patch) has a great feature that allows you to see the expected changes without actually applying them — the --dry-run flag. When it is used with -o yaml, this command outputs the manifest of the required object. For example:

3. kubectl run命令(以及createapplypatch )具有一项出色的功能,允许您无需实际应用即可看到预期的更改— --dry-run标志。 与-o yaml一起使用时,此命令输出所需对象的清单。 例如:

kubectl run test --image=grafana/grafana --dry-run -o yamlapiVersion: apps/v1
kind: Deployment
metadata:
creationTimestamp: null
labels:
run: test
name: test
spec:
replicas: 1
selector:
matchLabels:
run: test
strategy: {}
template:
metadata:
creationTimestamp: null
labels:
run: test
spec:
containers:
- image: grafana/grafana
name: test
resources: {}
status: {}

All you have to do now is to save it to a file, delete a couple of system/unnecessary fields, et voila.

现在您要做的就是将其保存到文件中,删除几个系统/不必要的字段,等等。

NB: Please note that the kubectl run behavior has been changed in Kubernetes v1.18 (now, it generates Pods instead of Deployments). You can find a great summary on this issue here.

注意 :请注意, kubectl run 行为在Kubernetes v1.18中已更改(现在,它生成Pod而不是Deployments)。 您可以在 这里 找到有关此问题的精彩摘要

4. Getting a description of the manifest of a given resource:

4.获取对给定资源清单的描述:

kubectl explain hpaKIND:     HorizontalPodAutoscaler
VERSION: autoscaling/v1DESCRIPTION:
configuration of a horizontal pod autoscaler.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/api-conventions.md#resourceskind <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/api-conventions.md#types-kindsmetadata <Object>
Standard object metadata. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#metadataspec <Object>
behaviour of autoscaler. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status.status <Object>
current information about the autoscaler.

Well, that is a piece of extensive and very helpful information, I must say.

好吧,我必须说,这是一条广泛而非常有用的信息。

联网 (Networking)

1. Here is how you can get internal IP addresses of cluster nodes:

1.以下是获取群集节点的内部IP地址的方法:

kubectl get nodes -o json | \
jq -r '.items[].status.addresses[]? | select (.type == "InternalIP") | .address' | \
paste -sd "\n" -
Image for post

2. And this way, you can print all services and their respective nodePorts:

2.这样,您可以打印所有服务及其各自的nodePort:

kubectl get --all-namespaces svc -o json | \
jq -r '.items[] | [.metadata.name,([.spec.ports[].nodePort | tostring ] | join("|"))]| @tsv'

3. In situations where there are problems with the CNI (for example, with Flannel), you have to check the routes to identify the problem pod. Pod subnets that are used in the cluster can be very helpful in this task:

3.在CNI(例如Flannel)存在问题的情况下,您必须检查路由以识别问题窗格。 群集中使用的Pod子网在此任务中可能会非常有帮助:

kubectl get nodes -o jsonpath='{.items[*].spec.podCIDR}' | tr " " "\n"
Image for post

日志 (Logs)

1. Print logs with a human-readable timestamp (if it is not set):

1.打印带有人类可读时间戳的日志(如果未设置):

kubectl -n my-namespace logs -f my-pod --timestamps2020-07-08T14:01:59.581788788Z fail: Microsoft.EntityFrameworkCore.Query[10100]

Logs look so much better now, don’t they?

日志现在看起来好多了,不是吗?

2. You do not have to wait until the entire log of the pod’s container is printed out — just use --tail:

2.您不必等到豆荚容器的整个日志打印出来—只需使用--tail

kubectl -n my-namespace logs -f my-pod --tail=50

3. Here is how you can print all the logs from all containers of a pod:

3.您可以通过以下方式从容器的所有容器中打印所有日志:

kubectl -n my-namespace logs -f my-pod --all-containers

4. Getting logs from all pods using a label to filter:

4.使用标签过滤从所有窗格中获取日志:

kubectl -n my-namespace logs -f -l app=nginx

5. Getting logs of the “previous” container (for example, if it has crashed):

5.获取“上一个”容器的日志(例如,如果它已崩溃):

kubectl -n my-namespace logs my-pod --previous

其他快速动作 (Other quick actions)

1. Here is how you can quickly copy secrets from one namespace to another:

1.以下是如何将机密从一个名称空间快速复制到另一名称空间的方法:

kubectl get secrets -o json --namespace namespace-old | \
jq '.items[].metadata.namespace = "namespace-new"' | \
kubectl create-f -

2. Run these two commands to create a self-signed certificate for testing:

2.运行以下两个命令以创建用于测试的自签名证书:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout tls.key -out tls.crt -subj "/CN=grafana.mysite.ru/O=MyOrganization"
kubectl -n myapp create secret tls selfsecret --key tls.key --cert tls.crt

关于该主题的有用链接 (Helpful links on the topic)

In lieu of conclusion — here is a small list of similar publications and cheat sheets’ collections we’ve found online:

取而代之,这里是我们在网上找到的一小部分类似出版物和备忘单的收藏:

Image for post

This article has been written by our engineer Sergey Sizov. Follow our blog to get new excellent content from Flant!

本文由我们的工程师 Sergey Sizov撰写 跟随 我们的博客 ,从Flant获得新的优秀内容!

翻译自: https://medium.com/flant-com/kubectl-commands-and-tips-7b33de0c5476

kubectl命令

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值