Creating a TLS Secret in Kubernetes
Luke Hebert
- 2 minutes read - 339 wordsSetting up a webhook server in Kubernetes requires two things: a TLS secret built from your certificate and key, and a deployment that mounts that secret so the container can serve HTTPS. The steps below cover both, including a dry-run option if you want to review the manifest before applying it.
1. Create the TLS Secret
Option A - Generate the YAML first (dry-run), then apply
# Preview the secret manifest without creating it
kubectl create secret tls webhook-server-tls \
--cert=webhook-server-tls.crt \
--key=webhook-server-tls.key \
--dry-run=client -o yaml > tls-secret.yaml
# Review the file, then apply it
kubectl apply -f tls-secret.yamlOption B - Create it directly
kubectl create secret tls webhook-server-tls \
--cert=webhook-server-tls.crt \
--key=webhook-server-tls.key
Note
--dry-run=client tells kubectl to build the object locally and print it without contacting the API server. The > redirect writes that output to a file.
2. Deployment Manifest
apiVersion: apps/v1
kind: Deployment
metadata:
name: webhook-server
namespace: webhook-demo
labels:
app: webhook-server
spec:
replicas: 1
selector:
matchLabels:
app: webhook-server
template:
metadata:
labels:
app: webhook-server
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1234
containers:
- name: server
image: stackrox/admission-controller-webhook-demo:latest
imagePullPolicy: Always
ports:
- containerPort: 8443
name: webhook-api
volumeMounts:
- name: webhook-tls-certs
mountPath: /run/secrets/tls
readOnly: true
volumes:
- name: webhook-tls-certs
secret:
secretName: webhook-server-tlsBreakdown of Key Components
| Element | Purpose |
|---|---|
namespace: webhook-demo | Isolates the deployment in its own namespace. |
runAsNonRoot: true / runAsUser: 1234 | Security hardening; the container runs as an unprivileged user. |
imagePullPolicy: Always | Re-pulls the image on every pod start (useful for :latest tags). |
containerPort: 8443 | The HTTPS port the webhook listens on. |
volumeMounts → /run/secrets/tls | Mounts the TLS cert and key into the container at the conventional path. |
volumes → secretName: webhook-server-tls | References the secret created in Step 1. |
readOnly: true | Prevents the container from writing to the mounted secret. |
Prerequisites Checklist
-
webhook-server-tls.crtandwebhook-server-tls.keyexist in the working directory. - The
webhook-demonamespace exists (kubectl create namespace webhook-demo). - The image
stackrox/admission-controller-webhook-demo:latestis pullable from the cluster’s registry. - A
MutatingWebhookConfigurationorValidatingWebhookConfigurationis defined separately to point at this service (not included in this snippet).