This resume is also available in English.

6. Deploying the system3 / 14 · All columns

Columns › 6. Deploying the system › Part 30

A Kubernetes Configuration Reference: What to Write in Each Field, and Why

Kubernetes 配置參考:每個欄位怎麼寫、為什麼這樣寫

Turn the previous article’s setup into a reference you can check against: namespace guardrails (Pod Security, ResourceQuota, LimitRange), ServiceAccounts and RBAC, every key field of the Pod template, ConfigMaps and Secrets, Jobs and CronJobs, HPA and PDB, and finally the validation tools and checklist before going live.

  • Kubernetes
  • YAML
  • Security
  • DevOps
In this article
  1. What this article solves
  2. Step 1: Which resources surround a service
  3. Step 2: Namespace guardrails
  4. Step 3: Identity and permissions: ServiceAccounts and RBAC
  5. Step 4: A quick reference for the Pod template
  6. Step 5: ConfigMaps and Secrets
  7. Step 6: Jobs and CronJobs
  8. Step 7: Availability: HPA, PDB and priority
  9. Step 8: Validation tools before going live
  10. Step 9: The pre-launch checklist
  11. Common pitfalls
  12. Key takeaways
  13. References
  14. Next

The previous article, “Deploying a Microservice System on Kubernetes”, put api-gateway, order, payment and inventory on a cluster. It followed the order of getting the system running; this one takes another angle and organises everything by resource kind into a reference: which fields each resource should have, why, and what goes wrong without them, plus what the previous article didn’t go into (permissions, namespace guardrails, scheduled jobs, validation tools). Use it as a checklist when you write a new service or review someone else’s YAML.

What this article solves

Kubernetes YAML has an awkward property: many fields can be left out and it still runs. With no resource requests, the Pod starts; with no probes, the rolling update completes; the Pod mounts its ServiceAccount token by default and nobody notices. Until one day a single service eats a node’s memory, a new version takes traffic before it’s ready, or a compromised container uses that token to read every Secret in the namespace.

This article sets up what every service should have:

  1. Which resources surround a service, and what each one is for.
  2. Namespace guardrails: Pod Security, ResourceQuota, LimitRange.
  3. Identity and permissions: ServiceAccounts, token mounting and least-privilege RBAC.
  4. A quick reference for the Pod template’s key fields: image, resources, probes, security, shutdown and scheduling.
  5. ConfigMaps and Secrets: how updates take effect, and why a Secret isn’t encrypted.
  6. Job and CronJob fields: retries, timeouts, cleanup and concurrency.
  7. Availability: HPA scaling behaviour, PDBs and priority.
  8. Validation tools before going live, and a checklist.

The example continues the series: namespace shop, configuration in deploy/k8s/ (base and overlays), images at registry.example.com/shop/<service>.

Step 1: Which resources surround a service

Namespace shop Pod Security (restricted) · ResourceQuota · LimitRange Service order ServiceAccount + RBAC its own identity, no auto-mounted token Pod template (Deployment) image, resources, probes, security, shutdown ConfigMap / Secret generated with a hash; Secrets not in git Service stable name, address NetworkPolicy who may connect Gateway / HTTPRoute only the entry is open HPA scales on requests PDB how many stay in upkeep PriorityClass who stays when short The outer guardrails keep a service that forgot something in check; the middle is what every service writes; the sides let it be found, reached only by the right callers, and stay up while scaling and during maintenance.

Figure: the outer layer is the namespace’s guardrails, the middle is the service itself (identity, Pod template, configuration), and the sides make it reachable and keep it up through scaling and maintenance.

ResourceWhat it’s forWithout it
Namespace + Pod Security labelsThe boundary of an environment; limits what kind of Pod may runAny Pod may run as root or privileged
ResourceQuota / LimitRangeTotals for the namespace, defaults per containerOne service without requests starves a node
ServiceAccount + RBACThe Pod’s identity and what it may do with the APIThe default token is auto-mounted, the boundary unclear
DeploymentWhat runs, how many, how it updates—
ServiceA stable name and addressOther services can’t find it
ConfigMap / SecretConfiguration and secretsConfiguration baked into the image
HPAReplicas follow the loadCan’t take a peak, or wastes capacity off-peak
PDBHow many must stay during maintenance (draining nodes)Every replica evicted at once during a node upgrade
NetworkPolicyWho may connect to itAny Pod in the namespace can connect

The previous article already wrote the Deployment, Service, ConfigMap, HPA, PDB and NetworkPolicy. This one adds the outer guardrails and permissions, and puts the reason for every field in one place.

Step 2: Namespace guardrails

A namespace isn’t just a folder for sorting; it’s where you apply rules in bulk. Three resources together keep a service that “forgot something” from getting out of hand.

Pod Security. Kubernetes’ built-in Pod Security Admission checks every Pod against one of three levels, chosen by labels on the namespace: privileged (no restrictions), baseline (blocks obviously dangerous settings) and restricted (non-root, capabilities dropped, seccomp required and so on). The previous article’s Pods are already written for restricted, so production enforces it:

# deploy/k8s/overlays/prod/namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: shop
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/enforce-version: latest
    pod-security.kubernetes.io/warn: restricted
    pod-security.kubernetes.io/audit: restricted

enforce rejects non-compliant Pods; warn prints a warning on kubectl apply; audit writes to the audit log. To tighten an existing namespace, add only warn and audit first, and add enforce once a while has passed without warnings.

ResourceQuota. Caps what the whole namespace may use:

# deploy/k8s/overlays/prod/quota.yaml
apiVersion: v1
kind: ResourceQuota
metadata:
  name: shop-quota
spec:
  hard:
    requests.cpu: '20'
    requests.memory: 40Gi
    limits.memory: 80Gi
    pods: '200'
    services.loadbalancers: '0'

The last line is worth a note: services.loadbalancers: "0" stops the namespace from creating its own cloud load balancers (each costs money and bypasses the Gateway); the only way in is the Gateway. Note too: once a namespace has a quota on something like requests.cpu, every container must declare that request, or the Pod is rejected; the next resource supplies defaults for exactly that.

LimitRange. Fills in defaults for containers that didn’t write them, and bounds a single container:

# deploy/k8s/overlays/prod/limitrange.yaml
apiVersion: v1
kind: LimitRange
metadata:
  name: shop-defaults
spec:
  limits:
    - type: Container
      defaultRequest:
        cpu: 100m
        memory: 128Mi
      default:
        memory: 256Mi
      max:
        memory: 4Gi

defaultRequest applies when requests are missing, default when limits are missing. This is a safety net, not a design: every service should still write its own measured values (step 4).

Step 3: Identity and permissions: ServiceAccounts and RBAC

Every Pod runs as some ServiceAccount, the namespace’s default if none is named. And by default, that identity’s token is mounted into the container (/var/run/secrets/kubernetes.io/serviceaccount/). None of the shop’s four services calls the Kubernetes API; the only use that token will ever have is to an attacker who gets into the container.

So give each service its own ServiceAccount and turn auto-mounting off:

# deploy/k8s/base/order/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: order
  labels:
    app.kubernetes.io/name: order
automountServiceAccountToken: false

Add serviceAccountName: order to the Deployment’s Pod template. Each service runs as itself, so if one later needs cloud permissions (say through workload identity, to read object storage), only that one gets them.

A component that really needs the API (say an operations tool that reads a ConfigMap) gets least privilege through a Role and RoleBinding: one namespace, only the resources and verbs it needs, and if necessary only specific objects via resourceNames.

# example: may read only the ConfigMap named feature-flags in namespace shop
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: read-feature-flags
  namespace: shop
rules:
  - apiGroups: ['']
    resources: ['configmaps']
    resourceNames: ['feature-flags']
    verbs: ['get', 'watch']
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: flags-reader
  namespace: shop
subjects:
  - kind: ServiceAccount
    name: flags-reader
    namespace: shop
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: read-feature-flags

Three rules are enough to remember: prefer a Role to a ClusterRole; never grant list or watch on secrets (being able to list them is being able to read them all); no * wildcards. Check what an identity can do with kubectl auth can-i --list --as=system:serviceaccount:shop:flags-reader -n shop.

Step 4: A quick reference for the Pod template

The previous article’s order Deployment already has these fields. Here they are grouped by topic, to go through one by one in a review.

Image

FieldRecommendationWhy
imageAn immutable tag (the git SHA); in production you can add the digest (@sha256:…)latest can’t be traced or rolled back; a tag can be re-pushed, a digest can’t
imagePullPolicyLeave it out with immutable tags (defaults to IfNotPresent)With latest or no tag the default becomes Always, contacting the registry on every start
imagePullSecretsOnly for a private registry; put it on the ServiceAccount rather than every PodOne place to manage and rotate

Resources

FieldRecommendationWhy
requests.cpu / requests.memoryAlways, from measured normal usageThe scheduler places Pods by requests; HPA utilisation is relative to requests
limits.memoryAlways, a little above the measured peakExceeding it means OOMKilled, better than taking down the node; pair with GOMEMLIMIT
limits.cpuDepends; many teams leave it outExceeding a CPU limit doesn’t kill, it throttles, and latency gets erratic; without it the Pod can borrow idle CPU

Since Go 1.25 the runtime sets GOMAXPROCS from the container’s CPU limit automatically; if you set limits.cpu on an older Go, set it yourself (or use the automaxprocs package), or Go assumes every core on the node is available and gets throttled more.

The three probes

ProbeAsksOn failureCommon mistake
startupProbeHas it finished starting?Keeps failing: restartLeft out, so a slow starter is killed by liveness and starts over
readinessProbeCan it take traffic now?Removed from Service endpoints, not restartedChecks a dependency (database slows, every Pod leaves the endpoints)
livenessProbeIs it alive (or stuck)?Container restartedChecks dependencies, or is too strict, so a slow moment becomes a restart loop

The principle: liveness checks only the program itself (say, that it answers /livez), never the database; readiness may say “I don’t want new requests right now”, for example while shutting down.

Security

# Pod level
securityContext:
  runAsNonRoot: true
  seccompProfile:
    type: RuntimeDefault
# container level
securityContext:
  allowPrivilegeEscalation: false
  readOnlyRootFilesystem: true
  capabilities:
    drop: ['ALL']

These lines are what the restricted level requires. For a program that writes temporary files under readOnlyRootFilesystem, mount an emptyDir at /tmp.

Shutdown and scheduling

FieldRecommendationWhy
terminationGracePeriodSecondsLonger than the program’s shutdown timeout plus the preStop waitWhen it runs out, SIGKILL, and in-flight requests are cut off
lifecycle.preStopWait a few secondsLet the endpoint removal propagate before shutting down
topologySpreadConstraintsSpread across nodes (and zones)A failing node or zone doesn’t take every replica
priorityClassNameHigher priority for core servicesWhen resources run short, batch jobs are evicted before payments
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
  name: shop-critical
value: 100000
globalDefault: false
description: 'Payments, orders and other services that directly affect transactions'

Step 5: ConfigMaps and Secrets

A Pod doesn’t notice when its configuration changes. A ConfigMap read as environment variables (envFrom) only takes effect after the Pod restarts; one mounted as files is updated, but the program has to re-read it. The most dependable approach is the previous article’s Kustomize configMapGenerator: it appends a hash of the content to the name (say order-config-7h2kf9), so when the content changes the name changes, the Deployment’s reference changes with it, a rolling update follows naturally, and a rollback brings the old configuration back too.

Configuration that won’t change again can be marked immutable: true: the API server stops watching it for changes, and nobody can kubectl edit production configuration in place.

A Secret is not encryption. A Secret’s content is only base64-encoded; anyone who can read the object can decode it. Protecting it takes three things:

  • Encryption at rest: have etcd store Secrets encrypted. Managed Kubernetes services can usually encrypt with the cloud’s key management service; self-managed clusters configure the API server’s encryption settings.
  • RBAC: only identities that really need it can read it (step 3); above all, no list.
  • Not in git: the previous article’s dev environment used a secretGenerator reading local files kept out of version control. In production it’s more common for the cluster to fetch secrets from an external secret manager (External Secrets Operator), or to keep an encrypted version in git (Sealed Secrets). With Argo CD in the next article this becomes a requirement, and it’s covered there.

On the program side, the previous articles’ DB_PASSWORD_FILE approach (reading a mounted file) beats environment variables, which easily end up in logs, error reports or child processes.

Step 6: Jobs and CronJobs

One-off migrations are Jobs, recurring work is a CronJob. The shop runs a reconciliation every night (the process from “Reconciliation: Matching Payment Provider Statements Reliably”), written as a CronJob:

# deploy/k8s/base/payment/reconcile-cronjob.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: payment-reconcile
  labels:
    app.kubernetes.io/name: payment-reconcile
spec:
  schedule: '30 3 * * *'
  timeZone: Asia/Taipei
  concurrencyPolicy: Forbid
  startingDeadlineSeconds: 600
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 5
  jobTemplate:
    spec:
      backoffLimit: 2
      activeDeadlineSeconds: 3600
      ttlSecondsAfterFinished: 86400
      template:
        metadata:
          labels:
            app.kubernetes.io/name: payment-reconcile
        spec:
          restartPolicy: Never
          serviceAccountName: payment
          securityContext:
            runAsNonRoot: true
            seccompProfile:
              type: RuntimeDefault
          containers:
            - name: reconcile
              image: registry.example.com/shop/payment:latest
              args: ['reconcile', '--date=yesterday']
              resources:
                requests:
                  cpu: 200m
                  memory: 256Mi
                limits:
                  memory: 512Mi
              securityContext:
                allowPrivilegeEscalation: false
                readOnlyRootFilesystem: true
                capabilities:
                  drop: ['ALL']
FieldDoesWithout it
timeZoneWhich time zone the schedule usesThe control plane’s (usually UTC): 3 a.m. becomes 11 a.m.
concurrencyPolicy: ForbidSkip this run if the last hasn’t finishedDefault Allow: when a run overruns, two reconciliations process the same day at once
startingDeadlineSecondsHow late a missed run may still startAfter a control plane outage, catch-up or skipping is hard to predict
backoffLimitHow many retries on failureDefault 6: a job that will always fail retries for a long time
activeDeadlineSecondsThe longest the whole Job may runA stuck job never ends (and with Forbid, blocks every later run)
ttlSecondsAfterFinishedHow long after finishing to delete itFinished Jobs and Pods pile up
restartPolicy: NeverA failure creates a new Pod rather than restarting in placeWith OnFailure, logs and failure records are harder to follow

Scheduled work must be safe to re-run. backoffLimit retries and a failed node recreates the Pod, so the same day may be reconciled twice. Use the approach from “Idempotency and Distributed Locks” so that running twice gives the same result as running once.

Step 7: Availability: HPA, PDB and priority

HPA scaling behaviour. By default, scaling down is cautious (it waits five minutes) and scaling up is eager. For spiky traffic, spell it out with behavior to stop the replica count from oscillating:

# deploy/k8s/base/order/hpa.yaml (the behavior part)
spec:
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 0
      policies:
        - type: Percent
          value: 100
          periodSeconds: 30
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - type: Pods
          value: 2
          periodSeconds: 60

That means: scale up immediately, at most doubling every 30 seconds; scale down only after five minutes, at most two Pods a minute. HPA computes utilisation against requests, so wrong requests mean wrong scaling.

Choosing a PDB. minAvailable says “keep at least this many”, maxUnavailable says “lose at most this many”. When HPA decides the replica count and it varies, maxUnavailable: 1 is less likely to cause trouble: minAvailable: 2 with only two replicas blocks node drains completely. A PDB only covers voluntary disruptions (draining, upgrades), not a node crashing.

Priority. The PriorityClass from step 4 makes core services the last to be evicted when resources run short. Batch work (reconciliation, reports) uses the default or a lower priority.

Step 8: Validation tools before going live

The later a YAML mistake is found, the more it costs. Check in layers in CI, cheapest first:

  1. Render the final result: kubectl kustomize deploy/k8s/overlays/prod. Reviews should look at the rendered result, not the scattered base and patches.
  2. Schema validation: use kubeconform to check field names and types against the Kubernetes schemas (a misspelt field is often silently ignored by kubectl apply).
  3. Policy checks: use kube-linter, Kyverno or Conftest for team rules such as “every container has requests and a memory limit”, “no latest”, “must runAsNonRoot”.
  4. Server-side dry run: kubectl apply --dry-run=server -k … has the API server validate for real (admission and Pod Security included) without writing anything.
  5. Diff: kubectl diff -k deploy/k8s/overlays/prod lists what this change will touch; stop at anything unexpected.
#!/usr/bin/env bash
# CI: validate the production configuration
set -euo pipefail
OUT="$(mktemp)"
kubectl kustomize deploy/k8s/overlays/prod > "$OUT"
kubeconform -strict -summary -ignore-missing-schemas "$OUT"
kube-linter lint "$OUT"

(-ignore-missing-schemas makes kubeconform skip custom resources it has no schema for, such as the Argo CD resources in the next article; to check those, supply their CRD schemas separately.)

Step 9: The pre-launch checklist

AreaCheck
NamespacePod Security labels (restricted in production), ResourceQuota, LimitRange
IdentityEach service has its own ServiceAccount, automountServiceAccountToken: false, RBAC grants only what’s needed
ImageImmutable tags (git SHA), never latest
ResourcesEvery container has requests and a memory limit; GOMEMLIMIT follows the limit
ProbesStartup, readiness and liveness all present; liveness doesn’t check dependencies
SecurityNon-root, read-only root filesystem, capabilities dropped, seccomp
ShutdownpreStop, enough terminationGracePeriodSeconds, the program handles SIGTERM
ConfigurationConfigMaps generated (hashed names); Secrets not in git, readable only by those who need them
AvailabilityHPA on requests, PDB with maxUnavailable, PriorityClass for core services, Pods spread across nodes
NetworkNetworkPolicy denies by default and opens only the paths needed; the only way in is the Gateway
JobsJobs/CronJobs have timeouts, retry limits and automatic cleanup; they’re safe to re-run
ValidationCI runs kustomize, kubeconform, policy checks, a server-side dry run and a diff

Common pitfalls

No requests. The scheduler thinks the Pod needs nothing and packs it onto a full node; HPA can’t compute utilisation.

Liveness checks the database. The database slows down and every Pod is restarted at once; a small incident becomes a big one.

Granting list secrets. Listing them means reading their contents; look for this line in every RBAC review.

Believing Secrets are encrypted. base64 isn’t encryption; without encryption at rest and RBAC, a Secret is little better than a ConfigMap.

A CronJob without a time zone and concurrencyPolicy. It runs at a time you didn’t expect, and two copies run at once when it overruns.

A PDB whose minAvailable equals the replica count. Nodes can never be drained and cluster upgrades get stuck.

Shipping after a local apply. Misspelt fields are silently ignored; validate schemas and dry-run on the server in CI.

Key takeaways

  • Around a service, besides the Deployment and Service, there are namespace guardrails, identity and permissions, configuration, scaling, maintenance and network rules; each “runs without it”, and each gets remembered during an incident.
  • Namespace: Pod Security labels (restricted in production; warn/audit first, then enforce), a ResourceQuota for totals, a LimitRange for defaults.
  • Each service gets its own ServiceAccount with token auto-mounting off; API access goes through a Role with least privilege, never list secrets, never *.
  • Pod template: immutable image tags; requests and a memory limit always, CPU limits depending; three probes with distinct jobs, liveness never checking dependencies; restricted-level security; enough shutdown time; spreading and priority.
  • Generated ConfigMaps make content changes trigger rolling updates; Secrets are only base64, protected by encryption at rest, RBAC and staying out of git.
  • Jobs/CronJobs spell out time zone, concurrency, retries, timeouts and cleanup, and the work itself must be safe to re-run.
  • Before going live, validate in layers in CI: render, schema check, policy check, server-side dry run, diff.

References

  • Pod Security Admission (official Kubernetes documentation): the enforce, audit and warn namespace label modes used in step 2.
  • Resource Quotas (official Kubernetes documentation): namespace totals and the LoadBalancer count quota, used for the ResourceQuota in step 2.
  • Limit Ranges (official Kubernetes documentation): default and defaultRequest filling in container defaults, used for the LimitRange in step 2.
  • Configure Service Accounts for Pods (official Kubernetes documentation): automountServiceAccountToken: false to stop the token being mounted, used in step 3.
  • Role Based Access Control Good Practices (official Kubernetes documentation): least privilege, avoiding wildcards and list on Secrets, the three rules in step 3.
  • Good practices for Kubernetes Secrets (official Kubernetes documentation): encryption at rest, least-privilege access and external secret stores, used in step 5.
  • CronJob (official Kubernetes documentation): timeZone, concurrencyPolicy and history limits, used for the reconciliation job in step 6.
  • Go 1.25 Release Notes (official Go documentation): the container-aware GOMAXPROCS default based on the cgroup CPU limit, mentioned in step 4.

Next

The configuration is now complete and validated, but it’s still applied by CI running kubectl apply with cluster admin rights. The next article, “GitOps with Argo CD: Let the Cluster Follow git on Its Own”, reverses the direction: git is the single source of truth, and Argo CD inside the cluster pulls, compares and applies on its own, putting things back when someone changes the cluster by hand.