Pod入门知识(4)


一、Pod是什么?

官方文档:https://kubernetes.io/docs/concepts/workloads/pods/

  Pod 是 Kubernetes 中的最小调度单元,k8s 是通过定义一个 Pod 的资源,然后在 Pod 里面运行容器,容器需要指定一个镜像,这样就可以用来运行具体的服务。一
个 Pod 封装一个容器(也可以封装多个容器),Pod 里的容器共享存储、网络、存储等。也就是说,应该把整个 pod 看作虚拟机,然后每个容器相当于运行在虚拟机的进程。

Pod入门知识(4)

1.1 Pod 如何管理多个容器

    Pod 中可以同时运行多个容器。同一个 Pod 中的容器会自动的分配到同一个 node 上。同一个 Pod 中的容器共享资源、网络环境,它们总是被同时调度,在一个 Pod 中同时运行多个容器是一种比较高级的用法,
只有当你的容器需要紧密配合协作的时候才考虑用这种模式。例如,你有一个容器作为 web 服务器运行,需要用到共享的 volume,有另一个“sidecar”容器来从远端获取资源更新这些文件。

Pod入门知识(4)

1.2 Pod网络

    Pod 是有 IP 地址的,每个 pod 都被分配唯一的 IP 地址(IP 地址是靠网络插件 calico、flannel、weave 等分配的),POD 中的容器共享网络名称空间,包括 IP 地址和网络端口。 
Pod 内部的容器可以使用 localhost 相互通信。 Pod 中的容器也可以通过网络插件 calico 与其他节点的 Pod 通信。

1.3 Pod存储

创建 Pod 的时候可以指定挂载的存储卷。 POD 中的所有容器都可以访问共享卷,允许这些容器共享数据。 Pod 只要挂载持久化数据卷,Pod 重启之后数据还是会存在的。 

1.4 Pod的工作方式

    在 K8s 中,所有的资源都可以使用一个 yaml 文件来创建,创建 Pod 也可以使用 yaml 配置文件。或者使用 kubectl run 在命令行创建 Pod(不常用)。

1.4.1 自主式pod

  所谓的自主式 Pod,就是直接定义一个 Pod 资源,如下:

vi pod-tomcat.yaml
apiVersion: v1 kind: Pod metadata: name: tomcat-test namespace: default labels: app: tomcat spec: containers: - name: tomcat-java ports: - containerPort: 8080 image: xianchao/tomcat-8.5-jre8:v1 imagePullPolicy: IfNotPresent
# 导入准备好的tomat.tar.gz
[root@monitor ~]# docker load -i tomcat.tar.gz
[root@node3 ~]# docker load -i tomcat.tar.gz

# 更新资源清单文件
[root@master work]# kubectl apply -f pod-tomcat.yaml 
pod/tomcat-test created

# 查看pod是否创建成功
[root@master work]# kubectl get pods -o wide -l app=tomcat
NAME          READY   STATUS    RESTARTS   AGE   IP             NODE    NOMINATED NODE   READINESS GATES
tomcat-test   1/1     Running   0          39s   10.244.135.4   node3   <none>           <none>

# 但是自主式 Pod 是存在一个问题的,假如我们不小心删除了 pod: 
[root@master work]# kubectl delete pods tomcat-test
pod "tomcat-test" deleted
[root@master work]# kubectl get pods -l app=tomcat
No resources found in default namespace.
# 说明pod已经被删除了
通过上面可以看到,如果直接定义一个 Pod 资源,那 Pod 被删除,就彻底被删除了,不会再创建一个新的 Pod,这在生产环境还是具有非常大风险的,所以今后我们接触的 Pod,都是控制器管理的。

1.4.2 控制器管理POD

  常见的管理 Pod 的控制器:Replicaset、Deployment、Job、CronJob、Daemonset、Statefulset。 控制器管理的 Pod 可以确保 Pod 始终维持在指定的副本数运行。

如,通过 Deployment 管理 Pod

# 导入镜像nginx.tar.gz,monitor和node3上导入

# 创建一个资源清单文件
[root@master work]# vim nginx-deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-test
  labels:
    app: nginx-deploy
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 2
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: my-nginx
        image: xianchao/nginx:v1
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 80

# 更新资源清单文件
[root@master work]# kubectl apply -f nginx-deploy.yaml 
deployment.apps/nginx-test created

# 查看deployment
[root@master work]# kubectl  get deploy -l app=nginx-deploy
NAME         READY   UP-TO-DATE   AVAILABLE   AGE
nginx-test   0/2     2            0           42s

# 查看Replicaset
[root@master work]# kubectl get rs -l app=nginx
NAME                    DESIRED   CURRENT   READY   AGE
nginx-test-75c685fdb7   2         2         0       57s

# 查看pod
[root@master work]# kubectl get pods -o wide -l app=nginx
NAME                          READY   STATUS    RESTARTS   AGE   IP       NODE     NOMINATED NODE   READINESS GATES
nginx-test-75c685fdb7-9mkzf   0/1     Pending   0          73s   <none>   <none>   <none>           <none>
nginx-test-75c685fdb7-k6467   0/1     Pending   0          73s   <none>   <none>   <none>           <none>

# 删除nginx-test-75c685fdb7-k6467 这个pod
[root@master work]# kubectl delete pods nginx-test-75c685fdb7-k6467
pod "nginx-test-75c685fdb7-k6467" deleted

[root@master work]# kubectl get pods -o wide -l app=nginx
NAME                          READY   STATUS    RESTARTS   AGE     IP              NODE      NOMINATED NODE   READINESS GATES
nginx-test-75c685fdb7-9mkzf   1/1     Running   0          3m48s   10.244.75.199   monitor   <none>           <none>
# 多查看几次
[root@master work]# kubectl get pods -o wide -l app=nginx
NAME                          READY   STATUS    RESTARTS   AGE     IP              NODE      NOMINATED NODE   READINESS GATES
nginx-test-75c685fdb7-92w5b   1/1     Running   0          37s     10.244.135.6    node3     <none>           <none>
nginx-test-75c685fdb7-9mkzf   1/1     Running   0          4m28s   10.244.75.199   monitor   <none>           <none>
# 可以发现创建了一个新的pod:nginx-test-75c685fdb7-92w5b

通过上面可以发现通过 deployment 管理的 pod,可以确保 pod 始终维持在指定副本数量 

1.5 如何创建一个Pod资源

K8s创建pod流程:

Pod入门知识(4)

     Pod 是 Kubernetes 中最基本的部署调度单元,可以包含 container,逻辑上表示某种应用的一个 实例。例如一个 web 站点应用由前端、后端及数据库构建而成,这三个组件将运行在各自的容器中,那 么我们可以创建包含三个 container 的 pod。

创建Pod流程:

Pod入门知识(4)

master 节点:kubectl -> kube-api -> kubelet -> CRI 容器环境初始化 

1.客户端提交创建 Pod 的请求,可以通过调用 API Server 的 Rest API 接口,也可以通过 kubectl 命令行工具。如 kubectl apply -f filename.yaml(资源清单文件)

2.apiserver 接收到 pod 创建请求后,会将 yaml 中的属性信息(metadata)写入 etcd。 

3.apiserver 触发 watch 机制准备创建 pod,信息转发给调度器 scheduler,调度器使用调度算法选择node,调度器将 node 信息给 apiserver,apiserver 将绑定的 node 信息写入 etcd

调度器用一组规则过滤掉不符合要求的主机。比如 Pod 指定了所需要的资源量,那么可用资源比 Pod 需要的资源量少的主机会被过滤掉。
scheduler 查看 k8s api ,类似于通知机制。 
首先判断:pod.spec.Node == null? 
若为 null,表示这个 Pod 请求是新来的,需要创建;因此先进行调度计算,找到最“闲”的 node。 然后将信息在 etcd 数据库中更新分配结果:pod.spec.Node = nodeA (设置一个具体的节点) 
ps:同样上述操作的各种信息也要写到 etcd 数据库中中 

4.apiserver 又通过 watch 机制,调用 kubelet,指定 pod 信息,调用 Docker API 创建并启动 pod 内的容器

5.创建完成之后反馈给 kubelet, kubelet 又将 pod 的状态信息给 apiserver, apiserver 又将 pod 的状态信息写入 etcd。

二、Pod资源清单YAML编写技巧

举例:
[root@master work]# cat pod-tomcat.yaml apiVersion: v1 # api版本 kind: Pod # 创建的资源 metadata: name: tomcat-test # Pod的名字,自取比较有代表性的名字 namespace: default # Pod所在的名称空间 labels: app: tomcat # pod具有的标签 spec: containers: - name: tomcat-java # Pod里容器的名字 ports: - containerPort: 8080 # 容器暴露的端口 image: cxiong/tomcat-8.5-jre8:v1 # 容器使用的镜像 imagePullPolicy: IfNotPresent #镜像拉取的策略 # apiVersion:使用kubectl api-versions查看api版本可以发现很多版本,v1核心版 # 更新资源清单文件 kubectl apply -f pod-tomcat.yaml

2.1 Pod资源清单编写技巧

# 通过kubectl explain 查看定义的Pod包含哪些字段
[root@master work]# kubectl explain pods
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.
[Pod 是可以在主机上运行的容器的集合。此资源是由客户端创建并安排到主机上。] 

FIELDS:
   apiVersion    <string>  # 从最上面可以看到使用的版本是v1版
     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/sig-architecture/api-conventions.md#resources
[APIVersion 定义了对象,代表了一个版本。] 

   kind    <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/sig-architecture/api-conventions.md#types-kinds
[Kind 是字符串类型的值,代表了要创建的资源。服务器可以从客户端提交的请求推断出这个资源。]

   metadata    <Object>    # 
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
[metadata 是对象,定义元数据属性信息的] 

   spec    <Object>  #创建一个什么样的
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
[spec 制定了定义 Pod 的规格,里面包含容器的信息] 

   status    <Object> 不需要写
     Most recently observed status of the pod. This data may not be up to date.
     Populated by the system. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
[status 表示状态,这个不可以修改,定义 pod 的时候也不需要定义这个字段] 
# 查看pod.metadata字段如何定义
[root@master work]# kubectl explain pods.metadata
KIND:     Pod
VERSION:  v1
RESOURCE: metadata <Object>
# metadata 是对象<Object>,下面可以有多个字段 
DESCRIPTION:
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
ObjectMeta is metadata that all persisted resources must have, which
includes all objects users must create.
FIELDS:
annotations    <map[string]string>
Annotations is an unstructured key value map stored with a resource that
may be set by external tools to store and retrieve arbitrary metadata. They
are not queryable and should be preserved when modifying objects. More
info: http://kubernetes.io/docs/user-guide/annotations
# annotations 是注解,map 类型表示对应的值是 key-value 键值对,<string,string>表示 key 和value 都是 String 类型的 
"metadata": {
"annotations": {
"key1" : "value1",
"key2" : "value2"
}
}
用 Annotation 来记录的信息包括: 
build 信息、release 信息、Docker 镜像信息等,例如时间戳、release id 号、镜像 hash 值、docker 
registry 地址等; 
日志库、监控库、分析库等资源库的地址信息; 
程序调试工具信息,例如工具名称、版本号等; 
团队的联系信息,例如电话号码、负责人名称、网址等。
clusterName    <string>
The name of the cluster which the object belongs to. This is used to
distinguish resources with same name and namespace in different clusters.
This field is not set anywhere right now and apiserver is going to ignore
it if set in create or update request.
# 对象所属群集的名称。这是用来区分不同集群中具有相同名称和命名空间的资源。此字段现在未设置在任何位置,apiserver 将忽略它,如果设置了就使用设置的值
creationTimestamp    <string>
CreationTimestamp is a timestamp representing the server time when this
object was created. It is not guaranteed to be set in happens-before order
across separate operations. Clients may not set this value. It is
represented in RFC3339 form and is in UTC.
Populated by the system. Read-only. Null for lists. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
deletionGracePeriodSeconds    <integer>
Number of seconds allowed for this object to gracefully terminate before it
will be removed from the system. Only set when deletionTimestamp is also
set. May only be shortened. Read-only.
deletionTimestamp    <string>  # 默认删除时间是30s
DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items,deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested.
  Populated by the system when a graceful deletion is requested. Read-only.
  More info:
  https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
finalizers    <[]string>
Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order. Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list.
generateName    <string>
GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.
If this field is specified and the generated name exists, the server will NOT return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not be found in the time allotted, and the client should retry (optionally after the time indicated in the Retry-After header).
Applied only if Name is not specified. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency
generation    <integer>
A sequence number representing a specific generation of the desired state.Populated by the system. Read-only.
labels    <map[string]string>
Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels
# labels 是标签,labels 是 map 类型,map 类型表示对应的值是 key-value 键值对,<string,string>表示 key 和 value 都是 String 类型的 
managedFields    <[]Object>
ManagedFields maps workflow-id and version to the set of fields that are managed by that workflow. This is mostly for internal housekeeping, and users typically shouldn't need to set or understand this field. A workflow can be the user's name, a controller's name, or the name of a specific apply path like "ci-cd". The set of fields is always in the version that the workflow used when modifying the object.
name    <string>   # 创建资源的名字
Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated.
More info: http://kubernetes.io/docs/user-guide/identifiers#names
namespace    <string>  # 创建资源所属的名称空间
Namespace defines the space within which each name must be unique. An empty namespace is equivalent to the "default" namespace, but "default" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.
Must be a DNS_LABEL. Cannot be updated. More info:
http://kubernetes.io/docs/user-guide/namespaces
# namespaces 划分了一个空间,在同一个 namesace 下的资源名字是唯一的,默认的名称空间是default。 
ownerReferences    <[]Object>
List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller.
resourceVersion    <string>
An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources. Populated by the system. Read-only. Value must be treated as opaque by
clients and . More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
selfLink    <string>
SelfLink is a URL representing this object. Populated by the system.
Read-only.
DEPRECATED Kubernetes will stop propagating this field in 1.20 release and
the field is planned to be removed in 1.21 release.
uid    <string>
UID is the unique in time and space value for this object. It is typically
generated by the server on successful creation of a resource and is not
allowed to change on PUT operations.
Populated by the system. Read-only. More info:
http://kubernetes.io/docs/user-guide/identifiers#uids

 查看spec常用字段

[root@master work]# kubectl explain pods.spec

查看spec下containers

[root@master work]# kubectl explain pods.spec.container
# container 是定义在 pod 里面的,一个 pod 至少要有一个容器。
# 以下设置:使用本地镜像,如果本地没有就去拉取镜像
# image 是用来指定容器需要的镜像的
image: tomcat
imagePullPolicy: IfNotPresent
imagePullPolicy    <string>
Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always
if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated.
More info:
https://kubernetes.io/docs/concepts/containers/images#updating-images
#镜像拉取策略,pod 是要调度到 node 节点的,那 pod 启动需要镜像,可以根据这个字段设置镜像拉
取策略,支持如下三种: 
Always:不管本地是否存在镜像,都要重新拉取镜像 
Never: 从不拉取镜像 
IfNotPresent:如果本地存在,使用本地的镜像,本地不存在,从官方拉取镜像 

查看pods.spec.containers.ports字段如何定义

[root@master work]# kubectl explain pods.spec.containers.ports
containerPort:容器端口,containerPort 是必须字段, pod 中的容器需要暴露的端口。
hostIP: 主机IP,将容器中的服务暴露到宿主机的端口上时,可以指定绑定的宿主机 IP。 
hostPort: 主机端口,容器中的服务在宿主机上映射的端口
name: 容器名字,别名
protocol: 协议

2.2 通过资源文件创建第一个Pod

apiVersion: v1
kind: Pod
metadata:
name: pod-test
namespace: default
labels:
app: tomcat-pod-test
spec:
containers:    # 下面的内容第一次运行以后就不能再修改了
- name:  tomcat-test
ports:
- containerPort: 8080
image: cxiong/tomcat-8.5-jre8:v1
imagePullPolicy: IfNotPresent
# 更新资源清单文件
kubectl apply -f pod-test.yaml
# 查看pod是否创建成功
[root@master work]# kubectl get pods -o wide
NAME                          READY   STATUS    RESTARTS   AGE     IP              NODE      NOMINATED NODE   READINESS GATES
demo-pod                      1/1     Running   0          6h9m    10.244.135.2    node3     <none>           <none>
nginx-7f466444dc-ndp5t        1/1     Running   0          5h44m   10.244.75.198   monitor   <none>           <none>
nginx-7f466444dc-qbxfn        1/1     Running   0          5h44m   10.244.135.3    node3     <none>           <none>
nginx-test-75c685fdb7-92w5b   1/1     Running   0          97m     10.244.135.6    node3     <none>           <none>
nginx-test-75c685fdb7-9mkzf   1/1     Running   0          101m    10.244.75.199   monitor   <none>           <none>
pod-test                      1/1     Running   0          12s     10.244.75.200   monitor   <none>           <none>
tomcat-test                   1/1     Running   0          2m41s   10.244.135.7    node3     <none>           <none>
# 查看pod日志
kubectl logs pod-test
#查看 pod 里指定容器的日志 
kubectl logs pod-first -c tomcat-first
# 进入创建的容器,默认进入到pod里第一个容器中
[root@master work]# kubectl exec -it pod-test -- /bin/bash
# 如果pod里有多个容器,则需要具体指定容器,可以自建2个进行测试,metadata.name名字相同,但是containers.name名字不同
kubectl exec -it pod-first -c tomcat-test -- /bin/bash
    我们上面创建的 pod 是一个自主式 pod,也就是通过 pod 创建一个应用程序,如果 pod 出现故障停掉,那么我们通过 pod 部署的应用也就会停掉,不安全, 还有一种控制器管理的 pod,
通过控制器创建pod,可以对 pod 的生命周期做管理,可以定义 pod 的副本数,如果有一个 pod 意外停掉,那么会自动起来一个 pod 替代之前的 pod,之后会讲解 pod 的控制器

 2.3 通过kubect run运行pod

[root@master work]# kubectl run pod-run --image=tomat --image-pull-policy=IfNotPresent --port=8080
pod/pod-run created
[root@master work]# kubectl get pods
NAME                          READY   STATUS    RESTARTS   AGE
demo-pod                      1/1     Running   0          6h23m
nginx-7f466444dc-ndp5t        1/1     Running   0          5h59m
nginx-7f466444dc-qbxfn        1/1     Running   0          5h59m
nginx-test-75c685fdb7-92w5b   1/1     Running   0          112m
nginx-test-75c685fdb7-9mkzf   1/1     Running   0          116m
pod-run                       0/1     Pending   0          24s
pod-test                      1/1     Running   0          15m
tomcat-test                   1/1     Running   0          17m
# 导出pod-run的yaml文件
[root@master work]# kubectl get pods pod-run -o yaml

三、命名空间namespace概述

# 什么是名称空间?
Kubernetes 支持多个虚拟集群,它们底层依赖于同一个物理集群。 这些虚拟集群被称为命名空间。 
命名空间 namespace 是 k8s 集群级别的资源,可以给不同的用户、租户、环境或项目创建对应的命名空间,例如,可以为 test、devlopment、production 环境分别创建各自的命名空间。
# 查看名称空间命令:kubectl get namespace或者kubectl get ns
[root@master work]# kubectl get namespace
NAME                   STATUS   AGE
default                Active   9d
kube-node-lease        Active   9d
kube-public            Active   9d
kube-system            Active   9d
kubernetes-dashboard   Active   6h24m
# 创建名称空间
[root@master work]# kubectl create ns test
namespace/test created
[root@master work]# kubectl get ns
NAME                   STATUS   AGE
default                Active   9d
kube-node-lease        Active   9d
kube-public            Active   9d
kube-system            Active   9d
kubernetes-dashboard   Active   6h29m
test                   Active   6s
#创建一个测试的namespace
[root@master work]# kubectl apply -f test.yaml 
pod/pod-test created
[root@master work]# kubectl get pods -n test
NAME       READY   STATUS    RESTARTS   AGE
pod-test   0/1     Pending   0          8s

3.1 namespace应用场景

命名空间适用于存在很多跨多个团队或项目的用户的场景。对于只有几到几十个用户的集群,根本不需要创建或考虑命名空间。 
1、查看名称空间及其资源对象 
k8s 集群默认提供了几个名称空间用于特定目的,例如,kube-system 主要用于运行系统级资源,存放 k8s 一些组件的。而 default 则为那些未指定名称空间的资源操作提供一个默认值。 
使用 kubectl get namespace 可以查看 namespace 资源,使用 kubectl describe namespace $NAME 可以查看特定的名称空间的详细信息。

[root@master work]# kubectl describe ns test
Name: test
Labels: <none>
Annotations: <none>
Status: Active

No resource quota.

No LimitRange resource.

2、管理 namespace 资源 
namespace 资源属性较少,通常只需要指定名称即可创建,如“kubectl create namespace qa”。namespace 资源的名称仅能由字母、数字、下划线、连接线等字符组成。
删除 namespace资源会级联删除其包含的所有其他资源对象。

3.删除命名空间,会将名称空间下的所有容器都删除

[root@master work]# kubectl delete ns qa
namespace “qa” deleted

 3.2 namespace使用案例分享

# 创建命名空间
kubectl create ns teset
# 切换命名空间
[root@master work]# kubectl  config set-context --current --namespace=kube-system
Context "kubernetes-admin@kubernetes" modified.
kubectl get pods可以看到kube-systemx下的资源,不需要-n指定
#查看哪些资源属于命名空间级别的
[root@master work]# kubectl api-resources --namespaced=true

3.3 namespace资源限额

  namespace 是命名空间,里面有很多资源,那么我们可以对命名空间资源做个限制,防止该命名空间 部署的资源超过限制。

如何对 namespace 资源做限额呢?

[root@master work]# cat namespace-quota.yaml 
apiVersion: v1
kind: ResourceQuota
metadata:
name: mem-cpu-quota
namespace: test
spec:
hard:
requests.cpu: "2"
requests.memory: 2Gi
limits.cpu: "4"
limits.memory: 4Gi
#创建的 ResourceQuota 对象将在 test 名字空间中添加以下限制: 
每个容器必须设置内存请求(memory request),内存限额(memory limit),cpu 请求(cpu 
request)和 cpu 限额(cpu limit)。 
所有容器的内存请求总额不得超过 2GiB。 
所有容器的内存限额总额不得超过 4 GiB。 
所有容器的 CPU 请求总额不得超过 2 CPU。 
所有容器的 CPU 限额总额不得超过 4CPU。
[root@master work]# kubectl apply -f namespace-quota.yaml
resourcequota/mem-cpu-quota created
[root@master work]# kubectl describe ns test
Name:         test
Labels:       <none>
Annotations:  <none>
Status:       Active
Resource Quotas
Name:            mem-cpu-quota
Resource         Used  Hard
--------         ---   ---
limits.cpu       0     4
limits.memory    0     4Gi
requests.cpu     0     2
requests.memory  0     2Gi

[root@master work]# kubectl describe pods pod-test -n test

3.4 k8s标签labels

什么是标签? 
标签其实就一对 key/value ,被关联到对象上,比如 Pod,标签的使用我们倾向于能够表示对象的特殊特点,就是一眼就看出了这个 Pod 是干什么的,标签可以用来划分特定的对象(比如版本,服务类型等),
标签可以在创建一个对象的时候直接定义,也可以在后期随时修改,每一个对象可以拥有多个标签,但是,key 值必须是唯一的。创建标签之后也可以方便我们对资源进行分组管理。
如果对 pod 打标签,之后就可以使用标签来查看、删除指定的 pod。
在 k8s 中,大部分资源都可以打标签。

给pod资源打标签

  kubectl lable pod –help

# 对已存在的pod打标签
# 对名称空间default下的pod-run打标签
[root@master work]# kubectl get pods -n default --show-labels
NAME                          READY   STATUS             RESTARTS   AGE     LABELS
pod-run                       0/1     ImagePullBackOff   0          121m    run=pod-run
[root@master work]# kubectl label pods -n default pod-run release=v1
pod/pod-run labeled
# 查看default名称空间下的资源
[root@master work]# kubectl get pods -n default --show-labels
NAME                          READY   STATUS             RESTARTS   AGE     LABELS
pod-run                       0/1     ImagePullBackOff   0          122m    release=v1,run=pod-run
# 查看默认名称空间下所有 pod 资源的标签
[root@master work]# kubectl get pods --show-labels
#查看默认名称空间下指定 pod 具有的所有标签 
[root@master work]# kubectl get pods pod-test --show-labels
NAME       READY   STATUS    RESTARTS   AGE   LABELS
pod-test   1/1     Running   0          12m   app=tomcat-pod-test,release=v1
#列出默认名称空间下标签 key 是 release 的 pod,不显示标签
[root@master work]# kubectl get pods -l release
NAME       READY   STATUS    RESTARTS   AGE
pod-test   1/1     Running   0          14m
#列出默认名称空间下标签 key 是 release、值是 v1 的 pod,不显示标签 
[root@master work]# kubectl get pods -l release=v1
NAME       READY   STATUS    RESTARTS   AGE
pod-test   1/1     Running   0          15m
# 列出默认名称空间下标签 key 是 release 的所有 pod,并打印对应的标签值 
[root@master work]# kubectl get pods -L release
pod-test                                   1/1     Running   0          16m     v1
# 查看所有名称空间下的所有 pod 的标签 
[root@master work]# kubectl get pods --all-namespaces --show-labels
[root@master work]# kubectl get pods -l release=v1 -L release
NAME       READY   STATUS    RESTARTS   AGE   RELEASE
pod-test   1/1     Running   0          18m   v1

 

原创文章,作者:wdmbts,如若转载,请注明出处:https://blog.ytso.com/275534.html

(0)
上一篇 2022年7月20日
下一篇 2022年7月20日

相关推荐

发表回复

登录后才能评论