Kubernetes

kubernetes基础介绍及kubectl常用命令

本文主要是介绍kubernetes基础介绍及kubectl常用命令,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

  • kubernetes基础介绍及kubectl常用命令
    • k8s的pod分类
      • 自主式pod
      • 控制器管理的pod
    • 核心主键
      • HPA
      • service
    • 网络模型
      • 同节点Pod之间的通信
      • 不同节点上的Pod通信
      • Pod与Service
    • kubectl常用命令
      • create
      • run
      • delete
      • get
      • expose
      • edit
      • scale
      • autoscale
      • cluster-info
      • describe
      • logs
      • attach
      • exec
      • port-forward
      • cp
      • label
      • api-resources
      • api-versions
    • k8s进行版本的滚动更新及回滚

kubernetes基础介绍及kubectl常用命令

k8s的pod分类

pod分为两类:

  • 自主式pod
  • 控制器管理的pod

自主式pod由k8s管理器进行管理,而static pod由kubelet进行创建与管理

自主式pod

自主式pod总是在前台运行,同时接受k8s管理与调度,当集群当中的pod因为某种原因停止,k8s会根据其副本的数量,重新的生成对应的pod

自我管理的pod,创建以后仍然需要提交给apiserver,由apiserver接收以后借助于调度器将其调度至指定的node节点,由node启动此pod

如果此pod出现故障,需要重启容器则由kubelet来完成
如果node节点故障了,那么此pod将会消失。其无法实现全局调度。所以不推荐使用此种pod

控制器管理的pod

常见的pod控制器:

  • ReplicationController:当启动一个pod时。这个pod如果不够用可以再启个副本,而后由控制器来管理同一类pod的各种副本与对象。一旦副本少了就会自动增加。采取多退少补的规则,精确符合我们所定义的期望。支持滚动更新

  • ReplicaSet:由一个名叫Deployment的声明式更新的控制器来管理

  • Deployment:Deployment只能管理无状态的应用

  • StateFulSet:有状态副本集,可以管理有状态的应用

  • DaemonSet:如果需要在每个node上运行一个副本的时候可以用DaemonSet

核心主键

HPA

Deployment还支持二级控制器,HPA(HorizontalPodAutoscaler,水平pod自动伸缩控制器),一般情况下我们可以确保一个node上有2个pod在运行,万一用户访问流量增加,2个pod不足以承载这么多访问量怎么办?此时我们就应该要增加pod资源,那么到底应该加几个?

HPA控制器可自动监控pod、自动进行扩展。

service

假如有2个pod,pod有其生命周期,万一pod所在的节点宕机了,那么此pod将应该要在其他的节点上重建,而重建完的pod与原来的pod已经不是同一个pod了,只是两者都是运行的同一个服务而已。且每个容器都有其IP地址,重建的pod中的容器其IP地址与之前的pod中容器的IP地址是不一样的,如此一来就会存在一个问题,客户端如何访问这些pod中的容器呢?(会转换到另一个节点去运行)

用于做服务发现,pod是有生命周期的,一个pod随时都有可能离去,随时都有可能会有其他内pod加进来,假如它们提供的是同一种服务,客户端是无法通过固定的手段来访问这些pod的,因为pod本身是不固定的,它们随时可能被替换掉,无论使用主机名还是IP地址,都随时会被替换掉。

为了尽可能的降低客户端与pod间协调的复杂度,k8s为每一组提供同类服务的pod和其客户端之间添加了一个中间层,这个中间层是固定的,这个中间层就叫service。

service只要不被删除,其地址与名称皆是固定的,当客户端需要在其配置文件中写上访问某个服务时,它不再需要自动发现,只需要在配置文件中写明service的名称即可,而这个service是个调度器,其不但能够提供一个稳定的访问入口,还可以做反向代理,当service接收到客户端的请求后,会将其代理到后端的pod之上,一旦pod宕机了会立即新建一个pod,这个新建的pod会立即被service关联上,作为service后端的可用pod之一

客户端程序访问服务都是通过IP+端口或者主机名+端口的方式来实现的。而service关联后端的pod不是靠它的IP和主机名,而是靠pod的标签选择器。只要创建的pod的label是统一的,无论IP地址和主机如何改变,其都能被service所识别。如此一来,只要pod属于标签选择器,只要其在service的管理范围之内,则其就会被关联到service中,当这个动态的pod关联到service中之后,再进行动态的探测此pod的IP地址、端口,再将其作为自己后端可调度的可用服务蒂王机为象。因此,客户端的请求发送到service,然后由service代理到后端真实的pod中的容器进行响应。

service不是一个程序,也不是一个组件,它只是一个iptables的dnat规则,service作为k8s的对象,有其自身的名称,而service的名称相当于服务的名称,而这个名称可以被解析。

AddOns附件

dns pod:装完k8s后第一件事就需要在k8s集群上部署一个dns pod,以确保各service的名称能够被解析可以动态改变,包括动态创建、动态删除、动态修改,比如把service的名称改了,dnspod会自动触发,将dns解析记录中的名称也给改掉;假如我们手动把service的ip地址给改了,改完以后会自动触发,将dns服务中的解析记录给改掉。如此一来,客户端去访问pod资源的时候可以直接访问service的名称,然后由集群中专用的dns服务来负责解析。

这种pod是k8s自身的服务就需要用到的pod,所以我们把它称为基础性的系统架构级的pod对象,而且它们也被称为集群附件

网络模型

三种网络模型

  • 节点网络
  • service集群网络
  • pod网络

同节点Pod之间的通信

在容器启动前,会为容器创建一个虚拟Ethernet接口对,这个接口对类似于管道的两端,其中一端在主机命名空间中,另外一端在容器命名空间中,并命名为eth0。在主机命名空间的接口会绑定到网桥。网桥的地址段会取IP赋值给容器的eth0接口。

不同节点上的Pod通信

我们已经知道一个节点上的容器都会连接到同一网桥,因此要让运行在不同节点上的容器之间能够通信,这些节点的网桥就需要以某种方式连接起来。
跨整个集群的Pod的IP地址必须是唯一的,所有跨节点的网桥必须使用不重叠的网络地址段,以防止不同节点上的Pod拿到同一IP地址,即确保没有IP地址冲突。

发送到B节点上的容器时,报文会先通过veth接口对到网桥,再由网桥到A节点的物理适配器,再通过网线传输到B节点的物理适配器,再通过B的网桥,经过接口对到达目标容器。

注意:上述情形仅在节点连接到相同网关,之间没有任何路由设备时有效。否则,路由设备会因为IP私有产生丢包现象,除非设置路由规则。但随着节点的增加,路由的配置会变得非常困难。因此我们使用SDN(软件定义网络)技术来简化此类问题,SDN可以忽略底层网络拓扑,使其就像连接到同一网关。

Pod与Service

在不同节点上的Pod通信中,我们知道了Pod是以IP地址进行通信,但Kubernetes 的集群中, Pod 可能会频繁的销毁和创建,也就是说 Pod 的 IP 不是固定的。
为了解决这个问题,Service 提供了访问 Pod 的抽象层,即为一组功能相同的Pod提供单一不变的接入点资源。
无论后端的 Pod 如何变化,Service 都作为稳定的前端对外提供服务。
同时,Service 还提供了高可用和负载均衡功能,Service 负责将请求转发给正确的 Pod。

kubectl常用命令

语法

kubectl [command] [TYPE] [NAME] [flags]

command:子命令
TYPE:资源类型
NAME:资源名称
flags:命令参数

命令帮助
kubectl命令的帮助很详细,kubectl -h会列出所有的子命令,在任何子命令后跟 -h,都会输出详细的帮助以及用例,遇到问题可以随时查看帮助。

资源对象
kubectl大部分子命令后都可以指定要操作的资源对象,可以用kubectl api-resources命令参考

全局参数
kubectl options命令可以列出可以全局使用的命令参数
--cluster='': 指定命令操作对象的集群
--context='':  指定命令操作对象的上下文
-n, --namespace='': 指定命令操作对象的Namespace

create

从文件或标准输出中创建pod

# 创建一个deployment类型的pos,名字是nginx1,使用的镜像是nginx
[root@master ~]# kubectl create deployment wb1 --image=nginx
deployment.apps/wb1 created
[root@master ~]# kubectl create deployment nginx1 --image=nginx
deployment.apps/nginx1 created
[root@master ~]# kubectl get pods
NAME                      READY   STATUS    RESTARTS   AGE
nginx1-5c9f6bbd8c-2ng6h   1/1     Running   0          40s

# 创建deployment类型的pos,名字是nginx2,使用的镜像是nginx,replicas是指定创建的个数
[root@master ~]# kubectl create deployment nginx2 --image=nginx --replicas=2
deployment.apps/nginx2 created
[root@master ~]# kubectl get pods
NAME                      READY   STATUS              RESTARTS   AGE
nginx1-5c9f6bbd8c-2ng6h   1/1     Running             0          3m2s
nginx2-85bf7b8976-68q5d   0/1     ContainerCreating   0          42s
nginx2-85bf7b8976-74l6z   1/1     Running             0          42s

run

在集群中运行一个指定的镜像的pod(自主式pod)

# 使用run运行的pod默认为pod类型
[root@master ~]# kubectl run nginx --image nginx
pod/nginx created
[root@master ~]# kubectl get pods
NAME                   READY   STATUS              RESTARTS   AGE
nginx                  0/1     ContainerCreating   0          11s

# 运行一个pod叫nginx1,使用镜像nginx,指定标签为app=web
[root@master ~]# kubectl get pods
NAME                   READY   STATUS              RESTARTS   AGE
nginx                  0/1     ContainerCreating   0          11s
wb1-5dbfb96758-hhfhb   1/1     Running             0          16m
[root@master ~]# kubectl run nginx1 --image=nginx --labels="app=web"
pod/nginx1 created
[root@master ~]# kubectl get pods
NAME                   READY   STATUS    RESTARTS   AGE
nginx                  1/1     Running   0          2m9s
nginx1                 1/1     Running   0          18s

# 多创建几个,使它们的标签都是nginx
[root@master ~]# kubectl run nginx2 --image=nginx --labels="app=web"
pod/nginx2 created
[root@master ~]# kubectl run nginx3 --image=nginx --labels="app=web"
pod/nginx3 created
#查看一下
[root@master ~]# kubectl get pods
NAME                   READY   STATUS    RESTARTS   AGE
nginx                  1/1     Running   0          5m49s
nginx1                 1/1     Running   0          3m58s
nginx2                 1/1     Running   0          73s
nginx3                 1/1     Running   0          43s
# 删除时指定标签就可以删除对应标签的pod
[root@master ~]# kubectl delete pod -l app=web
pod "nginx1" deleted
pod "nginx2" deleted
pod "nginx3" deleted

#试运行,不会真正的创建运行,可以指定client/server端跑
[root@master ~]# kubectl run web123 --image=nginx --dry-run=client
pod/web123 created (dry run)

# 启动一个pod,并将其放在前台,如果它退出,不要重新启动它
[root@master ~]# kubectl run -i -t web123 --image=busybox --restart=Never
If you don't see a command prompt, try pressing enter.
/ # ls -l
total 16
drwxr-xr-x    2 root     root         12288 Dec  7 00:20 bin
drwxr-xr-x    5 root     root           380 Dec 19 10:22 dev
drwxr-xr-x    1 root     root            66 Dec 19 10:22 etc
drwxr-xr-x    2 nobody   nobody           6 Dec  7 00:20 home
dr-xr-xr-x  219 root     root             0 Dec 19 10:22 proc
drwx------    1 root     root            26 Dec 19 10:22 root
dr-xr-xr-x   13 root     root             0 Dec 19 10:21 sys
drwxrwxrwt    2 root     root             6 Dec  7 00:20 tmp
drwxr-xr-x    3 root     root            18 Dec  7 00:20 usr
drwxr-xr-x    1 root     root            17 Dec 19 10:22 var

delete

删除资源的文件名,标准输出,资源和名称,或资源和标签选择器

##查看所存在的service和pod
[root@master ~]# kubectl get pods,svc
NAME                          READY   STATUS    RESTARTS   AGE
pod/nginx-85b98978db-dgkbp    1/1     Running   0          97m
pod/nginx1-5c9f6bbd8c-2ng6h   1/1     Running   0          11m
pod/nginx2-85bf7b8976-68q5d   1/1     Running   0          9m8s
pod/nginx2-85bf7b8976-74l6z   1/1     Running   0          9m8s
pod/nginx3-59475d8756-l8mcq   1/1     Running   0          7m17s
pod/wb1-5dbfb96758-hhfhb      1/1     Running   0          11m

NAME                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
service/kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP        144m
service/nginx        NodePort    10.105.224.204   <none>        80:31753/TCP   97m
#删除service和pod名字叫nginx的
[root@master ~]# kubectl delete deployment,svc nginx
deployment.apps "nginx" deleted
service "nginx" deleted

#删除完后查看
[root@master ~]# kubectl get pods,svc
NAME                          READY   STATUS    RESTARTS   AGE
pod/nginx1-5c9f6bbd8c-2ng6h   1/1     Running   0          13m
pod/nginx2-85bf7b8976-68q5d   1/1     Running   0          10m
pod/nginx2-85bf7b8976-74l6z   1/1     Running   0          10m
pod/nginx3-59475d8756-l8mcq   1/1     Running   0          8m50s
pod/wb1-5dbfb96758-hhfhb      1/1     Running   0          13m

NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   146m
 

get

显示一个或更多资源

# 查看创建的pod
[root@master ~]# kubectl get pods
NAME                      READY   STATUS    RESTARTS   AGE
nginx-85b98978db-dgkbp    1/1     Running   0          90m
nginx1-5c9f6bbd8c-2ng6h   1/1     Running   0          5m2s
nginx2-85bf7b8976-68q5d   1/1     Running   0          2m42s
nginx2-85bf7b8976-74l6z   1/1     Running   0          2m42s
nginx3-59475d8756-l8mcq   1/1     Running   0          51s
wb1-5dbfb96758-hhfhb      1/1     Running   0          5m14s

# 查看创建的pod
[root@master ~]# kubectl get service
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP        138m
nginx        NodePort    10.105.224.204   <none>        80:31753/TCP   91m

# 查看多个信息,用","隔开
[root@master ~]# kubectl get service,pod
NAME                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
service/kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP        138m
service/nginx        NodePort    10.105.224.204   <none>        80:31753/TCP   91m

NAME                          READY   STATUS    RESTARTS   AGE
pod/nginx-85b98978db-dgkbp    1/1     Running   0          91m
pod/nginx1-5c9f6bbd8c-2ng6h   1/1     Running   0          5m52s
pod/nginx2-85bf7b8976-68q5d   1/1     Running   0          3m32s
pod/nginx2-85bf7b8976-74l6z   1/1     Running   0          3m32s
pod/nginx3-59475d8756-l8mcq   1/1     Running   0          101s
pod/wb1-5dbfb96758-hhfhb      1/1     Running   0          6m4s

# 查看名称空间
[root@master ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   139m
kube-node-lease   Active   139m
kube-public       Active   139m
kube-system       Active   139m

# 查看指定类型的pod
[root@master ~]# kubectl get deployment
NAME     READY   UP-TO-DATE   AVAILABLE   AGE
nginx    1/1     1            1           93m
nginx1   1/1     1            1           7m49s
nginx2   2/2     2            2           5m29s
nginx3   1/1     1            1           3m38s
wb1      1/1     1            1           8m1s
[root@master ~]# kubectl get deployment nginx
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   1/1     1            1           94m

expose

暴露端口号,–target-port表示暴露目标端口号

创建一个服务,这个服务在它的80端口号连接它的时候用容器的8000,用外面的80访问容器里的8000

#把80映射到8000,因为它的类型是ClusterIP,表示这个service只能在集群中能访问到;NodePort则表示是在真机上可以访问的
[root@master ~]# kubectl expose deployment myapp --port 80 --target-port 8000
service/myapp exposed
[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
myapp        ClusterIP   10.110.171.169   <none>        80/TCP         3s
nginx        NodePort    10.111.4.86      <none>        80:30859/TCP   41h

edit

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

[root@master ~]# kubectl describe pod nginx
Name:         nginx
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.235.172
Start Time:   Mon, 20 Dec 2021 22:14:38 +0800
Labels:       app=nginx
   ································          
[root@master ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx                     1/1     Running   0          87s


...
  labels:
    app: test		//将原本的nginx改为test
  name: nginx
[root@master ~]# kubectl describe pod nginx
...
Labels:       app=test

scale

扩容或缩容 Deployment、ReplicaSet、Replication Controller或 Job 中Pod数量

将名为nginx中的pod副本数量设置为3

[root@master ~]# kubectl get deployment
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   1/1     1            1           8m30s
[root@master ~]# kubectl scale --replicas 3 deployment/nginx
deployment.apps/nginx scaled
[root@master ~]# kubectl get deployment
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   1/3     3            1           8m56s
[root@master ~]# kubectl get pod
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6799fc88d8-5tsjt   1/1     Running   0          16s
nginx-6799fc88d8-dwrsh   1/1     Running   0          9m5s
nginx-6799fc88d8-sn82p   1/1     Running   0          15s

// 当前副本数为3,则将其扩展至5
root@master ~]# kubectl scale --current-replicas 3 --replicas 5 deployment/nginx
deployment.apps/nginx scaled
[root@master ~]# kubectl get pod
NAME                     READY   STATUS              RESTARTS   AGE
nginx-6799fc88d8-5tsjt   1/1     Running             0          62s
nginx-6799fc88d8-dwrsh   1/1     Running             0          9m51s
nginx-6799fc88d8-jkmln   0/1     ContainerCreating   0          2s
nginx-6799fc88d8-qm5ld   0/1     ContainerCreating   0          2s
nginx-6799fc88d8-sn82p   1/1     Running             0          61s
[root@master ~]# kubectl get deployment
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   4/5     5            4           9m58s

autoscale

自动扩展,给定一个范围,自动根据业务的访问量增加或减少

设定nginx这个deployment的副本数最少为1,最多为5

[root@master ~]# kubectl autoscale --min 1 --max 5 deployment/nginx
horizontalpodautoscaler.autoscaling/nginx autoscaled
[root@master ~]# kubectl get hpa
NAME    REFERENCE          TARGETS         MINPODS   MAXPODS   REPLICAS   AGE
nginx   Deployment/nginx   <unknown>/80%   1         5         0          8s

cluster-info

显示标签为 kubernetes.io/cluster-service=true 的控制平面和服务的地址。要进一步调试和诊断集群问题,请使用“kubectl cluster-info dump”

[root@master ~]# kubectl cluster-info
Kubernetes control plane is running at https://192.168.235.179:6443
KubeDNS is running at https://192.168.235.179:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.

describe

查看特定资源或资源组的详细信息

//查看名为nginx 的pod的详细信息
[root@master ~]# kubectl describe pod nginx
Name:         nginx-6799fc88d8-5tsjt
Namespace:    default
Priority:     0
Node:         node1.example.com/192.168.235.172
Start Time:   Mon, 20 Dec 2021 22:23:28 +0800
Labels:       app=nginx
              pod-template-hash=6799fc88d8
Annotations:  <none>
Status:       Running
IP:           10.244.1.5
IPs:
  IP:           10.244.1.5
Controlled By:  ReplicaSet/nginx-6799fc88d8
Containers:
  nginx:
    Container ID:   docker://5a331ad8c751b41bfa7fd98f4f73e1c97cbc9f8aa76aada48f0be3fe22c10097
    Image:          nginx
    Image ID:       docker-pullable://nginx@sha256:9522864dd661dcadfd9958f9e0de192a1fdda2c162a35668ab6ac42b465f0603
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Mon, 20 Dec 2021 22:23:37 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-n67dr (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-n67dr:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-n67dr
    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  8m9s  default-scheduler  Successfully assigned default/nginx-6799fc88d8-5tsjt to node1.example.com
  Normal  Pulling    8m8s  kubelet            Pulling image "nginx"
  Normal  Pulled     8m    kubelet            Successfully pulled image "nginx" in 7.583042375s
  Normal  Created    8m    kubelet            Created container nginx
  Normal  Started    8m    kubelet            Started container nginx

logs

输出pod或指定资源中容器的日志。如果pod中只有一个容器,则容器名是可选的

// 查看nginx的日志
[root@master ~]# kubectl logs deployment/nginx
Found 5 pods, using pod/nginx-6799fc88d8-dwrsh
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2021/12/20 14:14:43 [notice] 1#1: using the "epoll" event method
2021/12/20 14:14:43 [notice] 1#1: nginx/1.21.4
2021/12/20 14:14:43 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6) 
2021/12/20 14:14:43 [notice] 1#1: OS: Linux 4.18.0-257.el8.x86_64
2021/12/20 14:14:43 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/12/20 14:14:43 [notice] 1#1: start worker processes
2021/12/20 14:14:43 [notice] 1#1: start worker process 32
2021/12/20 14:14:43 [notice] 1#1: start worker process 33

attach

连接到一个正在运行的容器

//获取正在运行中的pod nginx的输出,默认连接到pod中的第一个容器

[root@master ~]# kubectl attach nginx
Defaulting container name to nginx.
Use 'kubectl describe pod/nginx -n default' to see all of the containers in this pod.
If you don't see a command prompt, try pressing enter.

exec

在容器内执行命令

//默认在pod/nginx的第一个容器中运行date并打印输出
[root@master ~]# kubectl exec deployment/nginx date
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
Mon Dec 20 14:38:25 UTC 2021

port-forward

将一个或多个本地端口转发到pod

/将容器中的80端口随即映射到本机的端口

[root@master ~]# kubectl port-forward nginx-6799fc88d8-5tsjt :80
Forwarding from 127.0.0.1:46459 -> 80
Forwarding from [::1]:46459 -> 80

[root@master ~]# curl 127.0.0.1:46459
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@master ~]#

cp

将文件和目录复制到容器或者从容器中拷贝

//将本地的anaconda-ks.cfg文件传输到pod/nginx的/tmp目录下
[root@master ~]# kubectl cp anaconda-ks.cfg nginx-6799fc88d8-5tsjt:/tmp
[root@master ~]# kubectl exec pod/nginx-6799fc88d8-5tsjt -- ls -l /tmp
total 4
-rw------- 1 root root 1252 Dec 20 14:48 anaconda-ks.cfg

label

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

  • label 必须以字母或数字开头,可以使用字母、数字、连字符、点和下划线,最长63个字符。
  • 如果–overwrite 为 true,则可以覆盖已有的 label,否则尝试覆盖 label 将会报错。
  • 如果指定了–resource-version,则更新将使用此资源版本,否则将使用现有的资源版本。
//更改标签
[root@master ~]# kubectl describe deployment/nginx
Name:                   nginx
Namespace:              default
CreationTimestamp:      Mon, 20 Dec 2021 22:14:38 +0800
Labels:                 app=nginx
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               app=nginx
Replicas:               5 desired | 5 updated | 5 total | 5 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=nginx
  Containers:
   nginx:
    Image:        nginx
    Port:         <none>
    Host Port:    <none>
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Progressing    True    NewReplicaSetAvailable
  Available      True    MinimumReplicasAvailable
OldReplicaSets:  <none>
NewReplicaSet:   nginx-6799fc88d8 (5/5 replicas created)
Events:
  Type    Reason             Age   From                   Message
  ----    ------             ----  ----                   -------
  Normal  ScalingReplicaSet  37m   deployment-controller  Scaled up replica set nginx-6799fc88d8 to 1
  Normal  ScalingReplicaSet  29m   deployment-controller  Scaled up replica set nginx-6799fc88d8 to 3
  Normal  ScalingReplicaSet  28m   deployment-controller  Scaled up replica set nginx-6799fc88d8 to 5

//追加标签
[root@master ~]# kubectl label deployment/nginx user=yaya
deployment.apps/nginx labeled
[root@master ~]# kubectl describe deployment/nginx
Name:                   nginx
Namespace:              default
CreationTimestamp:      Mon, 20 Dec 2021 22:14:38 +0800
Labels:                 app=nginx
                        user=tt

api-resources

在服务器上打印支持的 API 资源

//查看所有资源
[root@master ~]# kubectl api-resources
NAME                              SHORTNAMES   APIVERSION                             NAMESPACED   KIND
bindings                                       v1                                     true         Binding
componentstatuses                 cs           v1                                     false        ComponentStatus
configmaps                        cm           v1                                     true         ConfigMap

api-versions

在服务器上以’组/版本’的形式打印支持的api版本

[root@master ~]#  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

k8s进行版本的滚动更新及回滚

// 用Dockerfile编写两个镜像
//制作镜像1
[root@master ~]# mkdir httpd
[root@master ~]# cd httpd
[root@master httpd]# vim Dockerfile
[root@master httpd]# cat Dockerfile 
FROM busybox

RUN mkdir  /data && \
    echo "test page on v1" > /data/index.html
ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
[root@master httpd]# docker build -t weixiaoya/httpd:v0.1 .
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM busybox
latest: Pulling from library/busybox
3cb635b06aa2: Pull complete 
Digest: sha256:b5cfd4befc119a590ca1a81d6bb0fa1fb19f1fbebd0397f25fae164abe1e8a6a
Status: Downloaded newer image for busybox:latest
 ---> ffe9d497c324
Step 2/3 : RUN mkdir  /data &&     echo "test page on v1" > /data/index.html
 ---> Running in bf174265c61d
Removing intermediate container bf174265c61d
 ---> a074d85c6622
Step 3/3 : ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
 ---> Running in e362ffafa0e2
Removing intermediate container e362ffafa0e2
 ---> 104d28f2d58c
Successfully built 104d28f2d58c
Successfully tagged weixiaoya/httpd:v0.1


//制作镜像2
[root@master httpd]# vim Dockerfile 
[root@master httpd]# cat Dockerfile 
FROM busybox

RUN mkdir  /data && \
    echo "test page on v2" > /data/index.html
ENTRYPOINT ["/bin/httpd","-f","-h","/data"]

[root@master httpd]# docker build -t weixiaoya/httpd:v2 .
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM busybox
 ---> ffe9d497c324
Step 2/3 : RUN mkdir  /data &&     echo "test page on v2" > /data/index.html
 ---> Running in aa475f8038dd
Removing intermediate container aa475f8038dd
 ---> 867882b9f918
Step 3/3 : ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
 ---> Running in 4cbc3af592c9
Removing intermediate container 4cbc3af592c9
 ---> e423298d601e
Successfully built e423298d601e
Successfully tagged weixiaoya/httpd:v2


[root@master httpd]# docker images
REPOSITORY                                                        TAG        IMAGE ID       CREATED              SIZE
weixiaoya/httpd                                                   v2         e423298d601e   About a minute ago   1.24MB
weixiaoya/httpd                                                   v0.1       104d28f2d58c   3 minutes ago        1.24MB
busybox                                                           latest     ffe9d497c324   13 days ago          1.24MB


[root@master ~]# docker push weixiaoya/httpd:v0.1
The push refers to repository [docker.io/weixiaoya/httpd]
0d4853dfdf52: Pushed 
64cac9eaf0da: Mounted from library/busybox 
v0.1: digest: sha256:fb79b8b64543613f2677aeb489451b329ed7b4ccbade1820d9d5205495107f4f size: 734

用k8s基于httpd:v0.1镜像运行镜像3个pod

[root@master ~]# kubectl create deploy httpd --image weixiaoya/httpd:v0.1 --replicas 3
deployment.apps/httpd created

[root@master ~]# kubectl get pod
NAME                      READY   STATUS    RESTARTS   AGE
httpd-7649d9b878-5lvf7    1/1     Running   0          8m4s
httpd-7649d9b878-ck6cq    1/1     Running   0          8m4s
httpd-7649d9b878-pkqkk    1/1     Running   0          8m4s

//暴露端口
[root@master ~]# kubectl expose deploy httpd --port 80 --type NodePort
service/httpd exposed

[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
httpd        NodePort    10.111.22.218   <none>        80:31547/TCP   33s
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP        14h

[root@master ~]# curl 10.111.22.218
test page on v1

[root@master ~]# curl 192.168.235.179:31547
test page on v1

k8s进行版本更新

[root@master ~]# kubectl set image deploy/httpd httpd=weixiaoya/httpd:v2
deployment.apps/httpd image updated

//创建一个新pod,删除一个旧pod ,直到更新完成
[root@master ~]# kubectl get pod
NAME                      READY   STATUS              RESTARTS   AGE
httpd-7649d9b878-5lvf7    1/1     Terminating         0          11m
httpd-7649d9b878-ck6cq    1/1     Running             0          11m
httpd-7649d9b878-pkqkk    1/1     Terminating         0          11m
httpd-cb9c79f99-gfk9z     0/1     ContainerCreating   0          10s
httpd-cb9c79f99-w722f     1/1     Running             0          11s
httpd-cb9c79f99-zcsw5     1/1     Running             0          35s


[root@master ~]# kubectl get pod
NAME                      READY   STATUS        RESTARTS   AGE
httpd-cb9c79f99-gfk9z     1/1     Running       0          101s
httpd-cb9c79f99-w722f     1/1     Running       0          102s
httpd-cb9c79f99-zcsw5     1/1     Running       0          2m6s

[root@master ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
httpd        NodePort    10.111.22.218   <none>        80:31547/TCP   4m54s

//访问
[root@master ~]# curl 10.111.22.218
test page on v2
[root@master ~]# curl 192.168.235.179:31547
test page on v2

回滚

[root@master ~]# kubectl rollout undo deploy/httpd
deployment.apps/httpd rolled back

[root@master ~]# kubectl get pod
NAME                      READY   STATUS        RESTARTS   AGE
httpd-7649d9b878-96cnm    1/1     Running       0          8s
httpd-7649d9b878-mq6mh    1/1     Running       0          6s
httpd-7649d9b878-rtmjt    1/1     Running       0          10s
httpd-cb9c79f99-gfk9z     1/1     Terminating   0          3m21s
httpd-cb9c79f99-w722f     1/1     Terminating   0          3m22s
httpd-cb9c79f99-zcsw5     1/1     Terminating   0          3m46s


[root@master ~]# curl 10.111.22.218
test page on v1

[root@master ~]# curl 192.168.235.179:31547
test page on v1

这篇关于kubernetes基础介绍及kubectl常用命令的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!