Docker 与 K8S学习笔记(二十二)—— 高效使用kubectl的小技巧

本文涉及的产品
容器服务 Serverless 版 ACK Serverless,317元额度 多规格
容器服务 Serverless 版 ACK Serverless,952元额度 多规格
日志服务 SLS,月写入数据量 50GB 1个月
简介: kubectl作为我们主要的操作K8S的工具,其具备非常丰富的功能,但是如果不经过打磨,使用起来还是存在诸多不便,今天我们来看看如何将我们的kubectl打磨的更加易用。 一、命令自动补全 kubectl中提供非常多的命令,如果每一次都要手动一个字符一个字符的敲未免太累了,那么如何配置自动补全呢?这


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)

 

分类: 容器技术

相关实践学习
通过Ingress进行灰度发布
本场景您将运行一个简单的应用,部署一个新的应用用于新的发布,并通过Ingress能力实现灰度发布。
容器应用与集群管理
欢迎来到《容器应用与集群管理》课程,本课程是“云原生容器Clouder认证“系列中的第二阶段。课程将向您介绍与容器集群相关的概念和技术,这些概念和技术可以帮助您了解阿里云容器服务ACK/ACK Serverless的使用。同时,本课程也会向您介绍可以采取的工具、方法和可操作步骤,以帮助您了解如何基于容器服务ACK Serverless构建和管理企业级应用。 学习完本课程后,您将能够: 掌握容器集群、容器编排的基本概念 掌握Kubernetes的基础概念及核心思想 掌握阿里云容器服务ACK/ACK Serverless概念及使用方法 基于容器服务ACK Serverless搭建和管理企业级网站应用
相关文章
|
11天前
|
Kubernetes Java Docker
利用(K8S)配合Docker部署jar包
通过Docker打包并部署到Kubernetes(K8S)集群的过程。首先,通过SpringBoot生成jar包,接着在K8S环境中创建并编辑Dockerfile文件。随后构建Docker镜像,并将其推送到镜像仓库。最后,通过一系列kubectl命令(如get pods、get svc、logs等),展示了如何在K8S中管理应用,包括查看Pod状态、服务信息、Pod日志以及重启Pod等操作。
59 2
|
9天前
|
Ubuntu Linux pouch
Docker容器管理工具
文章介绍了Docker容器管理工具,以及早期使用的LXC容器管理工具,包括它们的安装、使用和相关技术特点。
38 10
Docker容器管理工具
|
6天前
|
Cloud Native 持续交付 Docker
云原生技术实践:Docker容器化部署教程
【9月更文挑战第4天】本文将引导你了解如何利用Docker这一云原生技术的核心工具,实现应用的容器化部署。文章不仅提供了详细的步骤和代码示例,还深入探讨了云原生技术背后的哲学,帮助你理解为何容器化在现代软件开发中变得如此重要,并指导你如何在实际操作中运用这些知识。
|
11天前
|
Kubernetes Cloud Native 开发者
探索云原生技术:从Docker到Kubernetes的旅程
【8月更文挑战第31天】云原生技术正在改变软件开发、部署和运维的方式。本文将带你了解云原生的核心概念,并通过实际代码示例,展示如何使用Docker容器化应用,并进一步通过Kubernetes进行集群管理。我们将一起构建一个简单的微服务架构,体验云原生带来的高效与便捷。
|
11天前
|
Kubernetes Cloud Native 云计算
云原生入门:从Docker到Kubernetes的旅程
【8月更文挑战第31天】 在数字化转型的浪潮中,云原生技术成为推动现代软件开发的关键力量。本文将引导读者理解云原生的基本概念,通过Docker和Kubernetes的实际应用示例,展示如何在云平台上部署和管理容器化应用。我们将一起探索服务编排、持续集成和微服务架构的实践之路,旨在为初学者揭开云原生技术的神秘面纱,并激发对这一前沿领域的深入探索。
|
11天前
|
运维 Kubernetes Cloud Native
云原生技术入门:Kubernetes和Docker的协同工作
【8月更文挑战第31天】 在云原生的世界里,容器技术是基石。本文将带你了解如何通过Kubernetes和Docker这两个强大的工具,搭建起你的云原生应用架构。我们将一起探索它们如何相互配合,提升开发与运维的效率。准备好了吗?让我们启航,探索云原生的奥秘!
|
11天前
|
Kubernetes Cloud Native 开发者
云原生入门:从Docker到Kubernetes的旅程
【8月更文挑战第31天】在数字化浪潮中,云原生技术如同一艘航向未来的船,承载着企业转型的梦想。本文将带领读者从Docker容器的基础出发,一路驶向Kubernetes的广阔海域。通过浅显易懂的语言和实用的代码示例,我们将探索云原生的核心概念、架构设计以及如何在实际项目中应用这些技术。无论你是初学者还是有一定经验的开发者,这篇文章都将为你提供一次宝贵的学习之旅。让我们一起启航,发现云原生的魅力!
|
Kubernetes 负载均衡 Linux
Docker从入门到掉坑(四) 国内搭建k8s避坑指南
Docker从入门到掉坑(四) 国内搭建k8s避坑指南
411 0
|
存储 JSON Kubernetes
Docker从入门到掉坑(五):继续挖一挖 k8s
Docker从入门到掉坑(五):继续挖一挖 k8s
Docker从入门到掉坑(五):继续挖一挖 k8s
|
Kubernetes 负载均衡 Linux
Docker从入门到掉坑(四):上手k8s避坑指南
Docker从入门到掉坑(四):上手k8s避坑指南
Docker从入门到掉坑(四):上手k8s避坑指南