提示:本网站现在为维护调试状态

K8s Pod ライフサイクル + Init コンテナ + Sidecar

Choyeon
Choyeon
2026年9月9日 1 分で読了 377 閲覧
510 字 3,120 文字 更新日 2026年11月8日
K8s Pod ライフサイクル + Init コンテナ + Sidecar
目次

K8s Pod Lifecycle, Init Containers & Sidecars

Pod is K8s' smallest schedulable unit. Master state transitions and inter-container patterns for reliability. Subtle differences in startup/shutdown ordering and probe configs directly affect production behavior.

Pod Lifecycle State Machine

Creation → PodScheduled → Init Containers run serially → Main containers start → PostStart hooks → readiness must pass before service sends traffic → liveness failures trigger restart → deletion sends SIGTERM → preStop fires → terminationGracePeriodSeconds hard kill.

apiVersion: v1
kind: Pod
metadata: { name: web-app-pod, labels: { app: web } }
spec:
  terminationGracePeriodSeconds: 60
  shareProcessNamespace: true
  serviceAccountName: web-sa
  initContainers:
    - name: wait-for-db
      image: bitnami/postgresql:16
      command: ["/bin/sh", "-c", "until pg_isready -h postgres -p 5432 -U app; do echo wait; sleep 3; done;"]
    - name: migrate-db
      image: registry.example.com/app:${APP_VERSION}
      command: ["alembic", "upgrade", "head"]
      envFrom: [{ configMapRef: { name: web-config } }]
      volumeMounts: [{ name: app-secret, mountPath: /run/secrets, readOnly: true }]
    - name: fetch-assets
      image: amazon/aws-cli
      command: ["aws", "s3", "sync", "s3://app-assets/static/", "/var/www/static/", "--delete"]
      volumeMounts: [{ name: static-assets, mountPath: /var/www/static }]
  containers:
    - name: app
      image: registry.example.com/app:${APP_VERSION}
      ports: [{ containerPort: 8000, name: http }]
      lifecycle:
        postStart: { exec: { command: ["/bin/sh", "-c", "echo started >> /var/log/app/boot.log"] } }
        preStop:
          exec: { command: ["/bin/sh", "-c", "sleep 5; kill -SIGTERM 1; while pidof app >/dev/null; do sleep 1; done;"] }
      readinessProbe: { httpGet: { path: /health/ready, port: http }, initialDelaySeconds: 3, periodSeconds: 5 }
      livenessProbe: { httpGet: { path: /health/live, port: http }, initialDelaySeconds: 15, periodSeconds: 20, failureThreshold: 3 }
      startupProbe: { httpGet: { path: /health/started, port: http }, periodSeconds: 5, failureThreshold: 30 }
      resources:
        requests: { cpu: 100m, memory: 256Mi }
        limits:   { cpu: 1000m, memory: 1Gi }
      volumeMounts:
        - { name: static-assets, mountPath: /app/static, readOnly: true }
        - { name: app-logs, mountPath: /var/log/app }
    - name: envoy-sidecar
      image: envoyproxy/envoy:v1.30
      lifecycle:
        preStop: { exec: { command: ["/bin/sh", "-c", "curl -X POST http://localhost:15000/healthcheck/fail; sleep 10;"] } }
    - name: fluentbit-sidecar
      image: fluent/fluent-bit:3.0
      volumeMounts: [{ name: app-logs, mountPath: /var/log/app, readOnly: true }]
  volumes:
    - { name: static-assets, emptyDir: {} }
    - { name: app-logs, emptyDir: {} }
    - { name: app-secret, secret: { secretName: web-secret } }

Init Containers and Sidecar Patterns

Init Containers execute in order; only when all succeed do mains start. Perfect for DB waits, migrations, asset pulls. Sidecars share network/volumes with the main app, providing non-intrusive proxies (istio/envoy) or log shipping (fluentbit).

Container Type Startup Timing Relationship to App Use Cases
Init Container Before main, serialized Runs-once success required DB waits, migrations
Sidecar Parallel with main Same lifecycle, exits together Service Mesh proxy
Sidecar Parallel with main Same lifecycle Log collector fluentbit
Main App After init succeeds Business process Web API server
Ephemeral kubectl debug any time Temporary injection Debug broken pods

Best Practices

Always add startupProbe for slow-booting apps. Sleep a few seconds in preStop to let endpoints deregister from services before killing process - prevents race where traffic arrives as app dies. Readiness should check DB dependencies, not just process liveness.

X微博Telegram

筆者について

投票

你最希望 Rosetta 优先加入哪项功能?

社区投票(演示数据,可后台删除)

コメント (4)

0 / 3000
机器学习萌新
机器学习萌新2026年9月30日

代码示例里那个 SQL 查询是不是应该加个 LIMIT?不然数据量大的时候全表扫描会很慢哦。

开源贡献者小Z
开源贡献者小Zoss-z.dev2026年9月29日

请问一下,文中提到的连接池配置,如果是在高并发场景下,一般设置多少比较合适?

自由撰稿人阿秋
自由撰稿人阿秋qiuwrites.blog2026年9月29日

作为一个刚入行的后端新人,这篇文章帮我理清了好多概念,谢谢博主持续输出高质量内容!

咖啡与代码
咖啡与代码2026年9月29日

哈哈,楼主的踩坑经历和我一模一样!我当时就是没注意到这个配置,排查了整整两天,看到这篇文章泪目了。

関連記事

Zero Trust セキュリティアーキテクチャ入門:決して信用せず、常に検証

Zero Trust セキュリティアーキテクチャ入門:決して信用せず、常に検証

Zero Trust セキュリティモデル体系入門:「決して信用せず、常に検証」を原則に、伝統的 VPN=内部信頼の境界防衛思考を打ち砕く。身元認証(MFA/SAML)、端末健康チェック、最小権限RBAC、マイクロセグメンテーションmTLS、継続的信用スコア、可視化監査ログの6本柱を解説、実装ロードマップ付き。

1 分で読了
Rust 所有権と借用:ライフタイム完全理解

Rust 所有権と借用:ライフタイム完全理解

Rustの最難解概念をマスター:所有権ルール、可変/不変借用の制約、ライフタイム注釈。コンパイルエラー例と修正を通してBorrow Checkerの思考法を習得。

1 分で読了
Linux 性能チューニング:perf + bpftrace + BCC

Linux 性能チューニング:perf + bpftrace + BCC

CPU/メモリ/IO/ネットワーク4次元:perfによるサンプリング、bpftraceワンライナー、BCC biolatency/offcputimeを用いた本番ボトルネック特定とトラブルシューティング。

1 分で読了
PostgreSQL クエリ最適化テクニック

PostgreSQL クエリ最適化テクニック

PostgreSQLクエリ最適化:EXPLAIN ANALYZEの読み方、インデックス種別選択、統計情報更新、結合戦略調整、パーティションテーブル設計。

1 分で読了
Docker Compose 本番デプロイ実践

Docker Compose 本番デプロイ実践

Docker Composeの本番環境ベストプラクティス:マルチステージビルド、ヘルスチェック、リソース制限、ログ設定、ネットワーク分離、シークレット管理を解説。

1 分で読了
テストピラミッド:単体/結合/E2E 比率と実践

テストピラミッド:単体/結合/E2E 比率と実践

テストピラミッド体系解説:下層 単体テスト(多数・高速・Mock分離)、中層 結合テスト(実DB/メッセージ協調)、上層 E2E(少数・重要ユーザーフロー)。推奨比率 70/20/10、カバレッジ指標と実践ガイド。

1 分で読了