logo

Just A Dev

article cover image

What happens when you run kubectl apply command?

April 21, 2024

What happens when you run kubectl apply command?

Why should we care?

e0d9375e940d3c9900fa4dcdef0af8f0.jpg

Have you ever thought about what happened behind the scenes? I bet you did. As a kid, you surely asked your parents questions like: "Why do day and night occur?". Unfortunately, when we grow up, some of us forget how to ask questions.

Those kinds of questions are actually important as they help us to understand the fundamentals. You're not going to use this knowledge every day. But when the time comes, it's really useful.

Well, long story short, this particular piece of knowledge will help you debug and optimize your K8S applications. And also really helpful when someone ask you in an interview session :)))

So what's happening?

Assuming you have this deployment.yaml file and want to deploy it to K8S cluster

apiVersion: apps/v1 kind: Deployment metadata: name: busybox-deployment spec: replicas: 2 selector: matchLabels: app: busybox template: metadata: labels: app: busybox spec: containers: - name: busybox image: busybox command: ["/bin/sh", "-c", "while true; do echo Hello from BusyBox; sleep 10; done"]

Firstly, when you call this command, that means you're interacting with the K8S API server.

Let's say you're having 2 nodes in your K8S cluster, then those 2 nodes are pulling data from API server as well.

kubectl apply -f deployment.yaml

k8s.step1.png

Then, guess what? The API server will save those objects in etcd, a internal persisten storage that being used by K8S.

k8s.step2.png

Sounds like a normal API server right? Normally, in Backend development, after we save objects in DB, then we'll need a background job to process these data right? Same here. What's when kube-controller-manager comes into the picture. It will:

  1. Fetch objects from API server
  2. Process them
  3. Then update objects back

k8s.step3.png

At this phase, the rest is really to guess. The kube-scheduler will:

  1. Fetch pods
  2. Process them
  3. Then update pods back
  4. Create a Binding object to put your pods in suitable nodes

k8s.step4.png

Then kubelet in side your Nodes will read from API server, then says: "Ok master, let me put your pods in my node".

Sounds simple right? But again, it's really important to know this, rather than just run your commands and know nothing about it. Hope you had fun reading this.

jon-snow.gif