第二讲《k8s资源介绍:Namespace与Pod 》

一、namespace介绍

1.概念

在 Kubernetes 中,命名空间(Namespace) 提供一种机制,将同一集群中的资源划分为相互隔离的组。 同一命名空间内的资源命名要唯一,但跨命名空间时没有这个要求。 命名空间作用域仅针对带有命名空间的对象,例如 Deployment、Service 等, 这种作用域对集群访问的对象不适用,例如 StorageClass、Node、PersistentVolume 等。

2.集群默认的namespace

命名空间查看

[root@k8s-master test-namespace]# kubectl get namespace
NAME              STATUS   AGE
default           Active   1d
kube-node-lease   Active   1d
kube-public       Active   1d
kube-system       Active   1d

default 没有指明使用其它命名空间的对象所使用的默认命名空间
kube-system Kubernetes系统创建对象所使用的命名空间
kube-public 这个命名空间是自动创建的,所有用户(包括未经过身份验证的用户)都可以读取它。这个命名空间主要用于集群使用,以防某些资源在整个集群中应该是可见和可读的。 这个命名空间的公共方面只是一种约定,而不是要求。
kube-node-lease 此命名空间用于与各个节点相关的 租约(Lease)对象。 节点租期允许 kubelet发送心跳,由此控制面能够检测到节点故障

3.创建命名空间

用apply创建

[root@k8s-master test-namespace]# cat test-namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: test
[root@k8s-master test-namespace]# kubectl apply -f test-namespace.yaml
namespace/test created

用create创建的两种方式

[root@k8s-master test-namespace]# kubectl create namespace test
namespace/test created
[root@k8s-master test-namespace]# kubectl create -f test-namespace.yaml
namespace/test created

4.命名空间删除(谨慎使用)

用yaml文件删除

[root@k8s-master test-namespace]# kubectl delete -f test-namespace.yaml
namespace/test deleted

用命令删除

[root@k8s-master test-namespace]# kubectl delete namespace test
namespace/test deleted

线上环境命名空间删除需谨慎,因为命名空间删除后,此命名空间下的所有资源会被全部删除,切记切记切记~

5.浅谈apply和create的区别

create命令演示

[root@k8s-master test-namespace]# kubectl create -f test-namespace.yaml
namespace/test1 created
[root@k8s-master test-namespace]# vim test-namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: test1
  labels:
    test: env
[root@k8s-master test-namespace]# kubectl create -f test-namespace.yaml
Error from server (AlreadyExists): error when creating "test-namespace.yaml": namespaces "test1" already exists

apply命令演示

[root@k8s-master test-namespace]# kubectl apply -f test-namespace.yaml
namespace/test1 created
[root@k8s-master test-namespace]# vim test-namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: test1
  labels:
    test: env
[root@k8s-master test-namespace]# kubectl apply -f test-namespace.yaml
namespace/test1 configured
  • create 此命令将告诉 K8S API服务器,你要创建、删除或替换一个或多个资源。以更简化的方式,这意味着你可以从头开始创建一个全新的对象。或者,它通过定义需求对任何现有对象进行一些更改。
  • apply 此命令意味着通过在给定的 YAML 文件中声明您确切需要的内容来更改已经存在的对象。

在 kubectl create 命令中,我们指定了一个特定行为,也就是 create,因此它是一种更具命令式的方法。在 kubectl apply 命令中,我们指定系统的目标状态,而不指定一个特定的行为,因此它是更具声明性的方法。我们让系统决定采取什么行动。如果资源不存在,它将创建它,如果资源存在,则它将配置应用于现有资源。

6.哪些资源在命名空间下

true OR false

[root@k8s-master ~]# kubectl api-resources
NAME                              SHORTNAMES   APIVERSION                             NAMESPACED   KIND
bindings                                       v1                                     true         Binding
componentstatuses                 cs           v1                                     false        ComponentStatus
configmaps                        cm           v1                                     true         ConfigMap
endpoints                         ep           v1                                     true         Endpoints
events                            ev           v1                                     true         Event
limitranges                       limits       v1                                     true         LimitRange

二、Pod介绍

1.概念

Pod 是可以在 Kubernetes 中创建和管理的、最小的可部署的计算单元,也是 kubernetes 系统上运行容器化应用的资源对象。Kubernetes 集群中其他资源对象都是为 pod 这个资源对象做支撑来实现 kubernetes 管理应用服务的目的。

2.Pod的结构

第二讲《k8s资源介绍:Namespace与Pod 》_第1张图片

Pause容器 全称infrastucture container(又叫infra)基础容器

  • 1.每个Pod里运行着一个特殊的被称之为Pause的容器,其他容器则为业务容器,这些业务容器共享Pause容器的网络栈和Volume挂载卷
  • 2.因此他们之间通信和数据交换更为高效,在设计时我们可以充分利用这一特性将一组密切相关的服务进程放入同一个Pod中。
  • 3.同一个Pod里的容器之间仅需通过localhost就能互相通信。

pause容器主要为每个业务容器提供以下功能:

① PID命名空间:Pod中的不同应用程序可以看到其他应用程序的进程ID。
② 网络命名空间:Pod中的多个容器能够访问同一个IP和端口范围。
③ IPC命名空间:Pod中的多个容器能够使用SystemV IPC或POSIX消息队列进行通信。
④ UTS命名空间:Pod中的多个容器共享一个主机名;Volumes(共享存储卷)
⑤ Pod中的各个容器可以访问在Pod级别定义的Volumes。

2.Pod生命周期

生命周期全过程
第二讲《k8s资源介绍:Namespace与Pod 》_第2张图片

  1. pod创建
  2. 运行初始化容器过程(init container)
  3. 运行主容器过程(main container)
  4. 容器启动钩子(post start),容器终止前钩子(prestop)(这两个钩子的作用就是,如果你想让容器启动之后做一些事情,你可以传递一些参数或者命令给容器启动钩子这个节点,当然如果你想在终止之前执行一些命令,你可以传递一些参数和一些命令给终止前这个节点)
  5. 容器的存活性探测(liveness probe),就绪性探测(readliness probe)(这两个作用就是子过程)
  6. pod终止

创建主容器是必须的操作,初始化init容器,启动后钩子,存活性探测,就绪性探测,停止前钩子为可选执行。
第二讲《k8s资源介绍:Namespace与Pod 》_第3张图片

在整个生命周期终,pod会出现5种状态,分别如下:

Pending(挂起):apiserver已经创建了pod资源对象,但它尚未被调度完成或者仍处于下载镜像的过程中
Running(运行中):Pod 已经调度到了某个节点,Pod中所有的容器都已被创建。至少有一个容器仍在运行,或者正处于启动或重启状态。
Succeeded(成功):pod中所有的容器都已经成功终止并且不会被重启
Failed(失败):所有容器都已经终止,但至少有一个容器终止失败,即容器返回了非0值的退出状态
Unknown(未知):apiserver无法正常获取到pod对象的状态信息,通常由网络通信失败所导致。

3.Pod的定义

apiVersion: v1     #必选,版本号,例如v1
kind: Pod         #必选,资源类型,例如 Pod
metadata:         #必选,元数据
  name: string     #必选,Pod名称
  namespace: string  #Pod所属的命名空间,默认为"default"
  labels:           #自定义标签列表
    - name: string                 
spec:  #必选,Pod中容器的详细定义
  containers:  #必选,Pod中容器列表
  - name: string   #必选,容器名称
    image: string  #必选,容器的镜像名称
    imagePullPolicy: [ Always|Never|IfNotPresent ]  #获取镜像的策略 
    command: [string]   #容器的启动命令列表,如不指定,使用打包时使用的启动命令
    args: [string]      #容器的启动命令参数列表
    workingDir: string  #容器的工作目录
    volumeMounts:       #挂载到容器内部的存储卷配置
    - name: string      #引用pod定义的共享存储卷的名称,需用volumes[]部分定义的的卷名
      mountPath: string #存储卷在容器内mount的绝对路径,应少于512字符
      readOnly: boolean #是否为只读模式
    ports: #需要暴露的端口库号列表
    - name: string        #端口的名称
      containerPort: int  #容器需要监听的端口号
      hostPort: int       #容器所在主机需要监听的端口号,默认与Container相同
      protocol: string    #端口协议,支持TCP和UDP,默认TCP
    env:   #容器运行前需设置的环境变量列表
    - name: string  #环境变量名称
      value: string #环境变量的值
    resources: #资源限制和请求的设置
      limits:  #资源限制的设置
        cpu: string     #Cpu的限制,单位为core数,将用于docker run --cpu-shares参数
        memory: string  #内存限制,单位可以为Mib/Gib,将用于docker run --memory参数
      requests: #资源请求的设置
        cpu: string    #Cpu请求,容器启动的初始可用数量
        memory: string #内存请求,容器启动的初始可用数量
    lifecycle: #生命周期钩子
		postStart: #容器启动后立即执行此钩子,如果执行失败,会根据重启策略进行重启
		preStop: #容器终止前执行此钩子,无论结果如何,容器都会终止
    livenessProbe:  #对Pod内各容器健康检查的设置,当探测无响应几次后将自动重启该容器
      exec:         #对Pod容器内检查方式设置为exec方式
        command: [string]  #exec方式需要制定的命令或脚本
      httpGet:       #对Pod内个容器健康检查方法设置为HttpGet,需要制定Path、port
        path: string
        port: number
        host: string
        scheme: string
        HttpHeaders:
        - name: string
          value: string
      tcpSocket:     #对Pod内个容器健康检查方式设置为tcpSocket方式
         port: number
       initialDelaySeconds: 0       #容器启动完成后首次探测的时间,单位为秒
       timeoutSeconds: 0          #对容器健康检查探测等待响应的超时时间,单位秒,默认1秒
       periodSeconds: 0           #对容器监控检查的定期探测时间设置,单位秒,默认10秒一次
       successThreshold: 0			#健康检查成功几次算成功
       failureThreshold: 0			#健康检查失败几次算失败
       securityContext:
         privileged: false
  restartPolicy: [Always | Never | OnFailure]  #Pod的重启策略
  nodeName: <string> #设置NodeName表示将该Pod调度到指定到名称的node节点上
  nodeSelector: obeject #设置NodeSelector表示将该Pod调度到包含这个label的node上
  imagePullSecrets: #Pull镜像时使用的secret名称,以key:secretkey格式指定
  - name: string
  hostNetwork: false   #是否使用主机网络模式,默认为false,如果设置为true,表示使用宿主机网络
  volumes:   #在该pod上定义共享存储卷列表
  - name: string    #共享存储卷名称 (volumes类型有很多种)
    emptyDir: {}       #类型为emtyDir的存储卷,与Pod同生命周期的一个临时目录。为空值
    hostPath: string   #类型为hostPath的存储卷,表示挂载Pod所在宿主机的目录
      path: string                #Pod所在宿主机的目录,将被用于同期中mount的目录
      type:string		#
    secret:          #类型为secret的存储卷,挂载集群与定义的secret对象到容器内部
      scretname: string  
      items:     
      - key: string
        path: string
    configMap:         #类型为configMap的存储卷,挂载预定义的configMap对象到容器内部
      name: string
      items:
      - key: string
        path: string

命令行查看资源的详细属性

[root@k8s-master test-namespace]# kubectl explain pod
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.

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/sig-architecture/api-conventions.md#resources

   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

   metadata     <Object>
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#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

   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
[root@k8s-master test-namespace]# kubectl explain pod.apiVersion
KIND:     Pod
VERSION:  v1

FIELD:    apiVersion <string>

DESCRIPTION:
     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

4.Pod的基本配置

4.1镜像拉取策略

[root@k8s-master test-namespace]# cat test-pod.yaml
apiVersion: v1
kind: Pod
metadata:
  name: test-pod
  namespace: test
  labels:
    env: test
spec:
  containers:
    - name: nginx # 容器名称
      image: nginx:1.16.1 # 容器需要的镜像地址
      imagePullPolicy: Always # 镜像拉去策略[Always|IfNotPresent|Never]

三种拉取策略:

Always:总是从远程仓库拉取镜像(一直远程下载)。
IfNotPresent:本地有则使用本地镜像,本地没有则从远程仓库拉取镜像(本地有就用本地,本地没有就使用远程下载)。
Never:只使用本地镜像,从不去远程仓库拉取,本地没有就报错(一直使用本地,没有就报错)。

默认值说明:

如果镜像tag为具体的版本号,默认策略是IfNotPresent。 如果镜像tag为latest(最终版本),默认策略是Always。

创建Pod

[root@k8s-master test-namespace]# kubectl apply -f test-pod.yaml

查看Pod的详细信息

[root@k8s-master test-namespace]# kubectl describe pod test-pod -n test

4.2启动命令

添加command参数

apiVersion: v1
kind: Pod
metadata:
  name: test-pod
  namespace: test
  labels:
    env: test
spec:
  containers:
    - name: nginx # 容器名称
      image: nginx:1.16.1 # 容器需要的镜像地址
      imagePullPolicy: Always # 镜像拉去策略[Always|IfNotPresent|Never]
    - name: busybox # 容器名称
      image: busybox:1.30 # 容器需要的镜像地址
      command: ["/bin/sh","-c","touch /tmp/hello.txt;while true;do /bin/echo $(date +%T) >> /tmp/hello.txt;sleep 3;done;"]

更新pod

[root@k8s-master test-namespace]# kubectl apply -f test-pod.yaml

进入pod查看命令执行结果

[root@k8s-master test-namespace]# kubectl exec -it test-pod -n test -c busybox -- /bin/sh
/ # cat /tmp/hello.txt
02:02:14
02:02:17
02:02:20
02:02:23

特别说明:通过上面发现command已经可以完成启动命令和传递参数的功能,为什么还要提供一个args选项,用于传递参数?其实和Docker有点关系,kubernetes中的command和args两个参数其实是为了实现覆盖Dockerfile中的ENTRYPOINT的功能:

如果command和args均没有写,那么用Dockerfile的配置。
如果command写了,但是args没有写,那么Dockerfile默认的配置会被忽略,执行注入的command。
如果command没有写,但是args写了,那么Dockerfile中配置的ENTRYPOINT命令会被执行,使用当前args的参数。
如果command和args都写了,那么Dockerfile中的配置会被忽略,执行command并追加上args参数。

4.3环境变量

添加env参数

apiVersion: v1
kind: Pod
metadata:
  name: test-pod
  namespace: test
  labels:
    env: test
spec:
  containers:
    - name: nginx # 容器名称
      image: nginx:1.16.1 # 容器需要的镜像地址
      imagePullPolicy: Always # 镜像拉去策略[Always|IfNotPresent|Never]
    - name: busybox # 容器名称
      image: busybox:1.30 # 容器需要的镜像地址
      command: ["/bin/sh","-c","touch /tmp/hello.txt;while true;do /bin/echo $(date +%T) >> /tmp/hello.txt;sleep 3;done;"]
      env:
        - name: "username"
          value: "admin"
        - name: "password"
          value: "123456"

更新pod

[root@k8s-master test-namespace]# kubectl apply -f pod-test.yaml
pod/test-pod created

进入Pod查看环境变量

/tmp # echo $username
admin
/tmp # echo $password
123456

4.4端口配置

apiVersion: v1
kind: Pod
metadata:
  name: test-pod
  namespace: test
  labels:
    env: test
spec:
  containers:
    - name: nginx # 容器名称
      image: nginx:1.16.1 # 容器需要的镜像地址
      imagePullPolicy: Always # 镜像拉去策略[Always|IfNotPresent|Never]
      ports:
      - containerPort: 8090	# 容器端口
        name: nginx-port	# 端口名称
        protocol: TCP		# 端口协议
    - name: busybox # 容器名称
      image: busybox:1.30 # 容器需要的镜像地址
      command: ["/bin/sh","-c","touch /tmp/hello.txt;while true;do /bin/echo $(date +%T) >> /tmp/hello.txt;sleep 3;done;"]
      env:
        - name: "username"
          value: "admin"
        - name: "password"
          value: "123456"

更新pod

[root@k8s-master test-namespace]# kubectl apply -f pod-test.yaml
pod/test-pod created

查看端口
第二讲《k8s资源介绍:Namespace与Pod 》_第4张图片

你可能感兴趣的:(k8s专题分享,kubernetes,docker,容器)