TExcelTAD

The Production Chart

Helm & Kustomize built a linkly chart with a Deployment, Service, ConfigMap, HTTPRoute and HPA. Now that you know the code, the chart can encode what the code needs to run well, and what the platform needs to operate it:

Addition Because linkly… Template
preStop sleep + terminationGracePeriodSeconds drains on SIGTERM, but endpoints are removed asynchronously deployment.yaml
SHUTDOWN_GRACE derived from the grace period must finish before the kubelet's SIGKILL configmap.yaml
readiness on /readyz, liveness on /healthz separates "can't serve" from "stuck" deployment.yaml
image.digest should run exactly the scanned bytes _helpers.tpl
database.secretKey reads url from External Secrets, uri from CloudNativePG deployment.yaml
PodDisruptionBudget runs several replicas that node drains shouldn't take down together pdb.yaml
NetworkPolicy should only be reachable from the Gateway and Prometheus networkpolicy.yaml
ServiceMonitor exposes /metrics for the Prometheus Operator servicemonitor.yaml
spread across nodes, maxUnavailable: 0 rollouts keeps capacity during rollouts and node failures deployment.yaml

The chart

The session writes the chart, lints it, renders three variants and validates each with kubeconform against the Kubernetes 1.34 schemas plus the Gateway API and Prometheus Operator CRDs. Then it scans the rendered manifests with Trivy's Kubernetes checks:

bash · try it yourself
mkdir -p chart/linkly/templates && cd chart/linkly
cat > Chart.yaml <<'YAML'
apiVersion: v2
name: linkly
description: linkly, a link shortener (Go, PostgreSQL, Redis)
type: application
version: 0.0.0-dev
appVersion: "0.0.0-dev"
kubeVersion: ">= 1.30.0-0"
YAML
cat > values.yaml <<'YAML'
replicaCount: 2
image:
  repository: ghcr.io/acme/linkly
  tag: ""          # defaults to appVersion
  digest: ""       # sha256:...; wins over the tag when set
config:
  logLevel: info
  baseUrl: https://lnk.example.com
  redisAddr: linkly-redis:6379
  cacheTTL: 1h
database:
  existingSecret: linkly-db   # created outside the chart (CloudNativePG, External Secrets)
  secretKey: url
service:
  port: 80
httpRoute:
  enabled: true
  parentRefs: [{name: public, namespace: gateway-system}]
  hostnames: [lnk.example.com]
autoscaling:
  enabled: false
  minReplicas: 2
  maxReplicas: 10
  targetCPUUtilizationPercentage: 70
podDisruptionBudget:
  enabled: true
  maxUnavailable: 1
serviceMonitor:
  enabled: false
  interval: 30s
networkPolicy:
  enabled: true
  ingressNamespaces: [gateway-system, monitoring]
terminationGracePeriodSeconds: 30
preStopSleepSeconds: 5
resources:
  requests: {cpu: 100m, memory: 64Mi}
  limits: {memory: 128Mi}
YAML
cat > templates/_helpers.tpl <<'YAML'
{{- define "linkly.fullname" -}}
{{- if contains .Chart.Name .Release.Name }}{{ .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}{{ printf "%s-%s" .Release.Name .Chart.Name | trunc 63 | trimSuffix "-" }}{{ end }}
{{- end }}
{{- define "linkly.selectorLabels" -}}
app.kubernetes.io/name: {{ .Chart.Name }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{- define "linkly.labels" -}}
{{ include "linkly.selectorLabels" . }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" }}
{{- end }}
{{- define "linkly.image" -}}
{{- if .Values.image.digest }}{{ .Values.image.repository }}@{{ .Values.image.digest }}
{{- else }}{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}{{ end }}
{{- end }}
YAML
cat > templates/configmap.yaml <<'YAML'
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
data:
  LISTEN_ADDR: ":8080"
  LOG_LEVEL: {{ .Values.config.logLevel | quote }}
  BASE_URL: {{ .Values.config.baseUrl | quote }}
  REDIS_ADDR: {{ .Values.config.redisAddr | quote }}
  CACHE_TTL: {{ .Values.config.cacheTTL | quote }}
  SHUTDOWN_GRACE: "{{ sub (sub .Values.terminationGracePeriodSeconds .Values.preStopSleepSeconds) 5 }}s"
YAML
cat > templates/deployment.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  {{- if not .Values.autoscaling.enabled }}
  replicas: {{ .Values.replicaCount }}
  {{- end }}
  revisionHistoryLimit: 5
  strategy: {rollingUpdate: {maxSurge: 25%, maxUnavailable: 0}}
  selector:
    matchLabels: {{- include "linkly.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      labels: {{- include "linkly.selectorLabels" . | nindent 8 }}
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum | trunc 16 }}
    spec:
      automountServiceAccountToken: false
      terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
      securityContext: {runAsNonRoot: true, runAsUser: 65532, runAsGroup: 65532, seccompProfile: {type: RuntimeDefault}}
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: ScheduleAnyway
          labelSelector:
            matchLabels: {{- include "linkly.selectorLabels" . | nindent 14 }}
      containers:
        - name: linkly
          image: {{ include "linkly.image" . | quote }}
          ports: [{name: http, containerPort: 8080}]
          envFrom: [{configMapRef: {name: {{ include "linkly.fullname" . }}}}]
          env:
            - name: DATABASE_URL
              valueFrom: {secretKeyRef: {name: {{ .Values.database.existingSecret }}, key: {{ .Values.database.secretKey }}}}
          readinessProbe: {httpGet: {path: /readyz, port: http}, periodSeconds: 5, failureThreshold: 2}
          livenessProbe: {httpGet: {path: /healthz, port: http}, periodSeconds: 10, failureThreshold: 3}
          lifecycle:
            preStop: {sleep: {seconds: {{ .Values.preStopSleepSeconds }}}}
          resources: {{- toYaml .Values.resources | nindent 12 }}
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: {drop: [ALL]}
YAML
cat > templates/service.yaml <<'YAML'
apiVersion: v1
kind: Service
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  selector: {{- include "linkly.selectorLabels" . | nindent 4 }}
  ports: [{name: http, port: {{ .Values.service.port }}, targetPort: http}]
YAML
cat > templates/httproute.yaml <<'YAML'
{{- if .Values.httpRoute.enabled }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  parentRefs: {{- toYaml .Values.httpRoute.parentRefs | nindent 4 }}
  hostnames: {{- toYaml .Values.httpRoute.hostnames | nindent 4 }}
  rules:
    - matches: [{path: {type: PathPrefix, value: /}}]
      backendRefs: [{name: {{ include "linkly.fullname" . }}, port: {{ .Values.service.port }}}]
{{- end }}
YAML
cat > templates/hpa.yaml <<'YAML'
{{- if .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: {{ include "linkly.fullname" . }}}
  minReplicas: {{ .Values.autoscaling.minReplicas }}
  maxReplicas: {{ .Values.autoscaling.maxReplicas }}
  metrics:
    - type: Resource
      resource: {name: cpu, target: {type: Utilization, averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}}}
{{- end }}
YAML
cat > templates/pdb.yaml <<'YAML'
{{- if .Values.podDisruptionBudget.enabled }}
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  maxUnavailable: {{ .Values.podDisruptionBudget.maxUnavailable }}
  selector:
    matchLabels: {{- include "linkly.selectorLabels" . | nindent 6 }}
{{- end }}
YAML
cat > templates/networkpolicy.yaml <<'YAML'
{{- if .Values.networkPolicy.enabled }}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  podSelector:
    matchLabels: {{- include "linkly.selectorLabels" . | nindent 6 }}
  policyTypes: [Ingress]
  ingress:
    - from:
        {{- range .Values.networkPolicy.ingressNamespaces }}
        - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: {{ . }}}}
        {{- end }}
      ports: [{port: http}]
{{- end }}
YAML
cat > templates/servicemonitor.yaml <<'YAML'
{{- if .Values.serviceMonitor.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: {{ include "linkly.fullname" . }}
  labels: {{- include "linkly.labels" . | nindent 4 }}
spec:
  selector:
    matchLabels: {{- include "linkly.selectorLabels" . | nindent 6 }}
  endpoints:
    - port: http
      path: /metrics
      interval: {{ .Values.serviceMonitor.interval }}
{{- end }}
YAML
cd ../..
helm lint chart/linkly --strict --quiet && echo "lint: ok"
echo "== defaults"
helm template linkly chart/linkly -n linkly-production > default.yaml
yq -N '.kind + "/" + .metadata.name' default.yaml | paste -sd' '
kubeconform -strict -summary default.yaml
echo "== production: autoscaling, ServiceMonitor, image by digest, CloudNativePG secret"
helm template linkly chart/linkly -n linkly-production --set autoscaling.enabled=true \
  --set serviceMonitor.enabled=true --set database.existingSecret=linkly-db-app --set database.secretKey=uri \
  --set image.digest=sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945 > production.yaml
yq -N '.kind + "/" + .metadata.name' production.yaml | paste -sd' '
kubeconform -strict -summary production.yaml
yq -o json -I0 'select(.kind == "Deployment") | .spec.template.spec.containers[0] | (.image, .env[0].valueFrom.secretKeyRef)' production.yaml
echo "== shutdown settings"
yq 'select(.kind == "Deployment") | .spec.template.spec | {"grace": .terminationGracePeriodSeconds, "preStop": .containers[0].lifecycle.preStop}' -o json -I0 default.yaml
yq 'select(.kind == "ConfigMap") | .data.SHUTDOWN_GRACE' default.yaml
echo "== trivy config on the rendered manifests"
trivy config -q -f json default.yaml | jq -r '.Results[] | "checks passed: \(.MisconfSummary.Successes), failed: \(.MisconfSummary.Failures)", (.Misconfigurations[]? | "  \(.Severity) \(.ID) \(.Title)")'
lint: ok
== defaults
NetworkPolicy/linkly PodDisruptionBudget/linkly ConfigMap/linkly Service/linkly Deployment/linkly HTTPRoute/linkly
Summary: 6 resources found in 1 file - Valid: 6, Invalid: 0, Errors: 0, Skipped: 0
== production: autoscaling, ServiceMonitor, image by digest, CloudNativePG secret
NetworkPolicy/linkly PodDisruptionBudget/linkly ConfigMap/linkly Service/linkly Deployment/linkly HorizontalPodAutoscaler/linkly HTTPRoute/linkly ServiceMonitor/linkly
Summary: 8 resources found in 1 file - Valid: 8, Invalid: 0, Errors: 0, Skipped: 0
"ghcr.io/acme/linkly@sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945"
{"name":"linkly-db-app","key":"uri"}
== shutdown settings
{"grace":30,"preStop":{"sleep":{"seconds":5}}}
20s
== trivy config on the rendered manifests
checks passed: 101, failed: 3
  LOW KSV-0011 CPU not limited
  LOW KSV-0110 Workloads in the default namespace
  MEDIUM KSV-0125 Restrict container images to trusted registries

Walkthrough

Graceful shutdown is a contract between three settings. When a pod is deleted, Kubernetes does two things at once: it removes the pod from the Service's endpoints (which takes a moment to reach every node and the Gateway), and it runs the preStop hook, then sends SIGTERM. Without a pause, linkly could stop accepting connections while the Gateway still sends it traffic. So:

text
t=0   pod deleted ──► endpoints removal starts propagating
      preStop: sleep 5s           (traffic drains away; linkly keeps serving)
t=5   SIGTERM ──► linkly: draining, srv.Shutdown(SHUTDOWN_GRACE = 20s)
t≤25  linkly exits 0
t=30  terminationGracePeriodSeconds: SIGKILL if still running

The chart computes SHUTDOWN_GRACE as grace period − preStop − 5 s of margin (20s with the defaults), so the app always finishes before the kubelet kills it. The hook uses the built-in sleep action (lifecycle.preStop.sleep), not exec: ["sleep", "5"]: distroless has no sleep binary, and an exec hook would fail silently. kubeconform accepted the field because it is in the Kubernetes 1.34 schema; on an older cluster it isn't available (the Field Notes have the fallback). Production Hardening models this timeline in code.

Probes. Readiness checks /readyz every 5 s and takes the pod out of rotation after two failures (database down, or draining). Liveness checks only /healthz, which depends on nothing: a liveness probe that checked the database would restart every pod during a database outage, making recovery slower.

maxUnavailable: 0 with maxSurge: 25% means a rollout adds new pods first and removes old ones only when new ones are ready; combined with readinessProbe, a broken image never reduces capacity. The PodDisruptionBudget does the same for voluntary disruptions (node drains, cluster upgrades): at most one pod is evicted at a time.

Image by digest. With image.digest set, the image reference becomes repository@sha256:… and the tag is ignored. The CI workflow writes both into the deploy repository; the digest is what runs, the tag is for humans.

The database Secret key is configurable because the two tracks produce different Secrets: CloudNativePG creates <cluster>-app with a uri key, the External Secrets template from the cloud lesson creates linkly-db with url.

NetworkPolicy allows ingress on the http port only from the namespaces listed in networkPolicy.ingressNamespaces (the Gateway's and Prometheus's), matched by the kubernetes.io/metadata.name label every namespace gets automatically. It only takes effect if the cluster's network plugin enforces policies: kind's default CNI (kindnet) supports NetworkPolicy in recent kind releases; on EKS, enable network policy support in the VPC CNI.

The ServiceMonitor is off by default because its CRD only exists where the Prometheus Operator is installed; a chart that renders it unconditionally fails to install on a bare cluster.

What Trivy flagged. Over a hundred Kubernetes checks pass (non-root, read-only root filesystem, no privilege escalation, dropped capabilities, seccomp, probes, memory limits, …). The three findings are worth reading one by one, because none of them is fixed by blindly following the advice:

  • KSV-0011 CPU not limited. Deliberate: linkly sets a CPU request but no CPU limit. CPU limits throttle a latency-sensitive Go service in short bursts even when the node is idle, while the memory limit is what protects the node from a leak. Record the exception with its reason, like the Dockerfile's HEALTHCHECK.
  • KSV-0110 default namespace. The rendered manifests carry no metadata.namespace, because Helm (-n) and Argo CD (the Application's destination.namespace) set it at apply time. Trivy sees an unqualified object and assumes default. Either ignore it for rendered charts or add namespace: {{ .Release.Namespace }} to every template, which some teams prefer so that helm template | kubectl apply is safe too.
  • KSV-0125 trusted registries. Trivy's default list of trusted registries is short. Which registries your clusters may pull from is a platform policy (enforced at admission by Kyverno or Gatekeeper), not something the chart can fix.

Values for the two environments

yaml
# linkly-deploy/apps/linkly/staging/values.yaml
replicaCount: 1
image:
  tag: v1.5.0-rc.1
config: {logLevel: debug, baseUrl: "https://lnk.staging.example.com", redisAddr: "linkly-redis:6379"}
database: {existingSecret: linkly-db-app, secretKey: uri}          # CloudNativePG
httpRoute: {hostnames: [lnk.staging.example.com]}
podDisruptionBudget: {enabled: false}                                # a PDB with 1 replica blocks node drains
serviceMonitor: {enabled: true}
yaml
# linkly-deploy/apps/linkly/production/values.yaml
image:
  tag: v1.4.0
  digest: sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945
config: {logLevel: info, baseUrl: "https://lnk.example.com", redisAddr: "linkly-redis:6379"}
database: {existingSecret: linkly-db-app, secretKey: uri}
httpRoute: {hostnames: [lnk.example.com]}
autoscaling: {enabled: true, minReplicas: 3, maxReplicas: 12}
serviceMonitor: {enabled: true}
resources:
  requests: {cpu: 250m, memory: 96Mi}
  limits: {memory: 192Mi}

Note the PDB is disabled in staging: with one replica and maxUnavailable: 1 it would be harmless, but with minAvailable: 1 it would block every node drain, a common way to stall a cluster upgrade.

Test yourself

Why does the chart use lifecycle.preStop.sleep instead of exec: ["sleep", "5"]?

  1. exec hooks are deprecated
  2. The distroless image has no sleep binary, so the exec hook would fail
  3. sleep actions are faster
  4. exec hooks can't run before SIGTERM

With terminationGracePeriodSeconds: 30 and a 5-second preStop sleep, what does the chart set SHUTDOWN_GRACE to, and why?

  1. 30s, the full period
  2. 20s: grace minus preStop minus a 5-second margin, so linkly finishes before SIGKILL
  3. 5s
  4. 0s

Why doesn't the liveness probe check the database?

  1. It would be too slow
  2. During a database outage, every pod would be restarted, which doesn't fix the database and slows recovery
  3. Liveness probes can't call HTTP endpoints
  4. The database has its own probe