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

K8s Pod Lifecycle, Init Containers & Sidecars

Choyeon
Choyeon
Sep 9, 2026 1 min read 378 Views
510 words 3,120 chars Updated Nov 8, 2026
K8s Pod Lifecycle, Init Containers & Sidecars
Table of contents

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

About the author

Poll

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

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

Comments (4)

0 / 3000
机器学习萌新
机器学习萌新Sep 30, 2026

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

开源贡献者小Z
开源贡献者小Zoss-z.devSep 29, 2026

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

自由撰稿人阿秋
自由撰稿人阿秋qiuwrites.blogSep 29, 2026

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

咖啡与代码
咖啡与代码Sep 29, 2026

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

Related posts

Zero Trust Security Architecture: Never Trust, Always Verify

Zero Trust Security Architecture: Never Trust, Always Verify

Zero Trust security model primer: built on "never trust, always verify" and dismantles traditional VPN-equals-trusted perimeter thinking. Six pillars explained — identity (MFA/SAML), device health checks, least-privilege RBAC, microsegmentation mTLS, continuous trust scoring, observable audit trail — with implementation roadmap.

1 min read
Rust Ownership & Borrowing: Lifetimes Explained

Rust Ownership & Borrowing: Lifetimes Explained

Master Rust's most unique concepts: ownership rules, mutable/immutable borrowing constraints, lifetime annotations. Compile-error examples + fixes to think like the Borrow Checker for safe zero-cost code.

1 min read
Linux Performance Tuning: perf, bpftrace & BCC

Linux Performance Tuning: perf, bpftrace & BCC

Tune Linux across CPU/mem/IO/net: perf for CPU sampling, bpftrace one-liners for kernel tracepoints, BCC classics biolatency/offcputime to pinpoint production bottlenecks with real incident methodology.

1 min read
PostgreSQL Query Optimization Techniques

PostgreSQL Query Optimization Techniques

Master PostgreSQL optimization: EXPLAIN ANALYZE plans, choosing index types (B-tree/GIN/BRIN), updating statistics, tuning joins, and partitioned table design for maximum performance.

1 min read
Docker Compose Production Deployment Guide

Docker Compose Production Deployment Guide

Deep dive into Docker Compose production best practices: multi-stage builds, health checks, resource limits, logging, network isolation, and secrets management for reliable container deployments.

1 min read
Test Pyramid: Unit/Integration/E2E Ratios & Implementation

Test Pyramid: Unit/Integration/E2E Ratios & Implementation

Systematic test pyramid breakdown: bottom unit tests (many, fast, mock isolated), middle integration tests (real service/db/message interaction), top E2E tests (few, critical user flows). Recommended ratio 70/20/10, with coverage metrics and implementation playbook.

1 min read