初始化容器

初始化容器的用途

  1. init容器可以包含一些安装过程中应用容器不存在的实用工具或者个性化代码
  2. init容器可以安全的运行的这些工具,避免这些工具导致应用镜像的安全性降低
  3. init容器可以以root身份运行,执行一些高权限命令
  4. init容器相关操作执行完成后即退出,不会给业务容器带来安全隐患

在主应用启动之前,做一些初始化的操作,比如创建文件、修改内核参数、等待依赖程序启动或者其它需要在主程序启动之前需要做的工作。

在写配置文件时,initContainers和containers得是同级别

初始化容器和普通容器的区别

init容器与普通的容器非常像,除了如下几点:

  1. 它们总是运行到完成
  2. 上一个运行完成才会运行下一个
  3. 如果pod的init容器运行失败,kubernetes会不断的重启该pod,直到init容器成功为止,但是Pod对应的restartPolicy值为Nerver,kubernetes不会重新启动该Pod
  4. init容器不支持lifecycle、livenessProbe、readinessProbe和startupProbe

示例

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myjob
  namespace: default
  labels:
    app: myjob
spec:
  selector:
    matchLabels:
      app: myjob
  replicas: 1
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: myjob
    spec:
      initContainers:
      - name: fix-permissions
        image: busybox
        command: ["sh","-c","chown -R root:root /usr/share/elasticsearch/data"]
        securityContext:
          privileged: true
        volumeMounts:
        - name: data
          mountPath: /usr/share/elasticsearch/data
      - name: increse-fd-ulimit
        image: busybox
        command: ["sysctl","-w","vm.max_map_count=262144"]
        securityContext:
          privileged: true
      - name: myjob
        image: myjob:latest
        imagePullPolicy: IfNotPresent
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
          limits:
            cpu: 100m
            memory: 100Mi
        livenessProbe:
          tcpSocket:
            port: 80
          initialDelaySeconds: 5
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 3
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /_status/healthz
            port: 80
          initialDelaySeconds: 5
          timeoutSeconds: 2
          successThreshold: 1
          failureThreshold: 3
          periodSeconds: 10
        env:
        - name: ACCEPT_EULA
          value: "Y"
        - name: DB_HOST
          valueFrom:
            configMapKeyRef:
              name: myjob
              key: DB_HOST
        - name: DB_HOST
          valueFrom:
            secretKeyRef:
              name: myjob
              key: MSSQL_SA_PASSWORD
        ports:
        - containerPort: 80
          name: myjob
        volumeMounts:
        - name: localtime
          mountPath: /etc/localtime
      volumes:
        - name: localtime
          hostPath:
            path: /usr/share/zoneinfo/Asia/Taipei
      restartPolicy: Always

 

posted @ 2024-03-27 14:44  羊脂玉净瓶  阅读(7)  评论(0)    收藏  举报