Kubernetes foundations: the cluster and kubectl · 6 MIN READ

Declarative configuration with kubectl apply, manifest directories and kustomize

Manage objects from version-controlled manifests with kubectl apply, interpret created, configured and unchanged, apply and delete whole directories, and produce per-environment variants with kustomize.

Imperative commands such as kubectl create and kubectl scale are quick, but they leave no record of what the cluster should look like, and nobody can review or reproduce them. Declarative management keeps the desired state in files, in git, and lets kubectl apply work out what to change. This lesson shows how apply decides, how it corrects drift, and how kustomize produces variants of the same manifests without copying them.

kubernetes · A MAP OF THE IDEA

  1. Write manifests in git
  2. Review changes as pull requests
  3. apply -f DIR or apply -k DIR
  4. Read created and configured
  5. Fix drift in the file

Useful when

  • Git history becomes the audit log and the rollback mechanism.
  • Overlays keep differences between environments small and reviewable.

Watch out

  • Manual changes to applied fields are overwritten without a warning.
  • Deleting a file does not delete the objects it created.

Implementation & operation cost: A repository of manifests, a review process, and the discipline to change the cluster only through them.

01

Imperative commands and declarative files

kubectl supports three styles. Imperative commands, such as create deployment, expose, scale and set image, act directly and suit experiments and one-off fixes. Imperative object configuration, create -f and replace -f, uses files but still names the operation, so create fails when the object exists and replace overwrites the whole object. Declarative configuration, apply -f, only states what should exist: kubectl compares the file with the live object and sends the difference, creating the object when it is missing. Use apply for anything that should outlive the afternoon. Do not mix styles on the same fields: a kubectl scale or set image on an applied object lasts only until the next apply of the file, which is correct when git is the source of truth and a nasty surprise when someone fixed production by hand.

02

What apply does and what its output means

apply prints one line per object: created when it did not exist, configured when the request changed something, and unchanged when the live object already matched the file. Client-side apply, the default, stores the file it applied in the kubectl.kubernetes.io/last-applied-configuration annotation and computes a three-way patch from that annotation, the new file and the live object. Fields in the file are set. Fields that were in the last applied file but are gone from the new one are removed. Fields that neither mentions, such as status, server defaults or a label another tool added, are left alone. That is why deleting a line from a manifest removes the field on the next apply, and why applying to an object first made with kubectl create prints a warning about the missing annotation.

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  labels:
    app: web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: web
        image: nginx:1.27
        ports:
        - containerPort: 80
Read the code

The manifest lives in shop/deployment.yaml beside shop/service.yaml. The field to watch is replicas, which the exercise changes from 2 to 3. Because replicas is in the file, every apply sets it, overriding a manual kubectl scale; if a HorizontalPodAutoscaler is to own the count, remove replicas from the file so that apply stops fighting it.

03

Directories, deletion and git

-f accepts a directory and applies every .yaml, .yml and .json file in it in lexical order; add -R to descend into subdirectories. Order matters only for dependencies, such as a Namespace that must exist before the objects in it, which a file named 00-namespace.yaml takes care of. kubectl delete -f with the same directory deletes exactly the objects its files define, which makes cleanup precise. Keep these directories in git: a pull request is the review, history records who changed what and why, and a git revert followed by apply is a rollback. Deleting a file does not delete its object, because plain apply only knows the files you pass it, so delete the objects with delete -f before you remove the files. Never commit Secrets in plain text.

bash
kubectl apply -f shop/
kubectl apply -f shop/ --dry-run=server
kubectl delete -f shop/
Read the code

--dry-run=server sends the objects through validation and admission without storing anything, the closest check to a real apply. On a real cluster, kubectl diff -f shop/ goes further and prints the changes apply would make; diff is not available in the lab. delete -f removes exactly the Deployment and Service the two files define.

04

kustomize: one set of manifests, variants per environment

kustomize is built into kubectl as apply -k DIR, long form --kustomize DIR. The directory's kustomization.yaml lists resources, which are files or other kustomization directories, and transformations applied to all of them. namespace sets metadata.namespace everywhere; namePrefix and nameSuffix rename objects and update references to them; images replaces image names or tags without editing the Deployment; replicas overrides counts; labels adds labels, which go into selectors only when you ask for it. The usual layout is a base directory with plain manifests and an overlay per environment, such as overlays/staging, whose resources entry is ../../base. The lab follows ../ paths as well; the exercise keeps everything in one directory to stay short. A directory with a kustomization.yaml is meant for -k; pointing -f at it makes kubectl try to apply kustomization.yaml itself.

yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- deployment.yaml
- service.yaml
namespace: staging
namePrefix: staging-
images:
- name: nginx
  newTag: "1.26"
Read the code

Applied with kubectl apply --kustomize shop/, this creates a staging-web Deployment and Service in the staging namespace running nginx:1.26, while deployment.yaml and service.yaml stay untouched. The images entry matches the image name as the Deployment writes it, nginx, whatever its tag. The Service's selector stays app=web, which is fine because a Service only selects pods in its own namespace.

05

Field ownership and server-side apply

Client-side apply tracks ownership crudely, in one annotation that only kubectl reads. Server-side apply, kubectl apply --server-side, moves the merge into the API server: every field records its manager in metadata.managedFields, an apply that would change a field owned by another manager fails with a conflict unless you pass --force-conflicts, and controllers, people and GitOps tools can share one object without overwriting each other. Flux applies server-side by default and Argo CD offers it as a sync option. It is the better model for new automation, but conflicts surface differently, so switch deliberately and for a whole set of manifests at once. The GopherForge lab uses client-side semantics throughout: created, configured and unchanged, with the file you apply deciding what is set.

06

Try it in the lab terminal

Apply a directory of two manifests twice, change the file, cause drift by hand and apply again to see which side wins, then delete everything the directory defines. Next, turn the same directory into a staging variant with a kustomization.yaml and apply it with kustomize. The last command deliberately points -f at the directory that now contains kustomization.yaml, a mistake that is easy to make and only half fails.

bash
kind create cluster
mkdir shop
cat > shop/deployment.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  labels:
    app: web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: web
        image: nginx:1.27
        ports:
        - containerPort: 80
EOF
cat > shop/service.yaml <<'EOF'
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector:
    app: web
  ports:
  - port: 80
    targetPort: 80
EOF
kubectl apply -f shop/
kubectl apply -f shop/
sed -i 's/replicas: 2/replicas: 3/' shop/deployment.yaml
kubectl scale deployment web --replicas=5
kubectl apply -f shop/
kubectl get deployment web
kubectl delete -f shop/
cat > shop/kustomization.yaml <<'EOF'
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- deployment.yaml
- service.yaml
namespace: staging
namePrefix: staging-
images:
- name: nginx
  newTag: "1.26"
EOF
kubectl create namespace staging
kubectl apply --kustomize shop/
kubectl get deploy,svc -n staging -o wide
kubectl apply -f shop/
Read the code

The first apply prints deployment.apps/web created and service/web created, the second unchanged for both. With replicas: 3 in the file and 5 set by hand, the next apply prints deployment.apps/web configured and service/web unchanged, and get deployment shows READY 1/3 while pods start: the file wins. delete -f removes both objects. apply --kustomize creates staging-web objects in staging, and -o wide shows nginx:1.26 although deployment.yaml still says 1.27. The final apply -f first creates the unprefixed web objects in default, then fails with error: resource mapping not found ... no matches for kind "Kustomization", which leaves you with an extra copy to delete.

TAKE THIS WITH YOU

Keep desired state in files under git and let kubectl apply compute the changes; created, configured and unchanged tell you what happened. Use kustomize for per-environment differences instead of copies, and remember that the file overrides manual changes on the next apply.

Check your understanding

During an incident someone ran kubectl scale deployment web --replicas=10. The manifest in git says replicas: 3. What happens on the next kubectl apply -f of that manifest?

Go to the source

Progress stays in this browser. No account needed.