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.
In this article
- What this article solves
- Step 1: Which resources surround a service
- Step 2: Namespace guardrails
- Step 3: Identity and permissions: ServiceAccounts and RBAC
- Step 4: A quick reference for the Pod template
- Step 5: ConfigMaps and Secrets
- Step 6: Jobs and CronJobs
- Step 7: Availability: HPA, PDB and priority
- Step 8: Validation tools before going live
- Step 9: The pre-launch checklist
- Common pitfalls
- Key takeaways
- References
- 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:
- Which resources surround a service, and what each one is for.
- Namespace guardrails: Pod Security, ResourceQuota, LimitRange.
- Identity and permissions: ServiceAccounts, token mounting and least-privilege RBAC.
- A quick reference for the Pod template’s key fields: image, resources, probes, security, shutdown and scheduling.
- ConfigMaps and Secrets: how updates take effect, and why a Secret isn’t encrypted.
- Job and CronJob fields: retries, timeouts, cleanup and concurrency.
- Availability: HPA scaling behaviour, PDBs and priority.
- 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
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.
| Resource | What it’s for | Without it |
|---|---|---|
| Namespace + Pod Security labels | The boundary of an environment; limits what kind of Pod may run | Any Pod may run as root or privileged |
| ResourceQuota / LimitRange | Totals for the namespace, defaults per container | One service without requests starves a node |
| ServiceAccount + RBAC | The Pod’s identity and what it may do with the API | The default token is auto-mounted, the boundary unclear |
| Deployment | What runs, how many, how it updates | — |
| Service | A stable name and address | Other services can’t find it |
| ConfigMap / Secret | Configuration and secrets | Configuration baked into the image |
| HPA | Replicas follow the load | Can’t take a peak, or wastes capacity off-peak |
| PDB | How many must stay during maintenance (draining nodes) | Every replica evicted at once during a node upgrade |
| NetworkPolicy | Who may connect to it | Any 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: restrictedenforce 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: 4GidefaultRequest 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: falseAdd 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-flagsThree 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
| Field | Recommendation | Why |
|---|---|---|
image | An 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 |
imagePullPolicy | Leave it out with immutable tags (defaults to IfNotPresent) | With latest or no tag the default becomes Always, contacting the registry on every start |
imagePullSecrets | Only for a private registry; put it on the ServiceAccount rather than every Pod | One place to manage and rotate |
Resources
| Field | Recommendation | Why |
|---|---|---|
requests.cpu / requests.memory | Always, from measured normal usage | The scheduler places Pods by requests; HPA utilisation is relative to requests |
limits.memory | Always, a little above the measured peak | Exceeding it means OOMKilled, better than taking down the node; pair with GOMEMLIMIT |
limits.cpu | Depends; many teams leave it out | Exceeding 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
| Probe | Asks | On failure | Common mistake |
|---|---|---|---|
startupProbe | Has it finished starting? | Keeps failing: restart | Left out, so a slow starter is killed by liveness and starts over |
readinessProbe | Can it take traffic now? | Removed from Service endpoints, not restarted | Checks a dependency (database slows, every Pod leaves the endpoints) |
livenessProbe | Is it alive (or stuck)? | Container restarted | Checks 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
| Field | Recommendation | Why |
|---|---|---|
terminationGracePeriodSeconds | Longer than the program’s shutdown timeout plus the preStop wait | When it runs out, SIGKILL, and in-flight requests are cut off |
lifecycle.preStop | Wait a few seconds | Let the endpoint removal propagate before shutting down |
topologySpreadConstraints | Spread across nodes (and zones) | A failing node or zone doesn’t take every replica |
priorityClassName | Higher priority for core services | When 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
secretGeneratorreading 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']| Field | Does | Without it |
|---|---|---|
timeZone | Which time zone the schedule uses | The control plane’s (usually UTC): 3 a.m. becomes 11 a.m. |
concurrencyPolicy: Forbid | Skip this run if the last hasn’t finished | Default Allow: when a run overruns, two reconciliations process the same day at once |
startingDeadlineSeconds | How late a missed run may still start | After a control plane outage, catch-up or skipping is hard to predict |
backoffLimit | How many retries on failure | Default 6: a job that will always fail retries for a long time |
activeDeadlineSeconds | The longest the whole Job may run | A stuck job never ends (and with Forbid, blocks every later run) |
ttlSecondsAfterFinished | How long after finishing to delete it | Finished Jobs and Pods pile up |
restartPolicy: Never | A failure creates a new Pod rather than restarting in place | With 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: 60That 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:
- Render the final result:
kubectl kustomize deploy/k8s/overlays/prod. Reviews should look at the rendered result, not the scattered base and patches. - Schema validation: use
kubeconformto check field names and types against the Kubernetes schemas (a misspelt field is often silently ignored bykubectl apply). - Policy checks: use
kube-linter, Kyverno or Conftest for team rules such as “every container has requests and a memory limit”, “nolatest”, “mustrunAsNonRoot”. - 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. - Diff:
kubectl diff -k deploy/k8s/overlays/prodlists 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
| Area | Check |
|---|---|
| Namespace | Pod Security labels (restricted in production), ResourceQuota, LimitRange |
| Identity | Each service has its own ServiceAccount, automountServiceAccountToken: false, RBAC grants only what’s needed |
| Image | Immutable tags (git SHA), never latest |
| Resources | Every container has requests and a memory limit; GOMEMLIMIT follows the limit |
| Probes | Startup, readiness and liveness all present; liveness doesn’t check dependencies |
| Security | Non-root, read-only root filesystem, capabilities dropped, seccomp |
| Shutdown | preStop, enough terminationGracePeriodSeconds, the program handles SIGTERM |
| Configuration | ConfigMaps generated (hashed names); Secrets not in git, readable only by those who need them |
| Availability | HPA on requests, PDB with maxUnavailable, PriorityClass for core services, Pods spread across nodes |
| Network | NetworkPolicy denies by default and opens only the paths needed; the only way in is the Gateway |
| Jobs | Jobs/CronJobs have timeouts, retry limits and automatic cleanup; they’re safe to re-run |
| Validation | CI 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 (
restrictedin 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,auditandwarnnamespace 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):
defaultanddefaultRequestfilling in container defaults, used for the LimitRange in step 2. - Configure Service Accounts for Pods (official Kubernetes documentation):
automountServiceAccountToken: falseto stop the token being mounted, used in step 3. - Role Based Access Control Good Practices (official Kubernetes documentation): least privilege, avoiding wildcards and
liston 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,concurrencyPolicyand history limits, used for the reconciliation job in step 6. - Go 1.25 Release Notes (official Go documentation): the container-aware
GOMAXPROCSdefault 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.