kubectl作为我们主要的操作K8S的工具,其具备非常丰富的功能,但是如果不经过打磨,使用起来还是存在诸多不便,今天我们来看看如何将我们的kubectl打磨的更加易用。

一、命令自动补全

kubectl中提供非常多的命令,如果每一次都要手动一个字符一个字符的敲未免太累了,那么如何配置自动补全呢?这里以ubuntu系统为例:

1、安装auto-completion工具

$ sudo apt update
Hit:1 http://archive.ubuntu.com/ubuntu bionic InRelease
Hit:2 http://security.ubuntu.com/ubuntu bionic-security InRelease
Hit:3 http://archive.ubuntu.com/ubuntu bionic-updates InRelease
Hit:4 https://download.docker.com/linux/ubuntu bionic InRelease
Hit:5 http://archive.ubuntu.com/ubuntu bionic-backports InRelease
Reading package lists... Done
Building dependency tree
Reading state information... Done
144 packages can be upgraded. Run 'apt list --upgradable' to see them.
$ sudo apt install bash-completion
Reading package lists... Done
Building dependency tree
Reading state information... Done
bash-completion is already the newest version (1:2.8-1ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 144 not upgraded.

PS:如果是centos系统,则使用yum install bash-completion -y命令安装

2、配置自动补全

Bash

source <(kubectl completion bash)
echo "source <(kubectl completion bash)" >> ~/.bashrc

Zsh

source <(kubectl completion zsh)
echo "[[ $commands[kubectl] ]] && source <(kubectl completion zsh)" >> ~/.zshrc

配置后就可以通过Tab键自动补全命令啦!

二、配置kubectl别名

我们可以通过设置别名简化kubectl命令,编辑.bashrc文件,添加如下内容:

alias sudo='sudo '
alias k='kubectl'
alias ka='kubectl apply --recursive -f'
alias kex='kubectl exec -i -t'
alias klo='kubectl logs -f'
alias kg='kubectl get'
alias kd='kubectl describe'

PS:alias sudo是为了解决sudo下别名不可用问题

保存后记得执行 source ~/.bashrc哈,接着我们体验下:

$ sudo ka webapp_pod.yaml
pod/webapp created
$ sudo kg pods
NAME READY STATUS RESTARTS AGE
webapp 0/2 ContainerCreating 0 7s
$ sudo kd pod webapp
Name: webapp
Namespace: default
Priority: 0
Node: ayato/172.16.194.135
Start Time: Wed, 09 Feb 2022 14:04:44 +0000
Labels: app=webapp
Annotations: <none>
Status: Running
IP: 172.17.0.6
IPs:
IP: 172.17.0.6
Containers:
webapp:
Container ID: docker://d9ddf9dd47de12b53f2119bf75df6706bee2e7711509638ad52adc9addeda704
Image: 172.16.194.135:5000/webapp:1.0
Image ID: docker-pullable://172.16.194.135:5000/webapp@sha256:df3a447a013ada0642dec67bb31976f42f1a0699a68873d0452f514fa24e5c77
Port: 5000/TCP
Host Port: 0/TCP
State: Running
Started: Wed, 09 Feb 2022 14:04:46 +0000
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/tmp from webapp-logs (rw)
/var/run/secrets/kubernetes.io/serviceaccount from default-token-pcr2h (ro)
busybox:
Container ID: docker://6a6a35a628a782fc643af3dd49986bbc77c23de1ae4726bc521c77f61abbbf5d
Image: busybox
Image ID: docker-pullable://busybox@sha256:afcc7f1ac1b49db317a7196c902e61c6c3c4607d63599ee1a82d702d249a0ccb
Port: <none>
Host Port: <none>
Command:
sh
-c
tail -f /logs/log.out
State: Running
Started: Wed, 09 Feb 2022 14:06:53 +0000
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/logs from webapp-logs (rw)
/var/run/secrets/kubernetes.io/serviceaccount from default-token-pcr2h (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
webapp-logs:
Type: EmptyDir (a temporary directory that shares a pod's lifetime)
Medium:
SizeLimit: <unset>
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 2m23s default-scheduler Successfully assigned default/webapp to ayato
Normal Pulled 2m22s kubelet Container image "172.16.194.135:5000/webapp:1.0" already present on machine
Normal Created 2m21s kubelet Created container webapp
Normal Started 2m21s kubelet Started container webapp
Normal Pulling 2m21s kubelet Pulling image "busybox"
Normal Pulled 15s kubelet Successfully pulled image "busybox" in 14.633078305s
Normal Created 15s kubelet Created container busybox
Normal Started 14s kubelet Started container busybox

真的是飞一般的感觉!!!

三、Context和Namespace切换

我们在公司的容器平台上使用kubectl时,经常需要切换context和namespace,导致命令非常繁琐,那有没有简便的方式呢?—— kubectx

kubectx安装

$ sudo git clone https://github.com/ahmetb/kubectx /opt/kubectx
Cloning into '/opt/kubectx'...
remote: Enumerating objects: 1457, done.
remote: Counting objects: 100% (172/172), done.
remote: Compressing objects: 100% (115/115), done.
remote: Total 1457 (delta 85), reused 97 (delta 51), pack-reused 1285
Receiving objects: 100% (1457/1457), 905.30 KiB | 69.00 KiB/s, done.
Resolving deltas: 100% (817/817), done.
$ sudo ln -s /opt/kubectx/kubens /usr/local/bin/kubectl-ns
$ sudo ln -s /opt/kubectx/kubectx /usr/local/bin/kubectl-ctx

我们来看一下效果:

$ sudo k ctx
minikube
$ sudo k ctx minikube
Switched to context "minikube".
$ sudo k ns
default
kube-node-lease
kube-public
kube-system
kubernetes-dashboard
$ sudo k ns kube-public
Context "minikube" modified.
Active namespace is "kube-public".
$ sudo k ns default
Context "minikube" modified.
Active namespace is "default".

四、跟踪查看多个Pod的日志

我们一般使用kubectl logs命令查看Pod日志,但是它不能通过-f参数同时跟踪查看多个Pod日志,这就不方便了,毕竟实际生产环境中每个服务都会有多个Pod,这时我们可以使用stern这个工具,它具备如下能力:

  • 允许使用正则表达式来选择需要查看的PodName

  • 为不同 Pod 的日志展示不同的颜色

  • 跟踪日志过程中假如有符合规则的新 Pod 被创建, 那么会自动添加到输出中

首先安装stern(下载stern时可能较慢可以多试几次):

wget https://github.com/wercker/stern/releases/download/1.11.0/stern_linux_amd64
sudo mv stern_linux_amd64 /usr/local/bin/kubectl-tail
sudo chomd +x /usr/local/bin/kubectl-tail

安装完毕后让我一起感受一下stern的魅力吧,我的Pod里面有两个容器:webapp和busybox,如果使用kubectl logs 还得指定具体的容器,而使用stern就没有这样的限制。

$ sudo k tail .
+ webapp › busybox
+ webapp › webapp
webapp busybox 14:04:53.197 [INFO ] [main] [org.apache.coyote.http11.Http11NioProtocol] Initializing ProtocolHandler ["http-nio-4567"]
webapp busybox 14:04:53.200 [INFO ] [main] [org.apache.catalina.core.StandardService] Starting service [Tomcat]
webapp busybox 14:04:53.201 [INFO ] [main] [org.apache.catalina.core.StandardEngine] Starting Servlet engine: [Apache Tomcat/9.0.41]
webapp busybox 14:04:53.324 [INFO ] [main] [org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/]] Initializing Spring embedded WebApplicationContext
webapp busybox 14:04:53.325 [INFO ] [main] [org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext] Root WebApplicationContext: initialization completed in 2952 ms
webapp busybox 14:04:53.801 [INFO ] [main] [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor] Initializing ExecutorService 'applicationTaskExecutor'
webapp busybox 14:04:54.264 [WARN ] [main] [org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$DefaultTemplateResolverConfiguration] Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
webapp busybox 14:04:54.377 [INFO ] [main] [org.apache.coyote.http11.Http11NioProtocol] Starting ProtocolHandler ["http-nio-4567"]
webapp busybox 14:04:54.481 [INFO ] [main] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] Tomcat started on port(s): 4567 (http) with context path ''
webapp busybox 14:04:54.509 [INFO ] [main] [org.demo.webapp.todolist.TodoListApplication] Started TodoListApplication in 6.235 seconds (JVM running for 8.074)
webapp webapp
webapp webapp . ____ _ __ _ _
webapp webapp /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
webapp webapp ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
webapp webapp \\/ ___)| |_)| | | | | || (_| | ) ) ) )
webapp webapp ' |____| .__|_| |_|_| |_\__, | / / / /
webapp webapp =========|_|==============|___/=/_/_/_/
webapp webapp :: Spring Boot :: (v2.4.2)
webapp webapp
webapp webapp 14:04:50.124 [INFO ] [main] [org.demo.webapp.todolist.TodoListApplication] Starting TodoListApplication v1.0-SNAPSHOT using Java 1.8.0_111 on webapp with PID 1 (/opt/soft/webapp.jar started by root in /opt/soft)
webapp webapp 14:04:50.165 [INFO ] [main] [org.demo.webapp.todolist.TodoListApplication] No active profile set, falling back to default profiles: default
webapp webapp 14:04:53.158 [INFO ] [main] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] Tomcat initialized with port(s): 4567 (http)
webapp webapp 14:04:53.197 [INFO ] [main] [org.apache.coyote.http11.Http11NioProtocol] Initializing ProtocolHandler ["http-nio-4567"]
webapp webapp 14:04:53.200 [INFO ] [main] [org.apache.catalina.core.StandardService] Starting service [Tomcat]
webapp webapp 14:04:53.201 [INFO ] [main] [org.apache.catalina.core.StandardEngine] Starting Servlet engine: [Apache Tomcat/9.0.41]
webapp webapp 14:04:53.324 [INFO ] [main] [org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/]] Initializing Spring embedded WebApplicationContext
webapp webapp 14:04:53.325 [INFO ] [main] [org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext] Root WebApplicationContext: initialization completed in 2952 ms
webapp webapp 14:04:53.801 [INFO ] [main] [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor] Initializing ExecutorService 'applicationTaskExecutor'
webapp webapp 14:04:54.264 [WARN ] [main] [org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$DefaultTemplateResolverConfiguration] Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
webapp webapp 14:04:54.377 [INFO ] [main] [org.apache.coyote.http11.Http11NioProtocol] Starting ProtocolHandler ["http-nio-4567"]
webapp webapp 14:04:54.481 [INFO ] [main] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] Tomcat started on port(s): 4567 (http) with context path ''
webapp webapp 14:04:54.509 [INFO ] [main] [org.demo.webapp.todolist.TodoListApplication] Started TodoListApplication in 6.235 seconds (JVM running for 8.074)

Docker 与 K8S学习笔记(二十二)—— 高效使用kubectl的小技巧的更多相关文章

  1. Docker 与 K8S学习笔记(十 二)容器间数据共享

    数据共享是volume的关键特性,今天我们来看一下通过volume实现容器与host.容器与容器之间共享数据. 一.容器与host共享数据 在上一篇中介绍到的bind mount和docker man ...

  2. Docker 与 K8S学习笔记(十八)—— Pod的使用

    Pod 是一组紧密关联的容器集合,它们共享IPC.Network和UTS namespace,是 Kubernetes 调度的基本单元.Pod 的设计理念是支持多个容器在一个 Pod 中共享网络和文件 ...

  3. Docker 与 K8S学习笔记(十九)—— Pod的配置管理

    我们在部署应用时常常会考虑将应用程序与配置文件相分离,这样可以使应用程序更好的复用,并且通过不同配置也能实现更灵活的功能.将应用制作成镜像后,我们可以在启动容器时通过环境变量或挂载文件的方式注入,但是 ...

  4. Docker 与 K8S学习笔记(十)—— 容器的端口映射

    我们一般将应用部署在容器里面,而一个服务器上会有许许多多的容器,那么外界该如何访问我们的应用呢?答案是:端口映射. Docker可以将容器对外提供服务的端口映射到host的某个端口上,外网通过此端口访 ...

  5. VSTO 学习笔记(十二)自定义公式与Ribbon

    原文:VSTO 学习笔记(十二)自定义公式与Ribbon 这几天工作中在开发一个Excel插件,包含自定义公式,根据条件从数据库中查询结果.这次我们来做一个简单的测试,达到类似的目的. 即在Excel ...

  6. 汇编入门学习笔记 (十二)—— int指令、port

    疯狂的暑假学习之  汇编入门学习笔记 (十二)--  int指令.port 參考: <汇编语言> 王爽 第13.14章 一.int指令 1. int指令引发的中断 int n指令,相当于引 ...

  7. Binder学习笔记(十二)—— binder_transaction(...)都干了什么?

    binder_open(...)都干了什么? 在回答binder_transaction(...)之前,还有一些基础设施要去探究,比如binder_open(...),binder_mmap(...) ...

  8. java之jvm学习笔记六-十二(实践写自己的安全管理器)(jar包的代码认证和签名) (实践对jar包的代码签名) (策略文件)(策略和保护域) (访问控制器) (访问控制器的栈校验机制) (jvm基本结构)

    java之jvm学习笔记六(实践写自己的安全管理器) 安全管理器SecurityManager里设计的内容实在是非常的庞大,它的核心方法就是checkPerssiom这个方法里又调用 AccessCo ...

  9. Android学习笔记(十二)——实战:制作一个聊天界面

    //此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! 运用简单的布局知识,我们可以来尝试制作一个聊天界面. 一.制作 Nine-Patch 图片 : Nine-Pa ...

  10. MySQL数据库学习笔记(十二)----开源工具DbUtils的使用(数据库的增删改查)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

随机推荐

  1. .net core中Grpc使用报错:The response ended prematurely.

    当我们调用Grpc是出现下面的一堆异常时,一般是由于LTS导致的: Call failed with gRPC error status. Status code: 'Unavailable', Me ...

  2. PHP-FPM 开启慢日志记录

    首先,找到 php-fpm 所在的目录: 使用 which php-fpm 使用 whereis php-fpm 然后找到 php-fpm.conf 所在的目录: 使用 ps -ef | grep p ...

  3. 为什么要避免在 Go 中使用 ioutil.ReadAll?

    原文链接: 为什么要避免在 Go 中使用 ioutil.ReadAll? ioutil.ReadAll 主要的作用是从一个 io.Reader 中读取所有数据,直到结尾. 在 GitHub 上搜索 i ...

  4. Snack3 3.2 发布,轻量的Json+Jsonpath框架

    Snack3 是一个轻量的 JSON + Jsonpath 框架. 借鉴了 Javascript 所有变量由 var 申明,及 Xml dom 一切都是 Node 的设计.其下一切数据都以ONode表 ...

  5. linux 查看历史命令 history命令

    1.history命令 "history"命令就是历史记录.它显示了在终端中所执行过的所有命令的历史. history //显示终端执行过的命令 history 10 //显示最近 ...

  6. react中关于create-react-app2里css相关配置

    先看 webpack.config.dev.js 里的相关代码: // style files regexes const cssRegex = /\.css$/; const cssModuleRe ...

  7. 利用js模拟用户的cookie信息保存

    注:图片如果损坏,点击文章链接:https://www.toutiao.com/i6814761849708347907/ 默认已完成爬虫文档<爬虫学习文档顺序> 并简单搭建完展示页面和管 ...

  8. 解决excel两表之间数据关联关系,知道这几招就够了

    用过SAP的凭证批量录入模板(Excel文件)的都知道,一个凭证由[抬头]和多个[行项目]组成,这是一个关于excel两表信息关联的典型场景. 这里头蕴藏着一个麻烦:当我们需要一次性录入多个凭证时,如 ...

  9. DEEP LEARNING WITH PYTORCH: A 60 MINUTE BLITZ | TENSORS

    Tensor是一种特殊的数据结构,非常类似于数组和矩阵.在PyTorch中,我们使用tensor编码模型的输入和输出,以及模型的参数. Tensor类似于Numpy的数组,除了tensor可以在GPU ...

  10. CAS学习笔记五:SpringBoot自动/手动配置方式集成CAS单点登出

    本文目标 基于SpringBoot + Maven 分别使用自动配置与手动配置过滤器方式实现CAS客户端登出及单点登出. 本文基于<CAS学习笔记三:SpringBoot自动/手动配置方式集成C ...