六、万物基础-容器

六、万物基础-容器

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

k8s的Pod是最小单位,Pod中容器的配置需要注意以下常用的

Pod里面的容器内容可以写的东西

kubectl explain pod.spec.containers
   args	<[]string>


   command	<[]string>
     Entrypoint array. Not executed within a shell. The docker image's
     ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME)
     are expanded using the container's 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 Pod's 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 container's termination
     message will be written is mounted into the container's 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 container's filesystem. Cannot be updated.

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

1、镜像

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-L7cUhD4v-1657518817633)(images/Kubernetes/image-20211109145840888.png)]

docker pull redis    
docker.io/library/redis:latest

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

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

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

下载私有仓库镜像

kubectl explain pod.spec.imagePullSecrets

https://kubernetes.io/zh/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod

#这个秘钥默认在default名称空间,不能被hello名称空间共享
kubectl create secret -n hello docker-registry my-aliyun \
  --docker-server=registry.cn-hangzhou.aliyuncs.com \
  --docker-username=forsumlove \
  --docker-password=11223344
  
apiVersion: v1
kind: Pod
metadata:
  name: foo
spec:
  containers:
    - name: foo
      image: registry.cn-zhangjiakou.aliyuncs.com/docker/java-img:v1.0
  imagePullSecrets:
    - name: mydocker

2、启动命令

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7sXR6pBP-1657518817634)(images/Kubernetes/1619532343232.png)]

kind: Pod
apiVersion: v1
metadata:
  name: my-command-test
  namespace: hello
spec:  # 指定规格信息
  containers:  # 指定要启动一个什么样的容器
  - image: nginx  #指定镜像。默认会启动一个nginx容器
    name: command-test  
    command:    # 以这里为准  ## redis 主节点  redis 启动命令
      - /bin/sh
      - -c
      - "echo $(msg);sleep 3600;"
    env:
      - name: msg
        value: "hello msg"   ## Dockerfile  CMD  能用到
    # 直接覆盖容器的默认命令  Dockerfile  ENTRYPOINT CMD 指定容器的启动命令

3、环境变量

env指定即可

kind: Pod
apiVersion: v1
metadata:
  name: my-mysql
  namespace: hello
  labels:
     aa: bb
     bb: dd
spec:  # 指定规格信息
  containers:  # 指定要启动一个什么样的容器
  ## docker run -e = env   --name=name -v=volumeMounts -w /usr/  /bin/bash
  - image: mysql:5.7.34  #指定镜像
    name: mysql  #容器的名字 数据就在容器里面  docker run mysql.
    # ports: #指定容器暴露哪些端口  -p  
    env:
     - name: MYSQL_ROOT_PASSWORD
       value: "123456"
     - name: MYSQL_DATABASE
       value: "test"

4、生命周期容器钩子

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

  • PostStart

    此钩子函数在容器创建后将立刻执行。但是,并不能保证该钩子函数在容器的 ENTRYPOINT 之前执行。该钩子函数没有输入参数。

  • PreStop

    此钩子函数在容器被 terminate(终止)之前执行,例如:

    • 通过接口调用删除容器所在 Pod
    • 某些管理事件的发生:健康检查失败、资源紧缺等

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

kubectl explain pod.spec.containers.lifecycle

https://kubernetes.io/zh/docs/concepts/containers/container-lifecycle-hooks/#container-hooks

# vi k8s-lifecycle_hook.yaml

kind: Pod
apiVersion: v1
metadata:
  name: my-life
  namespace: hello
  labels:
     aa: bb
     bb: dd
spec:  # 指定规格信息
  containers:  # 指定要启动一个什么样的容器
  - image: nginx  #指定镜像
    name: nginx  #容器的名字 数据就在容器里面  docker run mysql.
    lifecycle:
      postStart:
        # httpGet:
        #   port: 30935
        #   path: "http://192.168.169.160:30935/postStart"
        httpGet: 
           host: "192.168.85.200 "
           path: "/postStart"
           port: 80
           scheme: HTTP

        # exec:  容器创建之后,这个钩子程序执行一个命令  echo 1111
        # httpGet: 容器创建之后,这个钩子程序发送一个httpGet 请求
        # tcpSocket: 容器创建之后,这个钩子程序连上一个TCP端口
      preStop:  ## 
        httpGet: 
           host: "192.168.85.200 "
           path: "/preStop"
           port: 80
           scheme: HTTP
apiVersion: v1
kind: Pod
metadata:
  name: lifecycle-demo
spec:
  containers:
  - name: lifecycle-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;"]
  • Kubernetes 在容器启动后立刻发送 postStart 事件,但是并不能确保 postStart 事件处理程序在容器的 EntryPoint 之前执行。postStart 事件处理程序相对于容器中的进程来说是异步的(同时执行),然而,Kubernetes 在管理容器时,将一直等到 postStart 事件处理程序结束之后,才会将容器的状态标记为 Running。
  • Kubernetes 在决定关闭容器时,立刻发送 preStop 事件,并且,将一直等到 preStop 事件处理程序结束或者 Pod 的 --grace-period 超时,才删除容器

5、资源限制

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"

更多内容

更多详细内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小薛博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值