Skip to content

Kubernetes チートシート

デプロイとスケーリングを自動化するコンテナオーケストレーション基盤。

01

はじめに

kubectl の基本

kubectl は Kubernetes の CLI です。get はリソースの一覧、create は新規作成、expose はサービスの作成、scale はレプリカ数の変更です。describe でリソースの詳細情報が得られます。

kubernetes
# cluster info
kubectl cluster-info

# list nodes
kubectl get nodes

# list pods (all namespaces)
kubectl get pods --all-namespaces

# create a deployment
kubectl create deployment nginx --image=nginx

# expose deployment as service
kubectl expose deployment nginx --port=80 --type=LoadBalancer

# scale deployment
kubectl scale deployment nginx --replicas=3

# get detailed info
kubectl describe pod <pod-name>

# view logs
kubectl logs <pod-name>

出力の整形

-o フラグが出力を制御します。yaml/json はリソース spec の全体を表示します。jsonpath と custom-columns はスクリプト向けに特定のフィールドを取り出します。-w はライブの変化を監視します。スクリプトでは --no-headers で列名を落としましょう。

kubernetes
# wide format (more columns)
kubectl get pods -o wide

# YAML output
kubectl get pod nginx -o yaml

# JSON output
kubectl get pod nginx -o json

# jsonpath (extract specific fields)
kubectl get pods -o jsonpath='{.items[*].metadata.name}'

# custom columns
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase

# show labels
kubectl get pods --show-labels

# watch for changes
kubectl get pods -w

コンテキストと設定

コンテキストはクラスタのアドレス、ユーザー認証情報、名前空間をまとめたものです。kubeconfig ファイル(デフォルトは ~/.kube/config)に保存されます。KUBECONFIG 環境変数で複数のファイルを組み合わせられ、多数のクラスタを管理できます。

kubernetes
# view current config
kubectl config view

# list contexts
kubectl config get-contexts

# switch context
kubectl config use-context my-cluster

# set default namespace for current context
kubectl config set-context --current --namespace=dev

# show current context
kubectl config current-context

# KUBECONFIG with multiple files
export KUBECONFIG=~/.kube/config:~/.kube/prod-config

explain と API リソース

api-resources はクラスタが対応するリソースを一覧します。explain は任意のリソースの OpenAPI スキーマを表示します。ターミナルを離れずに YAML を書ける貴重な機能です。--recursive でネストした全構造を出力できます。

kubernetes
# list all resource types
kubectl api-resources

# list namespaced vs cluster-scoped
kubectl api-resources --namespaced=true
kubectl api-resources --namespaced=false

# explain a resource's fields
kubectl explain pod
kubectl explain pod.spec.containers
kubectl explain deployment.spec.strategy

# explain with recursion (all nested fields)
kubectl explain pod --recursive

# include description
kubectl explain pod.spec.containers.resources --api-version=apps/v1

ドライランと YAML 生成

--dry-run=client -o yaml は、命令的なコマンドからマニフェストの雛形を作る標準的な方法です。--dry-run=server は実物の apiserver(アドミッション Webhook、スキーマ)に対して検証し、保存はしません。宣言的 YAML の出発点として最適です。

kubernetes
# generate YAML without applying
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml

# pipe generated YAML straight to a file
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > nginx.yaml

# apply the generated manifest
kubectl apply -f nginx.yaml

# dry-run against the server (validates with apiserver)
kubectl apply -f nginx.yaml --dry-run=server

# generate a service from a deployment
kubectl create service clusterip my-svc --tcp=80:80 --dry-run=client -o yaml

ヘルプと補完

すべての kubectl コマンドは例付きの --help に対応しています。シェル補完は打鍵量を大幅に減らし、サブコマンドも見つけられます。k=kubectl のエイリアスは実務者にはほぼ標準です。補完と組み合わせるのが最良の体験です。

kubernetes
# top-level help
kubectl --help

# subcommand help
kubectl create --help
kubectl explain --help

# generate bash completion
kubectl completion bash > /etc/bash_completion.d/kubectl

# zsh completion
source <(kubectl completion zsh)

# alias k=kubectl with completion
alias k=kubectl
complete -o default -F __start_kubectl k

# shorthand: kubectl -> k
echo 'alias k=kubectl' >> ~/.bashrc
02

Pod

Pod マニフェスト

Pod は最小のデプロイ単位で、ネットワークとストレージを共有する 1 つ以上のコンテナを持ちます。Pod 内のコンテナは必ず同じノードに共同スケジューリングされます。Pod を直接作ることはまれで、通常は Deployment や Job を使います。

kubernetes
apiVersion: v1
kind: Pod
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  containers:
    - name: nginx
      image: nginx:1.25
      ports:
        - containerPort: 80
      resources:
        requests:
          cpu: 100m
          memory: 128Mi
        limits:
          cpu: 200m
          memory: 256Mi
  restartPolicy: Always

マルチコンテナ Pod(Sidecar)

複数コンテナの Pod はネットワーク(同じ IP、ポート空間)とボリュームを共有します。よくあるパターン: sidecar(補助)、adapter(出力の変換)、ambassador(プロキシ)。共有の emptyDir ボリュームで、sidecar がメインコンテナの書いたログを読めます。

kubernetes
apiVersion: v1
kind: Pod
metadata:
  name: web-with-logs
spec:
  containers:
    - name: app
      image: nginx
      volumeMounts:
        - name: shared-logs
          mountPath: /var/log/nginx
    - name: log-shipper
      image: busybox
      command: ["sh", "-c", "tail -f /var/log/nginx/access.log"]
      volumeMounts:
        - name: shared-logs
          mountPath: /var/log/nginx
          readOnly: true
  volumes:
    - name: shared-logs
      emptyDir: {}

Pod のライフサイクルとフェーズ

Pod の phase は大まかな状態です(Pending、Running、Succeeded、Failed)。コンテナの状態(Waiting/Running/Terminated)が実際の詳細を示します。たとえば CrashLoopBackOff はコンテナが繰り返し終了している状態です。再起動回数とイベントを調べて診断しましょう。

kubernetes
# pod phases: Pending | Running | Succeeded | Failed | Unknown
kubectl get pod nginx

# show status including container states
kubectl get pod nginx -o jsonpath='{.status}'

# container states: Waiting | Running | Terminated
kubectl describe pod nginx

# common Waiting reasons: ImagePullBackOff, CrashLoopBackOff, CreateContainerConfigError
kubectl get pods --field-selector=status.phase=Pending

# restart count reveals crash loops
kubectl get pods -o jsonpath='{.items[*].status.containerStatuses[*].restartCount}'

Pod の状態とイベント

イベントはリソースの監査ログのようなもので、スケジューリング、イメージ取得、取得エラー、Liveness の失敗などが記録されます。イベントは失効します(デフォルトで約 1 時間)ので、デバッグ中に取り込んでおきましょう。describe はイベントをリソース spec とまとめて表示し、素早い切り分けに役立ちます。

kubernetes
# full describe (includes Events at the bottom)
kubectl describe pod nginx

# list cluster events sorted by time
kubectl get events --sort-by=.lastTimestamp

# events for a specific namespace
kubectl get events -n default

# watch events live
kubectl get events -w

# filter events by type
kubectl get events --field-selector type=Warning

# events for a specific pod
kubectl get events --field-selector involvedObject.name=nginx

Exec と Port-Forward

exec はコンテナ内でコマンドを実行します。-it はシェル用に TTY を確保します。port-forward はローカルポートを pod/service へトンネルし、公開はしません。手元の PC からデータベースや Web UI をデバッグするのに不可欠です。

kubernetes
# open an interactive shell
kubectl exec -it nginx -- sh

# run a one-off command
kubectl exec nginx -- ls /etc/nginx

# specify container in a multi-container pod
kubectl exec -it web-with-logs -c log-shipper -- sh

# forward a local port to a pod port
kubectl port-forward pod/nginx 8080:80

# forward to a service / deployment
kubectl port-forward svc/nginx 8080:80
kubectl port-forward deployment/nginx 8080:80

# forward to a random local port
kubectl port-forward pod/nginx :80

削除と強制

Deployment/StatefulSet に管理された Pod を削除すると、すぐに代替が作られます。--force --grace-period=0 は TERM シグナルの猶予期間を飛ばし、古いリソースを残すことがあるので、多用は禁物です。Terminating のまま固まる Pod は、finalizer の除去が必要なことが多いです。

kubernetes
# delete a pod (controller will recreate it)
kubectl delete pod nginx

# force delete immediately (bypasses graceful shutdown)
kubectl delete pod nginx --grace-period=0 --force

# delete by label
kubectl delete pods -l app=nginx

# delete all pods in a namespace
kubectl delete pods --all -n default

# delete a pod and wait for it to be gone
kubectl delete pod nginx --wait

# delete with a timeout
kubectl delete pod nginx --timeout=30s
03

Deployment

Deployment マニフェスト

Deployment は ReplicaSet を管理し、宣言的なローリングアップデートとロールバックを提供します。spec.selector は spec.template.metadata.labels と一致しなければなりません。template が展開される Pod spec を定義します。

kubernetes
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:1.25
          ports:
            - containerPort: 80

ローリングアップデート戦略

RollingUpdate(デフォルト)はダウンタイムゼロで Pod を段階的に置き換えます。maxSurge/maxUnavailable が展開の速度と可用性を制御します。Recreate は新しい Pod を作る前に既存をすべて停止します。2 つのバージョンを同時に実行できないアプリ(例: 単一ボリュームの書き手)で使います。

kubernetes
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 10
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 25%        # extra pods above replicas during update
      maxUnavailable: 25%  # pods allowed down during update
  # alternative: recreate (kills all, then starts new)
  # strategy:
  #   type: Recreate
  selector:
    matchLabels:
      app: nginx
  template:

ロールバック

Pod テンプレートの変更のたびに ReplicaSet のリビジョンが作られます。undo でトラフィックを前の ReplicaSet に戻せます。pause はカナリア更新の合間に複数の修正を入れられます。変更理由の追跡には --record(非推奨)か annotation を使います。

kubernetes
# view rollout history
kubectl rollout history deployment/nginx

# see details of a specific revision
kubectl rollout history deployment/nginx --revision=2

# undo to the previous revision
kubectl rollout undo deployment/nginx

# undo to a specific revision
kubectl rollout undo deployment/nginx --to-revision=2

# pause/resume a rollout (for canary pauses)
kubectl rollout pause deployment/nginx
kubectl rollout resume deployment/nginx

# check rollout status
kubectl rollout status deployment/nginx

スケールと HPA

HPA は CPU/メモリやカスタムメトリクスに基づいてレプリカ数をスケールします。CPU/メモリには metrics-server が必要です。minReplicas と maxReplicas がスケーリングの範囲を決めます。v2 API は複数メトリクスと挙動の制御(スケールダウンの安定化)に対応しています。

kubernetes
# scale manually
kubectl scale deployment/nginx --replicas=5

# horizontal pod autoscaler (CPU target)
kubectl autoscale deployment nginx --min=2 --max=10 --cpu-percent=80

# list HPA
kubectl get hpa

# HPA manifest (v2 with custom metrics)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: nginx
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: nginx
  minReplicas: 2
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 80

イメージ更新と再起動

set image は新しい ReplicaSet を作りローリングアップデートします。rollout restart は最新イメージの取得や設定の反映を最もきれいに行う方法で、同じ spec の新しい ReplicaSet を作ります。edit は $EDITOR を開いてその場で修正できます。

kubernetes
# update container image
kubectl set image deployment/nginx nginx=nginx:1.26

# update from a specific container
kubectl set image deployment/nginx container=nginx:1.26 --record

# trigger a rollout restart (same image, recreate pods)
kubectl rollout restart deployment/nginx

# edit a deployment in editor
kubectl edit deployment/nginx

# patch a single field
kubectl patch deployment/nginx -p '{"spec":{"replicas":5}}'

# apply a manifest change
kubectl apply -f nginx-deployment.yaml

Deployment の状態

Deployment は複数の ReplicaSet を所有し、アクティブなのは 1 つだけ(replicas>0)です。古い ReplicaSet はロールバックのためにレプリカ数をゼロにします。pod-template-hash ラベルが各 Pod にリビジョンを付けます。status.conditions で Available、Progressing、ReplicaFailure を確認しましょう。

kubernetes
# deployment status
kubectl get deployment nginx

# watch rollout
kubectl rollout status deployment/nginx

# show ReplicaSets owned by the deployment
kubectl get rs -l app=nginx

# show pods across all revisions
kubectl get pods -l app=nginx --show-labels

# pod-template-hash label distinguishes revisions
# kubectl get pods -l app=nginx,pod-template-hash=xxxx

# conditions: Available, Progressing, ReplicaFailure
kubectl get deployment nginx -o jsonpath='{.status.conditions}'
04

Service

Service の種類

Service は Pod の集合にまたがってロードバランスする、安定した IP/DNS を提供します。ClusterIP はデフォルト(クラスタ内のみ)。NodePort と LoadBalancer は外部に公開します。ExternalName はプロキシではなく DNS のエイリアスです。

kubernetes
# four service types:
# - ClusterIP (default): reachable inside the cluster
# - NodePort: exposed on each node's IP at a static port
# - LoadBalancer: cloud-provisioned external LB
# - ExternalName: DNS CNAME to an external host

# quick create
kubectl expose deployment nginx --port=80 --type=ClusterIP
kubectl expose deployment nginx --port=80 --type=NodePort
kubectl expose deployment nginx --port=80 --type=LoadBalancer

# external name (no proxying, pure DNS)
kubectl create service externalname my-svc --external-name=db.example.com

ClusterIP Service

ClusterIP はクラスタ内の安定した仮想 IP と DNS 名を与えます。selector が Pod のラベルに一致し、kube-proxy が iptables/IPVS をプログラムしてエンドポイント間をロードバランスします。名前解決は <svc>.<ns>.svc.cluster.local または単に <svc> です。

kubernetes
apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  type: ClusterIP
  selector:
    app: nginx
  ports:
    - name: http
      port: 80          # service port
      targetPort: 80    # container port
      protocol: TCP
# DNS: nginx.default.svc.cluster.local
# short names also work: nginx, nginx.default
# kube-dns / CoreDNS resolves the service VIP

NodePort Service

NodePort はすべてのノードで同じ静的ポート(30000-32767)を開きます。どのノード:nodePort へのトラフィックも Pod に届きます(kube-proxy が別ノードの Pod へ転送することがあります)。クラウド LB を用意できないときに有用で、HA には外部 LB と組み合わせます。

kubernetes
apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  type: NodePort
  selector:
    app: nginx
  ports:
    - port: 80
      targetPort: 80
      nodePort: 30080   # optional, 30000-32767 range
# reachable at <any-node-ip>:30080
# also still reachable via clusterIP:80

# get assigned nodePort
kubectl get svc nginx -o jsonpath='{.spec.ports[*].nodePort}'

LoadBalancer Service

LoadBalancer はクラウドプロバイダに、ノードを指す外部ロードバランサーの構築を依頼します。externalTrafficPolicy: Local はクライアントの送信元 IP を保持します(SNAT なし)が、ノード間のロードバランスは行いません。STATUS に割り当てられた外部 IP が準備後に表示されます。

kubernetes
apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  type: LoadBalancer
  selector:
    app: nginx
  ports:
    - port: 80
      targetPort: 80
  # cloud-specific annotations
  # annotations:
  #   service.beta.kubernetes.io/aws-load-balancer-type: nlb
  #   service.beta.kubernetes.io/azure-load-balancer-internal: "true"
  # externalTrafficPolicy: Local preserves client IP
  externalTrafficPolicy: Local
# status.ingress shows the external IP/hostname

Headless Service

Headless service(clusterIP: None)には VIP がなく、DNS が Pod の IP を直接返します。StatefulSet に必須で、各 Pod が安定した DNS 名(pod-0.svc、pod-1.svc)を持ちます。バックエンドを自力で発見したいクライアントにも使われます。

kubernetes
apiVersion: v1
kind: Service
metadata:
  name: nginx-headless
spec:
  clusterIP: None       # makes it headless
  selector:
    app: nginx
  ports:
    - port: 80
      targetPort: 80
# DNS returns pod IPs directly (not a VIP)
# A records: nginx-headless.default.svc.cluster.local
#   -> 10.1.0.5, 10.1.0.6, 10.1.0.7
# used by StatefulSet for stable pod DNS:
#   <pod-name>.<svc-name>.default.svc.cluster.local

Endpoints と EndpointSlices

Endpoints/EndpointSlices は実際にトラフィックを受ける Pod の IP を列挙します。Ready な Pod だけが現れます。Service にエンドポイントがない場合、Pod が selector に一致していないか、Ready でないかです。EndpointSlices(v1)は巨大な Service でスケールしやすく、デフォルトになっています。

kubernetes
# view endpoints backing a service
kubectl get endpoints nginx

# endpoint slices (newer, more scalable)
kubectl get endpointslices -l kubernetes.io/service-name=nginx

# endpoints track pods that match the selector
# AND pass readiness checks
kubectl describe endpoints nginx

# a service with no ready pods has no endpoints
# - check pod readiness if traffic is refused
# - EndpointSlices are grouped by address type (IPv4/IPv6)

# manually managed endpoints (selector-less service)
05

ConfigMap

ConfigMap の作成

ConfigMap は機密でない設定をキーと値のペアとして保存します。--from-literal はインラインの値、--from-file はファイル全体の埋め込み(ファイル名がキーになる)です。イメージをリビルドせずに設定を分離できます。

kubernetes
# from literal values
kubectl create configmap app-config \
  --from-literal=LOG_LEVEL=debug \
  --from-literal=ENABLE_FEATURE=true

# from a file (key = filename, value = contents)
kubectl create configmap app-config --from-file=app.properties

# from a directory (one key per file)
kubectl create configmap app-config --from-file=configs/

# from an env file
kubectl create configmap app-config --from-env-file=app.env

# from a file with a custom key
kubectl create configmap app-config --from-file=custom-key=app.properties

ConfigMap マニフェスト

data は文字列の値を持ちます(各キーは環境変数か、マウント時のファイルになります)。複数行の文字列には YAML のブロックスカラー(|)を使います。binaryData はバイナリを受け付け(base64)。ConfigMap 1 個あたりの合計サイズの上限は 1 MiB です。

kubernetes
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  LOG_LEVEL: "debug"
  ENABLE_FEATURE: "true"
  application.yml: |
    server:
      port: 8080
    logging:
      level: debug
binaryData:
  # base64-encoded binary values
  logo.png: iVBORw0KGgoAAAANSUhEUg...

環境変数として利用

envFrom は ConfigMap の全キーを一括で環境変数に注入します。env + configMapKeyRef は個別のキーを選びます。optional: true なら ConfigMap が存在しなくても Pod は起動します。ConfigMap の更新は、実行中の Pod の環境変数には反映されません。

kubernetes
apiVersion: v1
kind: Pod
metadata:
  name: app
spec:
  containers:
    - name: app
      image: myapp:1.0
      env:
        - name: LOG_LEVEL
          valueFrom:
            configMapKeyRef:
              name: app-config
              key: LOG_LEVEL
      envFrom:
        - configMapRef:
            name: app-config      # injects all keys as env vars
              optional: true      # pod starts even if CM missing

ボリュームとして利用

ConfigMap をボリュームとしてマウントすると、各キーがファイルとして現れます。ConfigMap の更新はいずれマウント先のファイルに反映されます(kubelet の同期周期で設定)が、アプリ側が再読み込みする必要があります。subPath マウントは 1 つのキーを固定し、更新されません。

kubernetes
apiVersion: v1
kind: Pod
metadata:
  name: app
spec:
  containers:
    - name: app
      image: myapp:1.0
      volumeMounts:
        - name: config
          mountPath: /etc/config
          readOnly: true
  volumes:
    - name: config
      configMap:
        name: app-config
        items:                       # optional: pick subset
          - key: application.yml
            path: app.yml            # rename file
        defaultMode: 0644
# each ConfigMap key becomes a file under /etc/config

更新と再読み込み

マウントされた ConfigMap ファイルは自動的に更新されます(kubelet の同期後)が、環境変数は Pod の寿命の間不変です。環境変数の変更を反映するには Pod を再起動します。Deployment への設定反映には rollout restart が最もきれいです。

kubernetes
# edit the configmap
kubectl edit configmap app-config

# patch a single key
kubectl patch configmap app-config \
  --type merge -p '{"data":{"LOG_LEVEL":"info"}}'

# mounted files update within ~kubelet sync period (default 60s)
# but env vars do NOT update in running pods

# force pods to pick up new config by rolling them
kubectl rollout restart deployment/app

# verify the new value on a pod
kubectl exec app -- printenv LOG_LEVEL

Immutable ConfigMap

immutable: true を設定すると ConfigMap が凍結され、変更には削除 + 再作成が必要になります。大きな安定した設定では、kubelet と apiserver の watch トラフィックを大幅に削減できます(スケール時の大きな利点)。イメージとともにバージョン管理されるアプリ設定でよく使われます。

kubernetes
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
immutable: true
data:
  LOG_LEVEL: "debug"
# once immutable, the only change allowed is delete + recreate
# benefits: kubelet does not watch it, lower apiserver load
# useful for large, stable configs in production

# make it mutable again
kubectl patch configmap app-config -p '{"immutable":false}'
# (this fails if currently immutable — must delete instead)
06

Secret

Secret の作成

Secret は機密データを base64 エンコードで保存します(デフォルトでは保存時の暗号化はされません。本番では暗号化を有効化しましょう)。任意のデータには generic/Opaque、イメージ取得には docker-registry、Ingress の TLS には tls を使います。Secret の YAML を git にコミットしてはいけません。

kubernetes
# generic (opaque) from literals
kubectl create secret generic db-creds \
  --from-literal=username=admin \
  --from-literal=password='S3cur3!'

# from a file (e.g. SSH key, certificate)
kubectl create secret generic ssh-key --from-file=ssh-privatekey=~/.ssh/id_rsa

# docker registry secret (for private image registries)
kubectl create secret docker-registry regcred \
  --docker-server=registry.example.com \
  --docker-username=user \
  --docker-password=pass \
  [email protected]

# TLS secret from cert/key files
kubectl create secret tls my-tls \
  --cert=fullchain.pem \
  --key=privkey.pem

Secret マニフェスト

data の値は base64 エンコードが必須です(echo -n 'value' | base64)。stringData は平文を受け付ける便宜上のフィールドで、apply 時に data へマージされます。type Opaque がデフォルトで、専用の型(kubernetes.io/tls、kubernetes.io/dockerconfigjson)はキーを検証します。

kubernetes
apiVersion: v1
kind: Secret
metadata:
  name: db-creds
type: Opaque
data:
  username: YWRtaW4=         # base64 of "admin"
  password: UzNjdXIzIQ==     # base64 of "S3cur3!"
# stringData accepts plaintext (auto-encoded on apply)
stringData:
  api-key: "live-key-xyz"
# encode on the command line:
# echo -n 'admin' | base64
# decode:
# echo 'YWRtaW4=' | base64 -d

Secret を環境変数として利用

Secret を環境変数として使う方法は ConfigMap と同じですが、secretKeyRef/secretRef を使います。環境変数は /proc/1/environ やコンテナ内の任意のプロセスから見える点に注意しましょう。高度に機密性の高いデータには、ボリュームマウントが推奨です。

kubernetes
apiVersion: v1
kind: Pod
metadata:
  name: app
spec:
  containers:
    - name: app
      image: myapp:1.0
      env:
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: db-creds
              key: password
      envFrom:
        - secretRef:
            name: db-creds      # injects all keys
              optional: true

Secret をボリュームとして利用

マウントされた Secret は tmpfs(メモリ)ボリュームにファイルとして現れ、ノードのディスクには書き込まれません。defaultMode 0400 でアクセスを制限できます。マウントされた Secret は、環境変数の Secret と違い、変更時に更新されます(kubelet 同期後)。

kubernetes
apiVersion: v1
kind: Pod
metadata:
  name: app
spec:
  containers:
    - name: app
      image: myapp:1.0
      volumeMounts:
        - name: secrets
          mountPath: /etc/secrets
          readOnly: true
  volumes:
    - name: secrets
      secret:
        secretName: db-creds
        defaultMode: 0400       # restrict permissions
        items:
          - key: password
            path: db-password   # written to /etc/secrets/db-password
# memory-backed tmpfs, never written to disk on the node

ImagePullSecret

imagePullSecrets はイメージ取得時のプライベートレジストリの認証に使います。ServiceAccount に付けると、その SA を使うすべての Pod に適用されます(推奨パターン)。docker-registry 型の Secret は .dockerconfigjson のペイロードを自動的に作ってくれます。

kubernetes
# attach to a pod
apiVersion: v1
kind: Pod
metadata:
  name: private-app
spec:
  imagePullSecrets:
    - name: regcred
  containers:
    - name: app
      image: registry.example.com/myapp:1.0

# attach to a service account (auto-applied to all pods using it)
kubectl patch serviceaccount default \
  -p '{"imagePullSecrets":[{"name":"regcred"}]}'

# verify
kubectl get sa default -o jsonpath='{.imagePullSecrets}'

Secret の型

専用の Secret 型は検証と統合を可能にします。Ingress 用の tls、イメージ取得用の dockerconfigjson、Pod に自動マウントされる service-account-token などです。正しい型を使うと、キーが検証され、正しいコントローラーが消費してくれます。

kubernetes
# Opaque (default) — arbitrary key-value
type: Opaque

# kubernetes.io/service-account-token — auto for SAs
type: kubernetes.io/service-account-token

# kubernetes.io/dockerconfigjson — registry auth
type: kubernetes.io/dockerconfigjson
data:
  .dockerconfigjson: <base64>

# kubernetes.io/tls — for Ingress TLS
type: kubernetes.io/tls
data:
  tls.crt: <base64>
  tls.key: <base64>

# kubernetes.io/basic-auth
type: kubernetes.io/basic-auth
stringData:
  username: admin
  password: pass
07

Namespace

Namespace の作成

Namespace はクラスタを複数チームや環境(dev/stage/prod)に分割します。リソースの名前は名前空間内で一意である必要があります。一部のリソース(Node、PV、StorageClass)はクラスタスコープで、名前空間に属しません。

kubernetes
# imperative
kubectl create namespace dev

# declarative
apiVersion: v1
kind: Namespace
metadata:
  name: dev
  labels:
    environment: development
    team: platform

# apply
kubectl apply -f namespace.yaml

# list namespaces
kubectl get namespaces

# set default namespace for current context
kubectl config set-context --current --namespace=dev

ResourceQuota

ResourceQuota は名前空間内のリソース使用量の合計に上限を設けます。CPU/メモリの requests/limits の合計、オブジェクト数(pods、PVC、services、deployments)などです。マルチテナントのクラスタで、1 チームが他を枯渇させないのに不可欠です。明示的な requests のない Pod は、クォータ設定後は拒否されます。

kubernetes
apiVersion: v1
kind: ResourceQuota
metadata:
  name: compute-quota
  namespace: dev
spec:
  hard:
    requests.cpu: "10"
    requests.memory: 20Gi
    limits.cpu: "20"
    limits.memory: 40Gi
    pods: "50"
    services.loadbalancers: "2"
    persistentvolumeclaims: "10"
    count/deployments.apps: "5"
# limits total aggregate resource use in the namespace

LimitRange

LimitRange はリソースごとのデフォルトと範囲を設定します。指定しない Pod へのデフォルトの requests/limits、突出した値を抑える min/max です。ResourceQuota とペアにします。デフォルトの requests がないと、クォータが設定を忘れたすべての Pod を拒否してしまいます。

kubernetes
apiVersion: v1
kind: LimitRange
metadata:
  name: default-limits
  namespace: dev
spec:
  limits:
    - type: Container
      default:               # default limits (if unset)
        cpu: 500m
        memory: 512Mi
      defaultRequest:        # default requests (if unset)
        cpu: 100m
        memory: 128Mi
      max:                   # max allowed limits
        cpu: "2"
        memory: 2Gi
      min:                   # min allowed requests
        cpu: 50m
        memory: 64Mi
    - type: PersistentVolumeClaim
      max:
        storage: 100Gi
      min:
        storage: 1Gi

Namespace の削除と Finalizer

名前空間の削除はその中の全リソースに連鎖します。Terminating のまま固まる名前空間には、完了できない finalizer があるのが通常です。利用できない APIService(例: metrics-server)や、コントローラーが消えた CRD などが原因です。finalizer を除去すれば完了しますが、外部リソースが漏出することがあります。

kubernetes
# delete a namespace (cascades all resources in it)
kubectl delete namespace dev

# if stuck in Terminating, inspect finalizers
kubectl get namespace dev -o yaml

# remove finalizer to force completion (DANGEROUS)
kubectl patch namespace dev -p '{"metadata":{"finalizers":null}}'

# resources that block deletion:
# - APIService unavailable (metrics-server removed)
# - custom resources whose CRD is gone
# - PVCs with attached PVs

# check what's still in the namespace
kubectl api-resources --verbs=list --namespaced -o name \
  | xargs -n 1 kubectl get -n dev --ignore-not-found

デフォルトの Namespace

kube-system はコントロールプレーンとアドオン(DNS、kube-proxy、CNI)を動かします。kube-public は認証なしユーザーが読めるブートストラップデータを持ちます。kube-node-lease はパフォーマンスのためにノードのハートビートを Lease オブジェクトとして保存します。default は名前空間を指定しないときのワークロードの置き場所です。

kubernetes
# built-in namespaces
kubectl get namespaces
# NAME              STATUS   AGE
# default           Active   30d   <- user workloads land here
# kube-system       Active   30d   <- control plane / addons
# kube-public       Active   30d   <- publicly readable (bootstrap)
# kube-node-lease   Active   30d   <- node heartbeats (leases)

# kube-system holds:
# - kube-dns / CoreDNS
# - kube-proxy
# - metrics-server
# - CNI, CSI, cloud provider controllers

# kube-public is readable by all (used for cluster info discovery)

Namespace スコープと Cluster スコープ

ワークロードのリソースの多くは名前空間に属します。インフラ(node、PV、StorageClass、ClusterRole)はクラスタスコープです。Service は自分の名前空間の Pod しか対象にできません。-A は --all-namespaces の省略形で、クラスタ全体の可視性に不可欠です。

kubernetes
# which resources are namespaced?
kubectl api-resources --namespaced=true
kubectl api-resources --namespaced=false

# namespaced: pods, services, deployments, configmaps, secrets
# cluster-scoped: nodes, namespaces, PVs, StorageClasses, ClusterRoles

# access across namespaces:
# - a Service selector only matches pods in the SAME namespace
# - cross-namespace refs require special controllers (e.g. external-dns)

# list resources across all namespaces
kubectl get pods --all-namespaces
kubectl get pods -A   # shorthand
08

ラベルとセレクター

ラベルの構文

ラベルはリソースの識別とグループ化に使うキーと値のペアです。キーには省略可能なプレフィックス(DNS サブドメイン、例: app.kubernetes.io/)が付けられます。ラベルはクエリ/フィルタのためのもので、任意の非識別メタデータを扱う annotation とは役割が違います。

kubernetes
# labels are key=value pairs
# key: prefix (optional DNS subdomain) + name
# value: string, up to 63 chars

metadata:
  labels:
    app: nginx
    tier: frontend
    env: prod
    app.kubernetes.io/name: nginx
    app.kubernetes.io/version: "1.25"

# view labels
kubectl get pods --show-labels

# add/overwrite a label
kubectl label pod nginx env=prod
kubectl label pod nginx env=staging --overwrite

# remove a label (trailing dash)
kubectl label pod nginx env-

等価セレクターと集合セレクター

セレクターには 2 種類あります。等価ベース(=、==、!=)と集合ベース(in、notin、exists、!exists)です。カンマで区切った複数の条件は AND です。Service と Deployment の YAML では等価ベースのセレクターを使い、kubectl -l は両方に対応します。

kubernetes
# equality-based: = == !=
kubectl get pods -l app=nginx
kubectl get pods -l env!=dev
kubectl get pods -l 'app=nginx,env=prod'   # AND of conditions

# set-based: in, notin, exists
kubectl get pods -l 'env in (prod,staging)'
kubectl get pods -l 'env notin (dev)'
kubectl get pods -l 'tier'                 # key exists
kubectl get pods -l '!canary'              # key does not exist

# combine equality and set-based
kubectl get pods -l 'app=nginx,env in (prod,staging)'

リソースへのラベリング

label は識別のためのメタデータを変更します。セレクターがマッチすべきものに使いましょう。annotate は非識別のメタデータ(所有者、チケット、説明、ツールのヒント)用です。ノードにはトポロジーやハードウェアのヒントのラベルがよく付けられ、スケジューリングを左右します。

kubernetes
# label a pod
kubectl label pod nginx app=nginx tier=web

# label all pods matching a selector
kubectl label pods -l app=oldapp app=newapp --overwrite

# label a node (for scheduling hints)
kubectl label node node-1 disktype=ssd

# remove a node label
kubectl label node node-1 disktype-

# list nodes by label
kubectl get nodes -l disktype=ssd

# annotate (non-identifying metadata)
kubectl annotate pod nginx owner=alice
kubectl annotate pod nginx description="web server"

マニフェスト内のセレクター

YAML ではセレクターに matchLabels(等価)と matchExpressions(集合ベースの In/NotIn/Exists/DoesNotExist)を使います。Deployment のセレクターは作成後は不変で、Pod テンプレートのラベルが一致する必要があります。Service は matchLabels のみに対応します。

kubernetes
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  selector:
    matchLabels:            # equality-based
      app: nginx
    matchExpressions:       # set-based (optional)
      - key: env
        operator: In
        values: [prod, staging]
      - key: tier
        operator: Exists
  template:
    metadata:
      labels:
        app: nginx          # MUST match selector
        env: prod
        tier: web

Annotation

annotation はツールが使う非識別のメタデータを保持します。kubectl apply は last-applied の設定を保存し、cert-manager は発行者のヒントを読み、Prometheus はスクレイプ設定を読み、コントローラーはロールアウト状態を保存します。ラベルと違い、annotation の値は大きな JSON でも構いません。

kubernetes
metadata:
  annotations:
    kubernetes.io/change-cause: "bump nginx to 1.26"
    prometheus.io/scrape: "true"
    prometheus.io/port: "9090"
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"apps/v1",...}
    cert-manager.io/cluster-issuer: "letsencrypt-prod"

# view annotations
kubectl get pod nginx -o jsonpath='{.metadata.annotations}'

# annotate
kubectl annotate pod nginx owner=team-platform

# remove an annotation (trailing dash)
kubectl annotate pod nginx owner-

推奨ラベル

app.kubernetes.io/* のラベルは共通の語彙で、ツール(Helm、オペレーター、ダッシュボード)がアプリの全リソースをグループ化できます。name+instance がリリースを一意に識別し、component/part-of が階層を、managed-by/created-by が所有者を表します。

kubernetes
# shared recommended labels (app.kubernetes.io/*)
metadata:
  labels:
    app.kubernetes.io/name: nginx
    app.kubernetes.io/instance: nginx-prod
    app.kubernetes.io/version: "1.25"
    app.kubernetes.io/component: web
    app.kubernetes.io/part-of: storefront
    app.kubernetes.io/managed-by: helm
    app.kubernetes.io/created-by: controller-manager

# Helm applies these automatically; kubectl doesn't.
# They unify how tooling identifies an application's resources
# across Deployments, Services, Ingresses, ConfigMaps, etc.
09

ReplicaSet

ReplicaSet マニフェスト

ReplicaSet はセレクターに一致するレプリカ Pod の集合を安定に維持します。削除や失敗で Pod を再作成します。通常は Deployment を使います。Deployment が ReplicaSet を包み、ローリングアップデートとロールバックを追加するからです。

kubernetes
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:1.25
# kubectl get rs
# kubectl describe rs nginx

ReplicaSet の仕組み

ReplicaSet コントローラーはセレクターで、望ましい Pod 数と実際の数を突き合わせて調整します。各 Pod には RS を指す ownerReference が付くので、kubectl get pod に「Owned by ReplicaSet/nginx」と表示されます。スケールは望ましい数を変えるだけです。

kubernetes
# the controller loop:
# 1. count pods matching selector
# 2. if fewer than replicas -> create from template
# 3. if more than replicas -> delete excess (arbitrary order)

# owned-by reference on each pod
kubectl get pod -l app=nginx -o jsonpath='{.items[*].metadata.ownerReferences}'

# if you delete a pod, the RS creates a new one immediately
kubectl delete pod <pod-name>
kubectl get pods -l app=nginx

# scale by editing replicas
kubectl scale rs nginx --replicas=5

ReplicaSet と ReplicationController

ReplicationController(元祖の v1 プリミティブ)は等価セレクターのみで、非推奨です。ReplicaSet(apps/v1)は集合ベースのセレクターを追加します。実務では Deployment を使いましょう。ReplicaSet を管理し、ローリングアップデート/ロールバックも提供してくれます。

kubernetes
# ReplicationController (v1, legacy): equality-only selectors
# ReplicaSet (apps/v1, modern): set-based selectors (in, notin, exists)

# ReplicationController is deprecated; do not use.
apiVersion: v1
kind: ReplicationController      # legacy
# ...
# ReplicaSet is the successor:
apiVersion: apps/v1
kind: ReplicaSet                 # modern
# ...
# Deployment wraps ReplicaSet and is the recommended primitive:
apiVersion: apps/v1
kind: Deployment                 # use this in practice

手動スケール

kubectl scale は replicas フィールドを変更します。同じリソースを HPA が対象にしている場合、次の調整で手動スケールは上書きされます。単発には kubectl scale、継続的な弾力性には HPA が向いています。

kubernetes
# scale a replicaset directly
kubectl scale rs nginx --replicas=5

# scale via patch
kubectl patch rs nginx -p '{"spec":{"replicas":5}}'

# scale multiple resources at once
kubectl scale deployment nginx deployment web --replicas=3

# scale by referencing a file
kubectl scale --replicas=5 -f nginx.yaml

# the autoscaler (HPA) will override manual scaling
# if it targets the same resource

テンプレート変更と採用(Adoption)

Deployment と違い、素の ReplicaSet は Pod テンプレートの変更を展開しません。新しく作られる Pod(削除やスケールアップの後)だけが新しい spec を受け取ります。ReplicaSet はセレクターに一致する孤立した Pod を採用するので、意外な挙動の原因になります。

kubernetes
# changing the pod template does NOT update existing pods
# (unlike a Deployment, a bare ReplicaSet won't roll out)
kubectl edit rs nginx   # change image -> new pods use it, old ones don't

# delete old pods to force them onto the new template
kubectl delete pods -l app=nginx

# a ReplicaSet will ADOPT existing pods that match its selector
# even pods created independently — useful (and dangerous)

# orphaned pods (no owner) matching the selector are taken over
kubectl get pods -l app=nginx --show-kind

ReplicaSet からの Pod の切り離し

ReplicaSet に再作成させずに Pod を取り除くには、先に RS を 0 にスケールするか、Pod から ownerReferences を剥がして RS の所有から外します。特定インスタンスのデバッグや、後片付け前のログの回収に便利です。

kubernetes
# detaching a pod from its ReplicaSet (so it isn't replaced)
kubectl patch pod <pod-name> \
  -p '{"metadata":{"ownerReferences":[]}}'

# now deleting this pod won't trigger a replacement,
# because the RS no longer owns it

# or scale the RS to 0 first, then delete
kubectl scale rs nginx --replicas=0
kubectl delete pod <pod-name>

# useful for debugging a specific failing pod instance
# without the RS immediately recreating it
10

StatefulSet

StatefulSet マニフェスト

StatefulSet は Pod に安定した識別(名前、ホスト名、ストレージ)と、順序付きのデプロイ/スケールを与えます。headless な serviceName が必要です。volumeClaimTemplates は Pod ごとに専用の PVC を作るので、pod-0 が再スケジュールされても同じボリュームが再接続されます。

kubernetes
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
spec:
  serviceName: mysql          # required: headless service
  replicas: 3
  selector:
    matchLabels:
      app: mysql
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:
        - name: mysql
          image: mysql:8
          ports:
            - containerPort: 3306
          volumeMounts:
            - name: data
              mountPath: /var/lib/mysql
  volumeClaimTemplates:       # one PVC per pod
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 10Gi

安定した識別

各 Pod は安定した序数の名前(mysql-0、mysql-1、…)と、headless service 経由の安定した DNS 名を持ちます。ノードが壊れても pod-0 は別の場所に再スケジュールされますが、名前を保ち、ボリュームを再接続します。安定したメンバー構成に依存するクラスタ型データベースには決定的に重要です。

kubernetes
# pods are named <statefulset-name>-<ordinal>
# mysql-0, mysql-1, mysql-2
kubectl get pods -l app=mysql

# each pod has stable DNS (via the headless service):
#   mysql-0.mysql.default.svc.cluster.local
#   mysql-1.mysql.default.svc.cluster.local

# stable hostname inside the pod:
kubectl exec mysql-0 -- hostname
# -> mysql-0

# ordinal index also exposed:
kubectl exec mysql-0 -- sh -c 'echo $HOSTNAME'
# -> mysql-0

# pod identity persists across reschedules

安定したストレージ

volumeClaimTemplates は予測可能な名前(data-mysql-0、…)で Pod ごとに 1 個の PVC を生成します。PVC は Pod と StatefulSet の削除を生き延びます。データ損失を防ぐ一方、ストレージの回収には PVC の明示的な削除が必要という意味でもあります。同じボリュームは常に同じ序数の Pod に再接続されます。

kubernetes
# one PVC per pod, named <volumeClaimTemplate-name>-<pod-name>
kubectl get pvc
# NAME        STATUS   VOLUME       CAPACITY   ...
# data-mysql-0   Bound   pvc-aaa      10Gi
# data-mysql-1   Bound   pvc-bbb      10Gi
# data-mysql-2   Bound   pvc-ccc      10Gi

# when pod-0 is rescheduled, it re-binds data-mysql-0
# deleting the StatefulSet does NOT delete PVCs by default
# (protects from accidental data loss)

# to actually delete the data:
kubectl delete pvc data-mysql-0 data-mysql-1 data-mysql-2

順序付きデプロイと Pod 管理

OrderedReady(デフォルト)は Pod を 0→1→2 の順に厳密に作り、削除は逆順です。レプリカの前にプライマリを立ち上げる必要があるシステム向けです。Parallel は全 Pod を同時に作成/削除します。対称なシャード型ストア(Cassandra、Elasticsearch)では高速です。

kubernetes
spec:
  podManagementPolicy: OrderedReady   # default: strict order
  # podManagementPolicy: Parallel      # create/delete all at once

  replicas: 3
  # OrderedReady: create pod-0, then pod-1, then pod-2 (each waits for Ready)
  # deletion is reverse: pod-2, pod-1, pod-0

  # Parallel: all pods created/deleted simultaneously
  # identity and storage remain stable either way

# check policy
kubectl get statefulset mysql -o jsonpath='{.spec.podManagementPolicy}'

# parallel is great for sharded stores that don't need bootstrap order

ローリングアップデート

StatefulSet のローリングアップデートは序数の逆順(N-1 から 0)に進みます。partition で最も序数の高い Pod からカナリアできます。OnDelete は手動で Pod を削除するまで更新を止めます。管理された移行に有用です。順序があるため、展開は Deployment より遅くなります。

kubernetes
spec:
  updateStrategy:
    type: RollingUpdate
    rollingUpdate:
      partition: 2          # only pods with ordinal >= 2 update
      maxUnavailable: 1     # (default 1) allowed down
  # type: OnDelete  -> only update when pod is manually deleted

# partition enables canaries: set partition=N to update
# only the top N pods; lower to 0 to roll out to all.

kubectl rollout status statefulset/mysql
# waits for all pods to be updated

# StatefulSets also support rollout history/undo,
# but only when the change is in the pod template

Headless Service との関連付け

spec.serviceName が参照する headless service(clusterIP: None)こそが、Pod ごとの安定した DNS を実現します。これがないと StatefulSet は Pod を作りません。クライアントはラウンドロビン用に service 名を、プライマリの固定には pod-0.svc を解決します。Service の作成を忘れずに。

kubernetes
apiVersion: v1
kind: Service
metadata:
  name: mysql
spec:
  clusterIP: None         # headless
  selector:
    app: mysql
  ports:
    - port: 3306
---
# StatefulSet references this service via spec.serviceName
# this gives each pod a stable DNS:
#   mysql-0.mysql.default.svc.cluster.local

# clients can:
# - resolve mysql -> any pod IP (load-balanced by DNS round-robin)
# - resolve mysql-0.mysql -> pod-0's IP (pin to a specific replica)

# required: serviceName MUST match the headless service name
11

DaemonSet

DaemonSet マニフェスト

DaemonSet は各ノードに(そのスケジューリング制約に一致する)ちょうど 1 個の Pod を実行します。ノードレベルのエージェントに最適です。ログ収集、監視、ストレージ、CNI、ingress コントローラーなど。新しいノードには自動で Pod が付き、削除されたノードの Pod は回収されます。

kubernetes
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: log-agent
  namespace: kube-system
  labels:
    app: log-agent
spec:
  selector:
    matchLabels:
      app: log-agent
  template:
    metadata:
      labels:
        app: log-agent
    spec:
      containers:
        - name: agent
          image: fluent-bit:2.2
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
      # one pod per (matching) node automatically

ノードのスケジューリング

nodeSelector は最も単純な制約です(すべての key=value が一致する必要)。nodeAffinity は In/NotIn/Exists 演算子と preferred/required ルールを追加します。DaemonSet も通常の Pod と同様にこれらを尊重し、toleration と組み合わせれば taint の付いたコントロールプレーンノードでもエージェントを動かせます。

kubernetes
spec:
  template:
    spec:
      nodeSelector:                # simplest: must match all
        disktype: ssd

      # more flexible affinity
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
              - matchExpressions:
                  - key: kubernetes.io/os
                    operator: In
                    values: [linux]

      # only run on nodes labeled role=logging
      nodeSelector:
        role: logging

      tolerations:                 # tolerate tainted nodes
        - key: node-role.kubernetes.io/control-plane
          operator: Exists

更新戦略

RollingUpdate(デフォルト)は maxUnavailable(数値または %)を上限にノード単位で Pod を更新します。OnDelete は手動で Pod を削除するまで更新を止めます。ノード単位の制御が必要なときに有用です。maxSurge のデフォルトは 0 です(DaemonSet は余分な Pod を通常は求めません)。

kubernetes
spec:
  updateStrategy:
    type: RollingUpdate           # default
    rollingUpdate:
      maxUnavailable: 1           # how many nodes update at once
      maxSurge: 0                 # (default 0) no extra pods
  # type: OnDelete               # only update when old pod is deleted

# trigger an update (e.g. new image)
kubectl set image daemonset/log-agent agent=fluent-bit:2.3

# watch rollout
kubectl rollout status daemonset/log-agent -n kube-system

# rollout restart (recreate pods on every node)
kubectl rollout restart daemonset/log-agent -n kube-system

Taint と Toleration

Taint は Pod をはじきます。Toleration は特定の Pod に taint を無視させます。コントロールプレーンノードには NoSchedule の taint が付き、ユーザーのワークロードが乗らないようにしています。ノードレベルのエージェントはそれを toleration してどこでも動きます。NoExecute は既に動いている非許容の Pod も追い出します。

kubernetes
# inspect a node's taints
kubectl describe node node-1 | grep Taints
# Taints: node-role.kubernetes.io/control-plane:NoSchedule

# tolerate control-plane so the agent runs there too
spec:
  template:
    spec:
      tolerations:
        - key: node-role.kubernetes.io/control-plane
          operator: Exists
          effect: NoSchedule
        - key: node.kubernetes.io/disk-pressure
          operator: Exists
          effect: NoExecute

# taint effects: NoSchedule | NoExecute | PreferNoSchedule

DaemonSet のユースケース

DaemonSet はノードレベルのインフラの標準的なデプロイ形態です。仕事のために特権アクセス(hostNetwork、hostPID、hostPath)が必要なことが多いので、意図的に、信頼できるイメージにだけ付与しましょう。水平スケールすべきアプリのワークロードに DaemonSet を使ってはいけません。

kubernetes
# classic DaemonSet workloads (node-level agents):
# - log collection:        fluent-bit, filebeat, promtail
# - monitoring:            node-exporter, datadog-agent
# - networking:            kube-proxy, CNI plugins, ingress controllers
# - storage:               CSI node plugins, Rook/Ceph
# - security:              Falco, Tetragon, runtime security
# - GPU/FPGA drivers:      nvidia-device-plugin

# storage / device plugins often need:
spec:
  template:
    spec:
      hostNetwork: true        # use node network namespace
      hostPID: true            # see node processes
      hostPath:                # mount node paths
        - path: /var/log
        - path: /var/lib/docker/containers

DaemonSet の状態

DESIRED はスケジューリング制約に一致するノード数です。CURRENT/READY は存在する Pod 数と readiness を通過している数を示します。-o wide が各 Pod がどのノードに載ったかを見る最も簡単な方法です。DaemonSet も Deployment と同様にロールアウト履歴/undo に対応しています。

kubernetes
# desired = number of matching nodes
kubectl get daemonset log-agent -n kube-system
# NAME         DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE
# log-agent    5         5         5       5            5

# show which nodes a DaemonSet pod landed on
kubectl get pods -n kube-system -l app=log-agent -o wide

# rollout history
kubectl rollout history daemonset/log-agent -n kube-system

# rollback
kubectl rollout undo daemonset/log-agent -n kube-system

# check a per-node pod's logs
kubectl logs -n kube-system log-agent-abcde
12

Job と CronJob

Job マニフェスト

Job は指定した数の Pod が成功裏に完了するまで(completions)Pod を実行します。restartPolicy は Never か OnFailure でなければなりません(Always は長時間実行のワークロード用)。backoffLimit が再試行の上限、activeDeadlineSeconds が合計実行時間の上限です。

kubernetes
apiVersion: batch/v1
kind: Job
metadata:
  name: pi
spec:
  completions: 1              # how many successful pods needed
  parallelism: 1              # how many run concurrently
  backoffLimit: 6             # retries before marking Failed
  activeDeadlineSeconds: 600  # hard timeout
  template:
    spec:
      restartPolicy: Never    # OnFailure | Never
      containers:
        - name: pi
          image: perl
          command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]
# kubectl get jobs
# kubectl logs job/pi

Job の completions と parallelism

completions は Job を満たす成功 Pod の数、parallelism は同時に実行する数です。Indexed Job は各 Pod に序数を付けます(環境変数 JOB_COMPLETION_INDEX)。各 Pod が 1 つのスライスを担当するシャード型バッチ処理に最適です。NonIndexed(デフォルト)はどこからでも N 個の成功があれば十分です。

kubernetes
spec:
  completions: 5         # 5 successful pods total
  parallelism: 2         # 2 pods run at a time
  backoffLimit: 4
  # default completionMode: NonIndexed (any 5 successes)
  completionMode: Indexed
  # Indexed: pods get 0..N-1 in JOB_COMPLETION_INDEX env,
  # useful for sharded work (each pod handles one shard)

  template:
    spec:
      restartPolicy: OnFailure
      containers:
        - name: worker
          image: worker:1.0

# set via kubectl
kubectl create job pi --image=perl -- perl -Mbignum=bpi -wle "print bpi(2000)"

Job のバックオフとタイムアウト

backoffLimit は失敗した Pod を再試行します(指数バックオフ)。activeDeadlineSeconds は硬い上限で、これに達すると再試行が残っていても Job は Failed になります。ttlSecondsAfterFinished は完了した Job を自動掃除します。podFailurePolicy(1.31+)は特定の終了コードで素早く失敗させたり、自発的な追い出しを無視したりできます。

kubernetes
spec:
  backoffLimit: 6            # default 6, retries on failure
  activeDeadlineSeconds: 3600  # hard wall, even if retries remain
  ttlSecondsAfterFinished: 86400  # auto-delete Job 1 day after done
  startingDeadlineSeconds: 300  # (CronJob only) miss window

  # pod failure handling (v1.31+):
  podFailurePolicy:
    rules:
      - action: FailJob
        onExitCodes:
          operator: In
          values: [42]      # exit 42 -> don't retry, fail fast
      - action: Count
        onPodConditions:
          - type: DisruptionTarget   # don't count voluntary evictions

  template:

CronJob マニフェスト

CronJob は cron のスケジュール(5 フィールド: 分 時 日 月 曜日)で Job を作ります。concurrencyPolicy は重複実行を制御します。Forbid は前の実行が続いていれば新規をスキップし、Replace は古いものを止めて新規を始めます。timeZone(1.27+)により UTC の計算が不要になります。

kubernetes
apiVersion: batch/v1
kind: CronJob
metadata:
  name: backup
spec:
  schedule: "0 2 * * *"          # 5-field cron: 02:00 daily
  timeZone: "Asia/Shanghai"
  concurrencyPolicy: Forbid      # Allow | Forbid | Replace
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1
  startingDeadlineSeconds: 200
  jobTemplate:
    spec:
      backoffLimit: 2
      template:
        spec:
          restartPolicy: OnFailure
          containers:
            - name: backup
              image: backup:1.0
# kubectl get cronjob
# kubectl get jobs

CronJob の suspend と履歴

suspend: true は CronJob を削除せずに一時停止します。障害対応中に便利です。履歴の上限が Job の一覧を管理しやすくします(デフォルトは成功 3 件/失敗 1 件)。kubectl create job --from=cronjob/X はテンプレートを即座に実行し、手動トリガーや取り逃した実行の埋め合わせに最適です。

kubernetes
spec:
  schedule: "*/5 * * * *"
  suspend: true                # pause without deleting the CronJob
  successfulJobsHistoryLimit: 3   # default 3
  failedJobsHistoryLimit: 1       # default 1

# toggle suspend
kubectl patch cronjob backup -p '{"spec":{"suspend":true}}'
kubectl patch cronjob backup -p '{"spec":{"suspend":false}}'

# trigger a one-off run immediately
kubectl create job --from=cronjob/backup manual-backup

# clean up old jobs manually
kubectl delete jobs -l job-name=backup

CronJob のスケジュールと注意点

標準の 5 フィールド cron です。日(月内)と曜日の両方が制限されているとき、cron はどちらか一致で発火します(OR の意味論)。古典的な落とし穴です。スケジュール時刻が startingDeadlineSeconds を超えて逃された場合、その実行は埋め合わせではなくスキップされます。

kubernetes
# cron syntax (5 fields):
# ┌───────────── minute (0-59)
# │ ┌───────────── hour (0-23)
# │ │ ┌───────────── day of month (1-31)
# │ │ │ ┌───────────── month (1-12)
# │ │ │ │ ┌───────────── day of week (0-6, Sun=0)
# "*/5 * * * *"      every 5 minutes
# "0 2 * * *"        daily at 02:00
# "0 0 * * 0"        weekly Sunday midnight
# "0 0 1 * *"        monthly on the 1st
# "30 3-5 * * *"     03:30, 04:30, 05:30

# gotchas:
# - day-of-month AND day-of-week both set => OR (not AND)
# - if startingDeadlineSeconds is missed, the run is skipped
# - control-plane restart can skip a tick if the schedule is missed
# - cron interprets literal fields; prefer timeZone over UTC math
13

Ingress

Ingress マニフェスト

Ingress はクラスタ外から Service への HTTP/HTTPS ルートを公開し、Ingress コントローラー(nginx、traefik、ALB など)が管理します。ingressClassName がどのコントローラーが処理するかを選びます。各ルールは host + path を service+port のバックエンドへ対応付けます。

kubernetes
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx
  rules:
    - host: app.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web
                port:
                  number: 80
          - path: /api
            pathType: Prefix
            backend:
              service:
                name: api
                port:
                  number: 8080

TLS 付き Ingress

tls エントリは TLS の Secret(type kubernetes.io/tls、tls.crt + tls.key を保持)を 1 つ以上の host に結び付けます。Ingress コントローラーが TLS を終端し、平文 HTTP をバックエンドへプロキシします。cert-manager は cluster-issuer の annotation に基づき、Let's Encrypt の証明書を自動発行・更新できます。

kubernetes
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web-tls
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - app.example.com
        - www.example.com
      secretName: web-tls-secret   # kubernetes.io/tls secret
  rules:
    - host: app.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web
                port:
                  number: 80

# auto-issue certs with cert-manager:
# annotations:
#   cert-manager.io/cluster-issuer: letsencrypt-prod

Ingress ルールとデフォルトバックエンド

defaultBackend はどのルールにも一致しないトラフィック(host なし、未一致の path)を処理します。複数のルールで 1 つの Ingress が多数の仮想ホストを振り分けられます。各ルールは複数の path バックエンドを持てるので、1 つの Ingress がアプリ全体のルーティング構造を担えます。

kubernetes
spec:
  ingressClassName: nginx
  defaultBackend:                # catch-all for unmatched traffic
    service:
      name: default-svc
      port:
        number: 80
  rules:
    - host: app.example.com
      http:
        paths:
          - path: /api
            pathType: Prefix
            backend:
              service: { name: api, port: { number: 8080 } }
    - host: blog.example.com     # different host -> different svc
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service: { name: blog, port: { number: 80 } }

IngressClass

IngressClass はコントローラーを宣言します(例: k8s.io/ingress-nginx)。Ingress は spec.ingressClassName で参照するので、複数のコントローラーが共存できます。is-default-class の annotation でデフォルトにできるのは 1 クラスだけで、明示のない新しい Ingress はそれを使います。

kubernetes
apiVersion: networking.k8s.io/v1
kind: IngressClass
metadata:
  name: nginx
  annotations:
    ingressclass.kubernetes.io/is-default-class: "true"
spec:
  controller: k8s.io/ingress-nginx

# an Ingress picks a class via spec.ingressClassName
# (replaces the deprecated kubernetes.io/ingress.class annotation)

# multiple IngressClasses in one cluster:
# - nginx    (community ingress-nginx)
# - traefik  (Traefik controller)
# - alb      (AWS ALB)
# only one IngressClass can be marked default

パスの型

Exact はパスそのままに一致し、Prefix はパスセグメント全体に一致します(/api は /api と /api/foo に一致し、/apix には一致しない)。ImplementationSpecific はコントローラーに委ねます(例: nginx の正規表現)。移植性のある挙動には Prefix か Exact を常に選びましょう。ImplementationSpecific は 1 つのコントローラーに縛られます。

kubernetes
spec:
  rules:
    - host: app.example.com
      http:
        paths:
          - path: /api/v1
            pathType: Exact        # only /api/v1 (exact match)
            backend: ...
          - path: /api
            pathType: Prefix       # /api, /api/, /api/x (prefix match)
            backend: ...
          - path: /old
            pathType: ImplementationSpecific  # controller decides
            backend: ...

# Prefix matches path segments, not raw string prefix:
# /api   matches /api, /api/, /api/x  but NOT /apix
# Exact  matches the path verbatim
# ImplementationSpecific defers to the controller

Annotation(Nginx コントローラー)

コントローラー固有の annotation は、標準の Ingress spec を超えた挙動を設定します。ingress-nginx には多数あります: rewrite-target、ssl-redirect、body-size、タイムアウト、CORS、basic 認証、設定スニペットなど。コントローラー固有なので、別のコントローラーへの移植は書き直しを意味します。

kubernetes
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web
  annotations:
    kubernetes.io/ingress.class: nginx          # legacy form
    nginx.ingress.kubernetes.io/rewrite-target: /$2
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-body-size: "50m"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
    nginx.ingress.kubernetes.io/cors-allow-origin: "https://app.example.com"
    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/auth-secret: basic-auth
    nginx.ingress.kubernetes.io/configuration-snippet: |
      more_set_headers "X-Frame-Options: DENY";
spec:
  rules:
    - host: app.example.com
      http:
        paths:
          - path: /v1(/|$)(.*)
            pathType: ImplementationSpecific
            backend:
              service: { name: api, port: { number: 8080 } }
14

ボリューム(PV/PVC)

PersistentVolume マニフェスト

PersistentVolume(PV)はクラスタスコープのストレージで、管理者が用意するか、StorageClass が動的にプロビジョニングします。accessModes はマウントの方法を記述します。reclaimPolicy は PVC が解放されたときのストレージの扱いを制御します。

kubernetes
apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-1
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce        # RWO: one node R/W
  persistentVolumeReclaimPolicy: Retain   # Retain | Delete | Recycle
  storageClassName: manual
  hostPath:                # for dev only (single node)
    path: /mnt/data
  # nfs:
  #   server: 10.0.0.1
  #   path: /export/data
  # csi:
  #   driver: ebs.csi.aws.com
  #   volumeHandle: vol-xxxx

PersistentVolumeClaim マニフェスト

PersistentVolumeClaim(PVC)は名前空間スコープのストレージの要求です。コントローラーが一致する PV(accessModes、十分な容量、同じ StorageClass)に結び付けます。デフォルトの StorageClass があれば、storageClassName を空のままにすると動的プロビジョニングが始まります。

kubernetes
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data-claim
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: manual
  resources:
    requests:
      storage: 5Gi
  volumeMode: Filesystem     # Filesystem | Block
  selector:                  # optional: filter PVs by labels
    matchLabels:
      disktype: ssd
# kubectl get pvc
# STATUS: Pending -> Bound once a matching PV is found

アクセスモード

accessModes はマウントの意味論を記述しますが、実際の対応はストレージのバックエンド次第です。EBS/GCE PD/Azure Disk は RWO のみです。RWX(複数ノードでの読み書き)には NFS、CephFS、分散ファイルシステムが必要です。RWOP(1.27+)は同じノードでも 1 Pod に制限します。

kubernetes
# four access modes (support is driver-specific):
# - ReadWriteOnce  (RWO):  mounted R/W by ONE node
# - ReadOnlyMany   (ROX):  mounted R/O by MANY nodes
# - ReadWriteMany  (RWX):  mounted R/W by MANY nodes
# - ReadWriteOncePod (RWOP): mounted R/W by ONE pod (1.27+)

# examples by backend:
# AWS EBS, GCE PD, Azure Disk:  RWO only
# NFS:                          RWO, ROX, RWX
# CephFS, Portworx:             RWO, RWX
# Block volumes:                RWO

# RWX is required for pods on different nodes
# to share the same volume (e.g. read-only assets)

Reclaim ポリシー

Retain は安全のためデータを残します。PV を手動で消去して再結合する必要があります。Delete(動的プロビジョニングのデフォルト)は PVC が消えると PV とその下のストレージを消します。Recycle は非推奨です。Retain の Released 状態の PV は、再結合の前に claimRef をクリアする必要があります。

kubernetes
# what happens when a PVC is deleted:
# - Retain:   PV stays, data preserved; PV must be manually
#             reclaimed (delete data, then delete PV) before reuse
# - Delete:   PV and the underlying storage are deleted (dynamic only)
# - Recycle:  deprecated; ran scrub on the volume

# change policy on an existing PV
kubectl patch pv pv-1 -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'

# a released PV (PVC deleted, policy Retain) is stuck:
#   phase=Released, claimRef still set
# to reuse: clear claimRef
kubectl patch pv pv-1 --type json -p '[{"op":"remove","path":"/spec/claimRef"}]'

Pod 内の PVC

PVC は persistentVolumeClaim.claimName で、他のボリュームと同じようにマウントします。subPath はサブディレクトリをマウントします。1 つのボリュームを Pod/パス間で共有するのに便利です。RWO ボリュームは複数の Pod でマウントできますが同じノード上のみで、ノードをまたぐと multi-attach エラーになります。

kubernetes
apiVersion: v1
kind: Pod
metadata:
  name: db
spec:
  volumes:
    - name: data
      persistentVolumeClaim:
        claimName: data-claim
  containers:
    - name: db
      image: postgres:16
      volumeMounts:
        - name: data
          mountPath: /var/lib/postgresql/data
          subPath: pgdata       # mount a subdirectory of the volume

# a PVC is namespaced and bound to ONE PV
# RWO PVCs can be mounted by multiple pods on the SAME node
# (e.g. one writer, several readers on that node)

静的と動的プロビジョニング

静的プロビジョニングは管理者が PV を事前に作る方式です。NFS には適しますが、スケールでは苦痛です。動的プロビジョニングは、PVC が StorageClass の provisioner を通じてオンデマンドのボリューム作成を引き起こします。モダンなクラスタはほぼ常に動的プロビジョニングで、静的は共有/レガシーストレージ向けです。

kubernetes
# STATIC: admin pre-creates PVs; PVCs bind to them.
#   Good for: pre-existing NFS exports, manual capacity planning.

# DYNAMIC: PVC requests storage; StorageClass provisions a PV
#   automatically (AWS EBS, GCE PD, Ceph, local-path, etc.)

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: dynamic-claim
spec:
  storageClassName: ebs-sc      # triggers dynamic provisioning
  accessModes: ["ReadWriteOnce"]
  resources:
    requests:
      storage: 20Gi

# no PV exists -> provisioner creates one -> binds to PVC
# kubectl get pvc dynamic-claim -> Bound
# kubectl get pv -> shows the dynamically-created PV
15

StorageClass

StorageClass マニフェスト

StorageClass は動的プロビジョニングされるストレージの「種類」を記述します。provisioner(CSI ドライバー)、パラメータ(ディスク種別、暗号化、fsType)、ポリシーです。PVC は spec.storageClassName で参照します。1 クラスタに通常複数のクラスがあります(高速 SSD、大容量 HDD、NFS など)。

kubernetes
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: ebs-sc
provisioner: ebs.csi.aws.com
parameters:
  type: gp3
  fsType: ext4
  encrypted: "true"
reclaimPolicy: Delete            # Retain | Delete
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true
mountOptions:
  - noatime
# kubectl get storageclass

デフォルトの StorageClass

デフォルトにできる StorageClass は 1 つだけです(annotation の is-default-class: true)。storageClassName を省いた PVC は自動的にそれを使います。どのバックエンドでも構わないユーザーには便利です。kubectl get sc で(default)と付いているクラスが分かります。

kubernetes
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: standard
  annotations:
    storageclass.kubernetes.io/is-default-class: "true"
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer

# a PVC with no storageClassName uses the default
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: auto
spec:
  accessModes: ["ReadWriteOnce"]
  resources:
    requests:
      storage: 5Gi
# (no storageClassName set -> uses 'standard')

Provisioner

kubernetes.io/no-provisioner は静的な結合のみを意味します(動的作成なし)。実際の動的プロビジョニングはすべて CSI ドライバーです。クラウドプロバイダは独自のもの(ebs.csi.aws.com など)を提供し、セルフホストの選択肢(Longhorn、Rook/Ceph、local-path)がベアメタルをカバーします。パラメータは完全に provisioner 固有です。

kubernetes
# built-in (no external driver): only static binding
provisioner: kubernetes.io/no-provisioner

# cloud CSI drivers (dynamic):
provisioner: ebs.csi.aws.com          # AWS EBS
provisioner: pd.csi.storage.gke.io    # GCE PD
provisioner: disk.csi.azure.com       # Azure Disk
provisioner: nfs.csi.k8s.io           # NFS

# popular self-hosted:
provisioner: driver.longhorn.io       # Longhorn
provisioner: rook-ceph.ceph.com       # Rook/Ceph
provisioner: rancher.io/local-path    # local-path (dev)

# parameters are provisioner-specific
# (e.g. AWS: type=gp3|iops=3000|encrypted=true)

Volume Binding Mode

Immediate は PVC 作成の瞬間に結合します。ゾーン付きディスクでは危険です。Pod が別のゾーンに落ちるかもしれないからです。WaitForFirstConsumer は Pod が実際に PVC を消費するまで結合を延期するので、ボリュームが正しいゾーンに置かれます。ゾーン付きクラウドディスクには常に WaitForFirstConsumer を使いましょう。

kubernetes
spec:
  volumeBindingMode: WaitForFirstConsumer
  # ^ default for many CSI drivers
  # alternatives:
  # volumeBindingMode: Immediate

# Immediate: PVC binds/provisions as soon as created
#   risk: volume created in zone A, pod scheduled in zone B
#   -> multi-attach / cross-zone latency issues

# WaitForFirstConsumer: delays binding until a pod using the PVC
#   is scheduled. The PV is then created in the pod's zone.
#   REQUIRED for topology-constrained backends (EBS, etc.)

# topology constraints come from the CSI driver via
# AllowedTopologies

StorageClass ごとの Reclaim ポリシー

StorageClass.reclaimPolicy は、そのクラスが動的に作るすべての PV のポリシーを決めます。Delete(デフォルト)は PVC の削除でボリュームを破壊します。効率的ですが本番データには危険です。データを救うには、PVC を削除する前に PV を Retain に切り替えるか、最初から Retain のクラスを使います。

kubernetes
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: ebs-temp
provisioner: ebs.csi.aws.com
reclaimPolicy: Delete            # default for dynamic volumes
# reclaimPolicy: Retain          # keep data after PVC delete

# the StorageClass policy becomes the PV's policy
# when a PV is dynamically provisioned

# to preserve data, either:
# 1. use a Retain StorageClass
# 2. patch the dynamically-created PV to Retain before deleting PVC:
kubectl patch pv pvc-xxxx -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'

# then delete PVC safely; data survives

ボリュームの拡張

allowVolumeExpansion: true を設定すると、spec.resources.requests.storage の編集で PVC を拡張できます。CSI ドライバーが下のボリュームを拡張し、次回のマウントで kubelet がファイルシステムを拡張します。縮小は決して対応されていません。多くのクラウド CSI ドライバーはオンライン拡張(アンマウント不要)に対応しています。

kubernetes
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: ebs-sc
provisioner: ebs.csi.aws.com
allowVolumeExpansion: true       # must be true to resize

# then resize by editing the PVC's requested size
kubectl patch pvc data-claim -p '{"spec":{"resources":{"requests":{"storage":"50Gi"}}}}'

# status.conditions shows Resizing / FileSystemResizePending
kubectl describe pvc data-claim

# requirements:
# - StorageClass.allowVolumeExpansion = true
# - driver supports online expansion (most CSI drivers do)
# - shrinking is NOT supported (only grow)
# - FilesystemResize happens after the PV is expanded
16

Helm

Helm の install と release

Helm は Kubernetes のマニフェストを「チャート」としてパッケージ化し、「リリース」として管理します。install がリリースを作り、upgrade が変更を適用します。upgrade --install は冪等です。リリースは名前空間内の Secret/ConfigMap で追跡されており、ロールバックはこの仕組みで動きます。

kubernetes
# add and update a chart repo
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update

# search for charts
helm search repo nginx
helm search hub wordpress   # searches Artifact Hub

# install a chart (creates a release)
helm install my-nginx bitnami/nginx --namespace web --create-namespace

# upgrade an existing release
helm upgrade my-nginx bitnami/nginx --set replicaCount=3

# upgrade + install in one idempotent command
helm upgrade --install my-nginx bitnami/nginx -f values.yaml

# uninstall
helm uninstall my-nginx -n web

# list releases
helm list -n web
helm list --all-namespaces

チャートの構造

チャートはテンプレート化された YAML とデフォルト値のディレクトリです。Chart.yaml がメタデータ、values.yaml がデフォルト値、templates/ がその値で描画される Go テンプレートを持ちます。helm create が動くチャートの雛形を作り、helm lint は公開前にスキーマ/テンプレートのエラーを捉えます。

kubernetes
my-chart/
├── Chart.yaml          # chart metadata (name, version, apiVersion)
├── values.yaml         # default values (overridable)
├── charts/             # chart dependencies (subcharts)
├── templates/          # Go-templated YAML
│   ├── deployment.yaml
│   ├── service.yaml
│   ├── _helpers.tpl    # named templates (partials)
│   └── NOTES.txt       # post-install notes
├── templates.yaml      # (optional) CRDs to install before templates
└── README.md

# create a new chart skeleton
helm create my-chart

# lint a chart
helm lint my-chart

# package into a .tgz
helm package my-chart

values と上書き

values.yaml はチャートのデフォルトを持ちます。--set(スカラー用)や -f(ファイル全体用)で上書きします。helm show values はチャートが受け付ける全キーを一覧します。helm template はクラスタに触れずにマニフェストを描画します。リリースが実際に何を適用するかの差分確認に不可欠です。

kubernetes
# values.yaml (chart defaults)
image:
  repository: nginx
  tag: "1.25"
replicaCount: 2
service:
  type: ClusterIP
  port: 80

# override on the command line
helm upgrade --install web my-chart \
  --set replicaCount=5 \
  --set image.tag=1.26 \
  --set service.type=LoadBalancer

# override from a file
helm upgrade --install web my-chart -f prod-values.yaml

# see all values a chart supports
helm show values bitnami/nginx

# rendered output (debug, no install)
helm template web my-chart -f prod-values.yaml

テンプレートと組み込みオブジェクト

テンプレートは Sprig 関数付きの Go テンプレート構文を使います。.Release.Name で毎回の install が一意になり、.Values がチャートの値を公開し、.Chart が Chart.yaml から取ります。default 関数がフォールバックを提供します。.Release.Name による安全な命名で、1 つのチャートが同じ名前空間で多数のリリースを持てます。

kubernetes
# built-in template objects:
#   .Values         chart values (after overrides)
#   .Release        release metadata (Name, Namespace, Service, Revision, IsInstall, IsUpgrade)
#   .Chart          Chart.yaml contents
#   .Files          files in the chart
#   .Capabilities   cluster capabilities (KubeVersion, APIVersions)
#   .Template       current template info

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Release.Name }}-app
  labels:
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
  replicas: {{ .Values.replicaCount | default 1 }}
  selector:
    matchLabels:
      app: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app: {{ .Release.Name }}

Helm リポジトリ

Helm 3 は従来の HTTP チャートリポジトリと OCI レジストリの両方に対応しています(helm push/pull oci://…)。OCI がモダンで署名に優れた経路です。helm repo update がインデックスを更新するので、upgrade の前に必ず実行して最新のチャートバージョンを得ましょう。Artifact Hub(helm search hub)が公開チャートのインデックスです。

kubernetes
# add a chart repository
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo add jetstack https://charts.jetstack.io

# list configured repos
helm repo list

# update repo indexes
helm repo update

# remove a repo
helm repo remove bitnami

# push to OCI registry (Helm 3+)
helm registry login registry.example.com
helm package my-chart
helm push my-chart-0.1.0.tgz oci://registry.example.com/charts

# pull an OCI chart
helm pull oci://registry.example.com/charts/my-chart --version 0.1.0

ロールバックと履歴

install/upgrade のたびに番号付きのリビジョンが Secret として保存されます。helm rollback は前のリビジョンへ即座に切り替えます。素の kubectl apply に対する Helm の決定的な強みです。helm get values は実際にデプロイされた値を示し、ドリフトした状態のデバッグに非常に役立ちます。

kubernetes
# view release history
helm history my-nginx -n web

# rollback to a previous revision
helm rollback my-nginx 1 -n web

# get rendered manifests of a deployed release
helm get manifest my-nginx -n web

# get the values used at install/upgrade
helm get values my-nginx -n web
helm get values my-nginx -n web --all   # incl. chart defaults

# get all info (hooks, manifest, values, notes)
helm get all my-nginx -n web

# wait for resources to be ready on install/upgrade
helm upgrade --install my-nginx bitnami/nginx --wait --timeout 5m
17

NetworkPolicy

NetworkPolicy マニフェスト

NetworkPolicy は Pod 向けのファイアウォールルールです。空の podSelector は名前空間内の全 Pod を選び、空のルールリストはその型の全トラフィックを拒否します。NetworkPolicy は加算的で、どれか 1 つのポリシーが許せば Pod は許可されます。対応する CNI が必要で、素の flannel は無視します。

kubernetes
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: prod
spec:
  podSelector: {}             # selects ALL pods in the namespace
  policyTypes:
    - Ingress
    - Egress
  # no ingress/egress rules => deny all traffic of that type
# effect: pods in 'prod' can't send or receive ANY traffic
# until another policy explicitly allows it

# REQUIRES a CNI that supports NetworkPolicy
# (Calico, Cilium, Weave, kube-router; NOT flannel alone)

Ingress ルール

Ingress ルールは選択された Pod への入りトラフィックを許可します。from エントリは OR、ports も OR です。podSelector は同じ名前空間の Pod に一致し、namespaceSelector は名前空間全体に一致します(自動追加の kubernetes.io/metadata.name ラベルを使いましょう)。1 つの項目に両方入れると AND になります。

kubernetes
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-web
  namespace: prod
spec:
  podSelector:
    matchLabels:
      app: web
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:               # pods in same namespace
            matchLabels:
              app: gateway
        - namespaceSelector:         # whole other namespace
            matchLabels:
              kubernetes.io/metadata.name: monitoring
        - ipBlock:                   # external CIDR
            cidr: 10.0.0.0/8
      ports:
        - protocol: TCP
          port: 8080

Egress ルール

Egress ルールは選択された Pod がどこへ話せるかを制御します。よくある落とし穴: デフォルト拒否の egress が DNS 解決を壊し、Pod が kube-dns に届かなくなります。他をすべて拒否する前に、kube-system 名前空間への UDP/TCP 53 を必ず許可しましょう。ipBlock.except で例外を切り出せます。

kubernetes
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-egress-dns
  namespace: prod
spec:
  podSelector:
    matchLabels:
      app: web
  policyTypes:
    - Egress
  egress:
    - to:
        - namespaceSelector: {}     # any namespace (kube-dns)
      ports:
        - protocol: UDP
          port: 53
    - to:
        - ipBlock:
            cidr: 0.0.0.0/0
            except:
              - 10.0.0.0/8          # allow internet, deny internal
      ports:
        - protocol: TCP
          port: 443

# WARNING: egress deny-all blocks DNS and breaks pods.
# Always allow kube-dns first.

セレクターと名前空間の選択

裸の podSelector はポリシー自身の名前空間の Pod に一致します。namespaceSelector は名前空間全体に一致します。1 つの項目に podSelector と namespaceSelector の両方を書くと AND(名前空間 Y のラベル X の Pod)になり、別々の項目にすると OR になります。ipBlock は外部 IP に一致します。

kubernetes
spec:
  podSelector:                       # selects pods in THIS namespace
    matchLabels:
      app: web
  ingress:
    - from:
        # SAME namespace, matching pods
        - podSelector:
            matchLabels:
              app: gateway

        # DIFFERENT namespace (whole namespace)
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: monitoring

        # BOTH: pods in another namespace with specific labels
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: backend
          podSelector:
            matchLabels:
              app: api

        # external IP range
        - ipBlock:
            cidr: 192.168.1.0/24

デフォルトポリシー(全拒否/全許可)

デフォルト拒否のポリシー(空のルール)は名前空間をロックダウンし、明示的な許可リストだけが穴を開けます。基準として deny-all ingress + deny-all egress を適用し、その後、狙った許可ポリシーを追加しましょう。空の ingress: [{}] はすべての ingress を許可します。オプトアウトのための逃げ道です。

kubernetes
# --- DEFAULT DENY INGRESS (in a namespace) ---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: prod
spec:
  podSelector: {}
  policyTypes: [Ingress]
---
# --- DEFAULT DENY EGRESS ---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-egress
  namespace: prod
spec:
  podSelector: {}
  policyTypes: [Egress]
---
# --- ALLOW ALL INGRESS (whitelist opt-out) ---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-all-ingress
  namespace: prod
spec:
  podSelector: {}
  policyTypes: [Ingress]
  ingress:
    - {}      # allow from anywhere

ポリシー型とデフォルト挙動

NetworkPolicy は加算的です。どれかのポリシーが Pod を選んだ時点で、そのトラフィック型は明示的なルールがない限りデフォルト拒否になります。ポリシーがまったくなければすべて開放です。Pod のラベルに一致するポリシーを一覧すれば、何がトラフィックを支配しているか分かります。

kubernetes
spec:
  policyTypes:
    - Ingress
    - Egress
  # if omitted, defaults are inferred:
  #   - Ingress is always present (a policy always affects ingress)
  #   - Egress is implied if any egress rule exists

# key behaviors:
# - policies are ADDITIVE: a pod is allowed if ANY matching
#   policy permits the traffic
# - if NO policy selects a pod => all traffic allowed (default open)
# - if at least one policy selects a pod => default deny for that type
#   unless an explicit rule allows it

# inspect effective policies for a pod
kubectl get networkpolicy -n prod -l app=web
18

RBAC

Role(名前空間スコープ)

Role は 1 つの名前空間内の名前空間スコープのリソースに対する権限を与えます。rules は apiGroups、resources、verbs を列挙します。pods/log はサブリソースで、pods/exec は create 動詞を要求します(exec がサブリソースを作るため)。'*' で任意の値のワイルドカードです。

kubernetes
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pod-reader
  namespace: dev
rules:
  - apiGroups: [""]
    resources: ["pods", "pods/log"]
    verbs: ["get", "list", "watch"]
  - apiGroups: [""]
    resources: ["pods/exec"]
    verbs: ["create"]
# a Role grants permissions WITHIN one namespace
# verbs: get, list, watch, create, update, patch, delete, deletecollection, "*"
# apiGroups: "" (core), "apps", "batch", "rbac.authorization.k8s.io", ...

RoleBinding

RoleBinding は Role(または 1 名前空間に限定した ClusterRole)を subject(User、Group、ServiceAccount)に与えます。バインディングは権限が適用される名前空間に置きます。roleRef は不変で、参照先の Role を変えるにはバインディングを削除して再作成します。

kubernetes
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: dev
subjects:
  - kind: User
    name: alice
    apiGroup: rbac.authorization.k8s.io
  - kind: ServiceAccount
    name: my-sa
    namespace: dev
  - kind: Group
    name: dev-team
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io
# binds the Role to users, groups, or service accounts
# RoleBinding can also reference a ClusterRole (scoped to its namespace)

ClusterRole と ClusterRoleBinding

ClusterRole はクラスタスコープのリソース(node、namespace、PV)に対する権限を与えます。Role はこれらに触れられません。ClusterRole は RoleBinding で任意の名前空間に結び付け、再利用できます(1 回定義、多数にバインド)。ClusterRoleBinding は ClusterRole をクラスタ全体に与えます。

kubernetes
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: node-reader
rules:
  - apiGroups: [""]
    resources: ["nodes"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: read-nodes
subjects:
  - kind: ServiceAccount
    name: monitor
    namespace: kube-system
roleRef:
  kind: ClusterRole
  name: node-reader
  apiGroup: rbac.authorization.k8s.io
# ClusterRole grants cluster-scoped resources (nodes, PVs, namespaces)
# or can be reused across namespaces via a RoleBinding

動詞、リソース、API グループ

apiGroups はリソースをグループ化します。core は ''(空文字列)、apps に Deployment/StatefulSet、batch に Job/CronJob があります。サブリソース(pods/log、pods/exec、pods/portforward)は別の権限です。resourceNames はルールを特定のインスタンスに限定します。nonResourceURLs は /healthz、/metrics などをカバーします。

kubernetes
rules:
  - apiGroups: [""]                        # core API group
    resources: ["pods", "services", "configmaps", "secrets"]
    verbs: ["get", "list", "watch"]
  - apiGroups: ["apps"]
    resources: ["deployments", "replicasets", "statefulsets"]
    verbs: ["*"]
  - apiGroups: ["batch"]
    resources: ["jobs", "cronjobs"]
    verbs: ["create", "delete", "get"]
  - apiGroups: [""]
    resources: ["pods/log", "pods/exec", "pods/portforward"]
    verbs: ["get", "create"]
  - nonResourceURLs: ["/healthz", "/healthz/*"]   # non-resource URLs
    verbs: ["get"]

# resourceNames: restrict to specific instances
  - apiGroups: [""]
    resources: ["configmaps"]
    resourceNames: ["my-config"]
    verbs: ["get"]

ServiceAccount

ServiceAccount は Pod のための ID です。serviceAccountName で割り当てると、トークンが /var/run/secrets/kubernetes.io/serviceaccount に自動マウントされます。1.24 以降、SA には恒久的なトークン Secret がなく、kubectl create token で短命で時間制限のあるトークンを作ります。automountServiceAccountToken: false でオプトアウトできます。

kubernetes
# create a service account
kubectl create serviceaccount my-sa -n dev

# assign a RoleBinding (see RoleBinding example)
# mount the SA in a pod
apiVersion: v1
kind: Pod
metadata:
  name: app
spec:
  serviceAccountName: my-sa
  automountServiceAccountToken: false   # opt out of token mount
  containers:
    - name: app
      image: myapp:1.0

# short-lived tokens (1.24+) - no permanent secret
kubectl create token my-sa -n dev --duration=1h

# list SAs
kubectl get sa -n dev

kubectl auth can-i

kubectl auth can-i は現在の(またはなりすましの)ユーザーの RBAC 権限をチェックします。forbidden エラーのデバッグに不可欠です。--list は許可されているすべての動詞/リソースを示し、--as はテストのためにユーザー/SA になりすます。組み込みロール(view、edit、admin、cluster-admin)が一般的なニーズをカバーします。

kubernetes
# check if you can do something
kubectl auth can-i create pods -n dev
kubectl auth can-i delete deployments -n prod

# check on behalf of another user/SA
kubectl auth can-i list secrets --as=system:serviceaccount:dev:my-sa -n dev

# check all allowed verbs on a resource
kubectl auth can-i --list --as=alice -n dev

# whoami (1.25+)
kubectl auth whoami

# reconcile: detect over-privileged bindings
kubectl get rolebindings,clusterrolebindings --all-namespaces -o wide

# common built-in cluster roles:
#   view, edit, admin, cluster-admin
19

Probe(Liveness/Readiness/Startup)

Liveness Probe

Liveness probe は kubelet にコンテナをいつ再起動すべきか伝えます。failureThreshold 回連続で失敗すると、kubelet がコンテナを停止し、再起動ポリシーが適用されます。デッドロックや回復不能な状態からの復帰に使うもので、依存のチェックには使いません(それは readiness です)。

kubernetes
apiVersion: v1
kind: Pod
metadata:
  name: app
spec:
  containers:
    - name: app
      image: myapp:1.0
      livenessProbe:
        httpGet:
          path: /healthz
          port: 8080
        initialDelaySeconds: 15
        periodSeconds: 10
        timeoutSeconds: 2
        failureThreshold: 3
        successThreshold: 1
# if the probe fails failureThreshold times in a row,
# kubelet kills and restarts the container (per restartPolicy)

Readiness Probe

Readiness probe は Pod が Service からトラフィックを受けるかどうかを制御します。失敗すると Pod の IP がエンドポイントから外れますが、再起動はしません。ウォームアップ(準備ができるまでルーティングしない)や、一時的な障害や優雅なシャットダウンの間のトラフィック遮断に使いましょう。

kubernetes
apiVersion: v1
kind: Pod
metadata:
  name: app
spec:
  containers:
    - name: app
      image: myapp:1.0
      readinessProbe:
        httpGet:
          path: /ready
          port: 8080
        initialDelaySeconds: 5
        periodSeconds: 5
        failureThreshold: 3
# a failing readiness probe REMOVES the pod from service endpoints,
# but does NOT restart the container.
# use to drain traffic during deploys, warm-up, or transient outages.

Startup Probe

Startup probe(1.18+)は起動の遅いアプリ(Java、レガシーサーバー)向けです。これが動いている間、liveness と readiness は無効なので、遅い起動が liveness に殺されません。startup が成功すると liveness/readiness が有効になります。起動のために failureThreshold × periodSeconds を長めに取りましょう。

kubernetes
apiVersion: v1
kind: Pod
metadata:
  name: slow-app
spec:
  containers:
    - name: app
      image: myapp:1.0
      startupProbe:
        httpGet:
          path: /startup
          port: 8080
        failureThreshold: 30
        periodSeconds: 10      # up to 300s to start
      livenessProbe:
        httpGet:
          path: /healthz
          port: 8080
        periodSeconds: 10
# while the startup probe runs, liveness/readiness are disabled.
# once startup succeeds, liveness/readiness take over.

Probe のハンドラー

ハンドラーは 3 種類です。httpGet(成功 = HTTP 2xx/3xx)、tcpSocket(成功 = TCP 接続)、exec(成功 = 終了コード 0)。gRPC probe(1.27+ GA)は gRPC サービスにはきれいな選択肢です。httpGet が推奨です。アプリが「健全だが忙しい」(503)を再起動なしで伝えられるからです。exec はもろいです(イメージにシェル/バイナリが必要)。

kubernetes
# three handler types:

# 1. HTTP GET (most common) - success = 200-399
livenessProbe:
  httpGet:
    path: /healthz
    port: 8080
    httpHeaders:
      - name: X-Custom
        value: probe
    scheme: HTTP

# 2. TCP socket - success = port open
livenessProbe:
  tcpSocket:
    port: 3306

# 3. Exec - success = exit code 0
livenessProbe:
  exec:
    command:
      - /bin/sh
      - -c
      - "pg_isready -h localhost"

# gRPC (1.24+, alpha -> GA): use grpc probe
livenessProbe:
  grpc:
    port: 9090
    service: my.package.Health

Probe のパラメータ

initialDelaySeconds は最初の probe を遅らせますが、遅い起動には startup probe のほうがきれいです。periodSeconds が周期で、failureThreshold × periodSeconds が対処までの許容時間です。速いフェイルオーバーには締め、寛容さには緩めましょう。terminationGracePeriodSeconds がシャットダウンの上限です。

kubernetes
livenessProbe:
  httpGet:
    path: /healthz
    port: 8080
  initialDelaySeconds: 15   # wait before first probe (after start)
  periodSeconds: 10         # probe every 10s
  timeoutSeconds: 2         # max time per probe
  successThreshold: 1       # consecutive successes to mark OK
  failureThreshold: 3       # consecutive failures to mark failed
  terminationGracePeriodSeconds: 30  # (liveness) grace before SIGKILL

# tuning tips:
# - set initialDelaySeconds > typical startup time
# - OR use a startup probe instead (cleaner)
# - shorter period = faster reaction, more load
# - higher failureThreshold = more tolerant of blips

Probe 失敗時の挙動

Liveness の失敗はその場でコンテナを停止・再起動します(再スケジュールはしません)。Readiness の失敗は Service から Pod を外すだけで、再起動はしません。Startup の失敗は liveness と同じ挙動です。Liveness の flapping は、遅い下流サービスに依存する probe が原因であることが多いです。ヘルスチェックは局所的で安価に保ちましょう。

kubernetes
# --- LIVENESS FAIL ---
#   container killed -> restarted (per restartPolicy: Always/OnFailure)
#   pod stays on the same node (NOT rescheduled)
#   CrashLoopBackOff if it keeps failing

# --- READINESS FAIL ---
#   pod stays running, but is REMOVED from Service endpoints
#   no traffic until it succeeds again
#   NOT restarted by kubelet

# --- STARTUP FAIL ---
#   container killed and restarted (like liveness)
#   liveness/readiness never activate
#   after failureThreshold × periodSeconds, pod is stuck restarting

# check probe results:
kubectl describe pod app | grep -A5 "Last State"
kubectl get pod app -o jsonpath='{.status.containerStatuses[*].state}'

# common cause of flapping: liveness probe hitting a slow dependency
20

リソースと高度な kubectl

requests と limits

requests はスケジューラが確保する量です(ノードに余剰の requests があれば Pod はスケジュールされる)。定常状態の必要量に設定しましょう。limits は硬い上限で、CPU はスロットルされ、メモリは OOMKilled されます。cpu はコア単位(500m = 0.5)、memory はバイト単位(Mi/Gi)です。本番では両方必ず設定しましょう。

kubernetes
spec:
  containers:
    - name: app
      image: myapp:1.0
      resources:
        requests:           # what the scheduler guarantees (reservation)
          cpu: 250m          # 250 millicores = 0.25 core
          memory: 256Mi      # 256 mebibytes
          ephemeral-storage: 1Gi
        limits:             # hard ceiling (enforced)
          cpu: "1"           # 1 core
          memory: 512Mi
          ephemeral-storage: 2Gi

# cpu limit: throttled (cfs quota)
# memory limit: OOMKilled if exceeded
# ephemeral-storage limit: evicted if exceeded
# request only (no limit): best-effort burst

LimitRange のデフォルト

LimitRange は指定のない Pod にデフォルトの requests/limits を適用します。ResourceQuota が requests を要求するときには決定的です。max/min が 1 コンテナの上限/下限を決め、maxLimitRequestRatio は request をどれだけ超えられるかを制限し、うるさい隣人を防ぎます。

kubernetes
apiVersion: v1
kind: LimitRange
metadata:
  name: defaults
  namespace: prod
spec:
  limits:
    - type: Container
      default:               # applied as LIMITS when not set
        cpu: 500m
        memory: 512Mi
      defaultRequest:        # applied as REQUESTS when not set
        cpu: 100m
        memory: 128Mi
      max:                   # max allowed LIMITS
        cpu: "4"
        memory: 8Gi
      min:                   # min allowed REQUESTS
        cpu: 50m
        memory: 64Mi
      maxLimitRequestRatio:  # limit/request ratio cap (burst cap)
        cpu: "4"

# a pod with no resources gets default/defaultRequest applied
# a pod with limit=4cpu, request=50m would breach maxLimitRequestRatio

Horizontal Pod Autoscaler

HPA はメトリクス(metrics-server 経由の CPU/メモリ、または Prometheus Adapter 経由のカスタム/外部メトリクス)に基づいてレプリカ数をスケールします。behavior(v2)が積極さを調整します。stabilizationWindowSeconds が flapping を防ぎ、policies が 1 分あたりの変化率を制限します。スケールアップは通常速く積極的で、スケールダウンは意図的に遅いです。

kubernetes
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: web
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web
  minReplicas: 3
  maxReplicas: 50
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization          # avg across pods
          averageUtilization: 70
    - type: Resource
      resource:
        name: memory
        target:
          type: Utilization
          averageUtilization: 80
  behavior:                          # (v2) scale up/down tuning
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - type: Percent
          value: 50                  # max 50% down per minute
          periodSeconds: 60
    scaleUp:
      stabilizationWindowSeconds: 0
      policies:
        - type: Percent
          value: 100
          periodSeconds: 60

# requires metrics-server for CPU/memory
kubectl get hpa web -w

Pod Disruption Budget

PodDisruptionBudget は、集合内の何個までの Pod を一度に自発的に追い出せるかを制限します。ノードの drain や cluster-autoscaler の操作中の可用性を守ります。minAvailable か maxUnavailable のどちらか一方を使います。非自発的な障害(ハードウェア故障)は防げません。それを守るのはレプリカだけです。

kubernetes
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: web-pdb
  namespace: prod
spec:
  minAvailable: 2            # at least 2 pods always available
  # OR
  # maxUnavailable: 1        # at most 1 down at a time
  selector:
    matchLabels:
      app: web
# PDB protects against VOLUNTARY disruptions:
#   - kubectl drain (node maintenance)
#   - cluster autoscaler evictions
#   - kubectl delete pod (controller-managed)
# It does NOT prevent INVOLUNTARY disruptions (node failure, kernel panic).

# check PDB status
kubectl get pdb -n prod
kubectl describe pdb web-pdb -n prod

Taint、Toleration、Affinity

Taint は Pod をはじき、Toleration は特定の Pod に無視させます。ノードを専用化する(GPU、ingress、コントロールプレーン)のに使います。nodeAffinity は特定のノードを優先/要求します。podAntiAffinity はレプリカをトポロジードメイン(ホスト、ゾーン)に広げて HA を実現します。taint の除去は同じ key+effect に末尾のダッシュを付けます。

kubernetes
# taint a node
kubectl taint nodes node-1 dedicated=gpu:NoSchedule

# tolerate the taint so a pod can schedule there
spec:
  tolerations:
    - key: dedicated
      operator: Equal
      value: gpu
      effect: NoSchedule

# prefer specific nodes
spec:
  affinity:
    nodeAffinity:
      preferredDuringSchedulingIgnoredDuringExecution:
        - weight: 100
          preference:
            matchExpressions:
              - key: disktype
                operator: In
                values: [ssd]
    podAntiAffinity:               # spread replicas across nodes
      requiredDuringSchedulingIgnoredDuringExecution:
        - topologyKey: kubernetes.io/hostname
          labelSelector:
            matchLabels:
              app: web

# remove a taint
kubectl taint nodes node-1 dedicated=gpu:NoSchedule-

高度な kubectl(patch/wait/top/debug)

patch は JSON、strategic-merge、merge の各型に対応します。wait は条件が満たされるまでブロックし、スクリプトに最適です。top はライブの CPU/メモリを表示します(metrics-server が必要)。kubectl debug は実行中の Pod に一時コンテナを付け(distroless イメージに便利)、ノード上でシェルを開けます。

kubernetes
# JSON patch (precise field ops)
kubectl patch deployment web --type json -p \
  '[{"op":"replace","path":"/spec/replicas","value":3}]'

# strategic merge patch (default for k8s objects)
kubectl patch svc web -p '{"spec":{"type":"NodePort"}}'

# wait for a condition
kubectl wait --for=condition=Ready pod/web --timeout=60s
kubectl wait --for=delete pod/web --timeout=30s

# resource usage (needs metrics-server)
kubectl top nodes
kubectl top pods -n prod
kubectl top pod web --containers

# ephemeral debug container (1.25+)
kubectl debug -it web --image=busybox --target=web
# debug a node
kubectl debug node/node-1 -it --image=ubuntu

# run a one-off pod
kubectl run tmp --rm -it --image=alpine -- sh

# explain a field
kubectl explain pod.spec.containers.resources

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.