首页/云/Kubernetes 速查/Init 容器(initContainers)

Init 容器(initContainers)

在主容器启动前按顺序逐个运行到成功退出的专用容器:做依赖等待、数据初始化、权限准备;失败会阻塞并重试。

Kubernetes 速查云更新于 2026-10-12

示例

示例
spec:
  initContainers:
    - name: wait-db
      image: busybox:1.36
      command: ['sh', '-c', 'until nc -z db 5432; do echo waiting; sleep 2; done']
    - name: init-data
      image: registry.example.com/tools:1.2
      command: ['sh', '-c', 'cp -n /seed/* /data/ || true']
      volumeMounts:
        - name: data
          mountPath: /data
  containers:
    - name: app
      image: registry.example.com/app:1.26.0
      volumeMounts:
        - name: data
          mountPath: /data

查看日志

查看日志
kubectl logs web-x -c wait-db
kubectl logs web-x -c init-data --previous
kubectl describe pod web-x | grep -A12 'Init Containers'
Init 容器串行执行;每个必须是退出码 0 才算成功;Pod 状态里 Init:0/2 之类即进度。

易错点

  • Init 容器一直不退出会卡在 Init 阶段,Pod 不会 Ready,先看它的日志而不是主容器
  • Init 卡住后重启策略决定重试方式,CrashLoop 发生在 init 上时 describe 里显示 Init:CrashLoopBackOff

数据来源与参考

  • Kubernetes 官方文档 · Init Containers
​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌