#云原生征文#深入万物基础-容器

Posted Lansonli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#云原生征文#深入万物基础-容器相关的知识,希望对你有一定的参考价值。


深入万物基础-容器

一、思考

我们在k8s里面的容器和docker的容器有什么异同?

其实docker之前有自己的一套编排软件:docker swarm
它可以在多台主机中创建一个docker集群,但是也仅限于此了,docker在很早就放弃了这个项目。
docker machine 是配合swarm的一个预处理工具

k8s全称:kubernetes,因为中间有8个字母,所以简称k8s,是谷歌公司开发的一款容器编排工具,占据了80%以上的市场份额。

k8s的Pod是最小单位,Pod中容器的配置需要注意以下常用的 Pod里面的容器内容可以写的东西


   args    <[]string>

   command    <[]string>
     Entrypoint array. Not executed within a shell. The docker images
     ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME)
     are expanded using the containers environment. If a variable cannot be
     resolved, the reference in the input string will be unchanged. The
     $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME).
     Escaped references will never be expanded, regardless of whether the
     variable exists or not. Cannot be updated. More info:
​      https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell​

   env    <[]Object>
     容器要用的环境变量

   envFrom    <[]Object>
     List of sources to populate environment variables in the container. The
     keys defined within a source must be a C_IDENTIFIER. All invalid keys will
     be reported as an event when the container is starting. When a key exists
     in multiple sources, the value associated with the last source will take
     precedence. Values defined by an Env with a duplicate key will take
     precedence. Cannot be updated.

   image    <string>
        写镜像的名字

   imagePullPolicy    <string>
        下载策略: 
        Always:总是去下载: 【默认】  
            先看网上有没有,有了就下载,(本机也有,docker就相当于不用下载了)
        Never:总不去下载,一定保证当前Pod所在的机器有这个镜像 ;直接看本机
        IfNotPresent:如果本机没有就去下载;先看本机,再看远程

   lifecycle    <Object>
      生命周期钩子

   livenessProbe    <Object>
     Periodic probe of container liveness. Container will be restarted if the
     probe fails. Cannot be updated. More info:
​      https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes​

   name    <string> -required-
           容器的名字

   ports    <[]Object>
      端口:

   readinessProbe    <Object>
     Periodic probe of container service readiness. Container will be removed
     from service endpoints if the probe fails. Cannot be updated. More info:
​      https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes​

   resources    <Object>
     Compute Resources required by this container. Cannot be updated. More info:
​      https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/​

   securityContext    <Object>
     Security options the pod should run with. More info:
     https://kubernetes.io/docs/concepts/policy/security-context/ More info:
​      https://kubernetes.io/docs/tasks/configure-pod-container/security-context/​

   startupProbe    <Object>
     StartupProbe indicates that the Pod has successfully initialized. If
     specified, no other probes are executed until this completes successfully.
     If this probe fails, the Pod will be restarted, just as if the
     livenessProbe failed. This can be used to provide different probe
     parameters at the beginning of a Pods lifecycle, when it might take a long
     time to load data or warm a cache, than during steady-state operation. This
     cannot be updated. More info:
​      https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes​

   stdin    <boolean>
     Whether this container should allocate a buffer for stdin in the container
     runtime. If this is not set, reads from stdin in the container will always
     result in EOF. Default is false.

   stdinOnce    <boolean>
     Whether the container runtime should close the stdin channel after it has
     been opened by a single attach. When stdin is true the stdin stream will
     remain open across multiple attach sessions. If stdinOnce is set to true,
     stdin is opened on container start, is empty until the first client
     attaches to stdin, and then remains open and accepts data until the client
     disconnects, at which time stdin is closed and remains closed until the
     container is restarted. If this flag is false, a container processes that
     reads from stdin will never receive an EOF. Default is false

   terminationMessagePath    <string>
     Optional: Path at which the file to which the containers termination
     message will be written is mounted into the containers filesystem. Message
     written is intended to be brief final status, such as an assertion failure
     message. Will be truncated by the node if greater than 4096 bytes. The
     total message length across all containers will be limited to 12kb.
     Defaults to /dev/termination-log. Cannot be updated.

   terminationMessagePolicy    <string>
     Indicate how the termination message should be populated. File will use the
     contents of terminationMessagePath to populate the container status message
     on both success and failure. FallbackToLogsOnError will use the last chunk
     of container log output if the termination message file is empty and the
     container exited with an error. The log output is limited to 2048 bytes or
     80 lines, whichever is smaller. Defaults to File. Cannot be updated.

   tty    <boolean>
     Whether this container should allocate a TTY for itself, also requires
     stdin to be true. Default is false.

   volumeDevices    <[]Object>
     volumeDevices is the list of block devices to be used by the container.

   volumeMounts    <[]Object>
     Pod volumes to mount into the containers filesystem. Cannot be updated.

   workingDir    <string>
        指定进容器的工作目录


二、镜像

在 Kubernetes 的 Pod 中使用容器镜像之前,我们必须将其推送到一个镜像仓库(或者使用仓库中已经有的容器镜像)。在 Kubernetes 的 Pod 定义中定义容器时,必须指定容器所使用的镜像,容器中的 ​​image​​ 字段支持与 ​​docker​​ 命令一样的语法,包括私有镜像仓库和标签。

#云原生征文#深入万物基础-容器_docker#云原生征文#深入万物基础-容器_docker_02​编辑

如果使用 ​​hub.dokcer.com​​ Registry 中的镜像,可以省略 registry 地址和 registry 端口。例如:​nginx:latest​

Kubernetes中,默认的镜像抓取策略是 ​​IfNotPresent​​,使用此策略,kubelet在发现本机有镜像的情况下,不会向镜像仓库抓取镜像。如果您期望每次启动 Pod 时,都强制从镜像仓库抓取镜像,可以尝试如下方式:

  • 设置 container 中的imagePullPolicyAlways
  • 省略imagePullPolicy 字段,并使用 :latest tag 的镜像
  • 省略imagePullPolicy 字段和镜像的 tag
  • 激活AlwaysPullImages 管理控制器
docker pull redis 
docker.io/library/redis:latest

#云原生征文#深入万物基础-容器_docker_03下载私有仓库镜像

#这个秘钥默认在default名称空间,不能被hello名称空间共享
kubectl create secret -n hello docker-registry my-aliyun \\
--docker-server=registry.cn-hangzhou.aliyuncs.com \\
--docker-username=lansonli \\
--docker-password=lansonli123456789

#云原生征文#深入万物基础-容器_docker_04

apiVersion: v1
kind: Pod
metadata:
name: foo
spec:
containers:
- name: foo
image: registry.cn-zhangjiakou.aliyuncs.com/atguigudocker/atguigu-java-img:v1.0
imagePullSecrets:
- name: mydocker

#云原生征文#深入万物基础-容器_docker_05

三、启动命令

#云原生征文#深入万物基础-容器_k8s_06#云原生征文#深入万物基础-容器_docker_07​编辑

四、环境变量

env指定即可

五、生命周期容器钩子

Kubernetes中为容器提供了两个 hook(钩子函数):

  • ​PostStart​
    此钩子函数在容器创建后将立刻执行。但是,并不能保证该钩子函数在容器的ENTRYPOINT 之前执行。该钩子函数没有输入参数。
  • ​PreStop​
    此钩子函数在容器被 terminate(终止)之前执行,例如:
  • 通过接口调用删除容器所在 Pod
  • 某些管理事件的发生:健康检查失败、资源紧缺等

如果容器已经被关闭或者进入了 ​​completed​​ 状态,preStop 钩子函数的调用将失败。该函数的执行是同步的,即,kubernetes 将在该函数完成执行之后才删除容器。该钩子函数没有输入参数。


apiVersion: v1
kind: Pod
metadata:
name: lansonli-demo
spec:
containers:
- name: lansonli-demo-container
image: alpine
command: ["/bin/sh", "-c", "echo hello; "]
volumeMounts:
- name: mount1
mountPath: /app
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "echo world;"]
preStop:
exec:
command: ["/bin/sh","-c","echo 66666;"]

#云原生征文#深入万物基础-容器_k8s_08

  • Kubernetes 在容器启动后立刻发送postStart 事件,但是并不能确保 postStart 事件处理程序在容器的 EntryPoint 之前执行。postStart 事件处理程序相对于容器中的进程来说是异步的(同时执行),然而,Kubernetes 在管理容器时,将一直等到 postStart 事件处理程序结束之后,才会将容器的状态标记为 Running。
  • Kubernetes 在决定关闭容器时,立刻发送preStop 事件,并且,将一直等到 preStop 事件处理程序结束或者 Pod 的 --grace-period 超时,才删除容器

六、资源限制

pods/qos/qos-pod.yaml 

apiVersion: v1
kind: Pod
metadata:
name: qos-demo
namespace: qos-example
spec:
containers:
- name: qos-demo-ctr
image: nginx
resources:
limits: # 限制最大大小 -Xmx
memory: "200Mi"
cpu: "700m"
# 启动默认给分配的大小 -Xms
requests:
memory: "200Mi"
cpu: "700m"

#云原生征文#深入万物基础-容器_k8s_09

kubectl describe 可用来排错的,查看资源的状态


【本文正在参加云原生有奖征文活动】,活动链接:https://ost.51cto.com/posts/12598


以上是关于#云原生征文#深入万物基础-容器的主要内容,如果未能解决你的问题,请参考以下文章

#云原生征文#深入RCRSDaemonSetStatefulSet

#云原生征文#深入了解k8s的Pod

#云原生征文#深入Kubernetes(k8s)概念

#云原生征文#深入了解Kubernetes(k8s)Service

万物互联应用现代化云原生新范式,华为云为数字化转型提供最优解

猿创征文 | 云原生领域之容器日常使用工具推荐