🐳

Kubernetes

10 notes  •  Containers & Orchestration

kubectl Quick Reference

Common kubectl commands for managing Kubernetes clusters, namespaces, pods, services, and deployments.

Cluster Info

kubectl version
kubectl cluster-info
kubectl config view
kubectl config current-context
kubectl config use-context <context-name>

Namespaces

kubectl get namespaces
kubectl create namespace <name>
kubectl delete namespace <name>

Pods

kubectl get pods
kubectl get pods --all-namespaces
kubectl get pods -n <namespace>
kubectl describe pod <pod-name> -n <namespace>
kubectl logs <pod-name> -n <namespace>
kubectl exec -it <pod-name> -- bash
kubectl delete pod <pod-name>

Deployments

kubectl get deployments
kubectl get deployment <name> -n <namespace>
kubectl describe deployment <name>
kubectl scale deployment <name> --replicas=3
kubectl rollout status deployment/<name>
kubectl rollout undo deployment/<name>

Services

kubectl get services --all-namespaces
kubectl describe service <name> -n <namespace>
kubectl expose deployment <name> --port=80 --type=LoadBalancer

Apply / Delete Resources

kubectl apply -f manifest.yaml
kubectl delete -f manifest.yaml
kubectl delete pod <pod-name> --grace-period=0 --force

Nodes

kubectl get nodes
kubectl describe node <node-name>
kubectl cordon <node-name>
kubectl drain <node-name> --ignore-daemonsets
kubectl uncordon <node-name>

Add Worker Nodes to a Kubernetes Cluster

How to add new worker nodes to an existing Kubernetes cluster. The cluster must have been initialized with kubeadm.

Prerequisites

  • Kubernetes cluster initialized with kubeadm
  • Worker node with the same OS and Docker/containerd version
  • Network connectivity between master and worker nodes

Step 1 — Get a Join Token on the Master

Tokens expire after 24 hours. Generate a new one if needed:

# On the master node
kubeadm token create --print-join-command

This outputs a full kubeadm join command with the token and CA hash.

Step 2 — Prepare the Worker Node

On the new worker node, ensure the same Kubernetes packages are installed:

sudo apt-get update
sudo apt-get install -y kubelet kubeadm kubectl
sudo systemctl enable kubelet

Step 3 — Join the Cluster

Run the join command from Step 1 on the worker node:

sudo kubeadm join <MASTER_IP>:6443 --token <TOKEN> \
    --discovery-token-ca-cert-hash sha256:<HASH>

Step 4 — Verify on the Master

kubectl get nodes

The new node should appear with status Ready within a few minutes.

Troubleshooting

  • If the token expired, regenerate it: kubeadm token create --print-join-command
  • If the node shows NotReady, check that a CNI plugin (Flannel, Calico, etc.) is deployed on the cluster.
  • Check worker kubelet status: sudo systemctl status kubelet

kops Command Reference (AWS Kubernetes Clusters)

kops (Kubernetes Operations) provisions and manages Kubernetes clusters on AWS. This guide covers the essential commands.

Prerequisites

  • kops and kubectl installed
  • AWS CLI configured with appropriate IAM permissions
  • An S3 bucket for kops state storage

Create a Cluster

export KOPS_STATE_STORE=s3://kops-storage-k8s

kops create cluster \
  --yes \
  --state=$KOPS_STATE_STORE \
  --zones=ap-south-1a,ap-southeast-1b \
  --node-count=2 \
  --node-size=t3.medium \
  --master-size=t3.medium \
  --name=mycluster.k8s.local

Validate Cluster

kops validate cluster --state=$KOPS_STATE_STORE

Export kubeconfig

kops export kubecfg --admin --state=$KOPS_STATE_STORE --name=mycluster.k8s.local
kubectl config current-context

Manage the Cluster

# List clusters
kops get clusters --state=$KOPS_STATE_STORE

# Edit cluster configuration
kops edit cluster mycluster.k8s.local --state=$KOPS_STATE_STORE

# Apply changes
kops update cluster mycluster.k8s.local --yes --state=$KOPS_STATE_STORE

# Rolling update (after config changes)
kops rolling-update cluster --yes --state=$KOPS_STATE_STORE

Scale Node Groups

kops get ig --state=$KOPS_STATE_STORE
kops edit ig nodes --state=$KOPS_STATE_STORE
# Change minSize / maxSize, then:
kops update cluster --yes --state=$KOPS_STATE_STORE

Delete Cluster

kops delete cluster mycluster.k8s.local --yes --state=$KOPS_STATE_STORE

Set Up Kubernetes with kubeadm

How to initialize a Kubernetes cluster on Ubuntu using kubeadm, covering both the master and worker node setup.

Prerequisites

  • Ubuntu 20.04 or 22.04 on all nodes
  • At least 2 CPUs and 2 GB RAM per node
  • Swap disabled: sudo swapoff -a
  • Unique hostname, MAC, and product_uuid per node

Step 1 — Install Container Runtime (all nodes)

sudo apt-get update
sudo apt-get install -y containerd
sudo mkdir -p /etc/containerd
containerd config default | sudo tee /etc/containerd/config.toml
sudo systemctl restart containerd
sudo systemctl enable containerd

Step 2 — Install kubeadm, kubelet, kubectl (all nodes)

sudo apt-get install -y apt-transport-https ca-certificates curl
sudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg \
  https://packages.cloud.google.com/apt/doc/apt-key.gpg

echo "deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] \
  https://apt.kubernetes.io/ kubernetes-xenial main" | \
  sudo tee /etc/apt/sources.list.d/kubernetes.list

sudo apt-get update
sudo apt-get install -y kubelet kubeadm kubectl
sudo apt-mark hold kubelet kubeadm kubectl

Step 3 — Initialize the Master Node

# If re-initializing, reset first:
sudo kubeadm reset

sudo kubeadm init --pod-network-cidr=10.244.0.0/16

# Configure kubectl for your user
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

Step 4 — Install a Pod Network (Master)

# Flannel
kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

Step 5 — Join Worker Nodes

# Get the join command from master output, or regenerate:
kubeadm token create --print-join-command

# Run on each worker node:
sudo kubeadm join <MASTER_IP>:6443 --token <TOKEN> --discovery-token-ca-cert-hash sha256:<HASH>

Verify

kubectl get nodes
kubectl get pods --all-namespaces

Install Kubernetes on Ubuntu Server

Step-by-step guide to installing Kubernetes on Ubuntu 20.04 or 22.04 using the official Kubernetes APT repository.

Prerequisites

  • Ubuntu 20.04 / 22.04
  • Root or sudo access
  • Swap disabled

Step 1 — Disable Swap

sudo swapoff -a
sudo sed -i '/ swap / s/^/#/' /etc/fstab

Step 2 — Install Dependencies

sudo apt-get update
sudo apt-get install -y apt-transport-https ca-certificates curl software-properties-common

Step 3 — Add Kubernetes Repository

sudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg \
  https://packages.cloud.google.com/apt/doc/apt-key.gpg

echo "deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] \
  https://apt.kubernetes.io/ kubernetes-xenial main" | \
  sudo tee /etc/apt/sources.list.d/kubernetes.list

sudo apt-get update

Step 4 — Install Kubernetes Components

sudo apt-get install -y kubelet kubeadm kubectl
sudo apt-mark hold kubelet kubeadm kubectl

Step 5 — Initialize the Cluster (Master Only)

sudo kubeadm init --pod-network-cidr=10.244.0.0/16

mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

Step 6 — Deploy Pod Network

kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

Verify

kubectl get nodes
kubectl get pods -n kube-system

eksctl Command Reference (Amazon EKS)

eksctl is the official CLI for creating and managing Amazon EKS clusters. This guide covers common commands for cluster and nodegroup management.

Prerequisites

  • eksctl installed (brew install eksctl or from GitHub releases)
  • AWS CLI configured with credentials
  • kubectl installed

Set AWS Profile

export AWS_DEFAULT_PROFILE=eks-course
# Or specify per-command: eksctl ... --profile eks-course

Create a Cluster

# Minimal cluster (no nodegroup — add separately)
eksctl create cluster \
  --name=eksdemo \
  --region=us-east-1 \
  --zones=us-east-1a,us-east-1b \
  --without-nodegroup

# Create a managed nodegroup
eksctl create nodegroup \
  --cluster=eksdemo \
  --region=us-east-1 \
  --name=ng-public \
  --node-type=t3.medium \
  --nodes=2 \
  --nodes-min=1 \
  --nodes-max=4 \
  --managed

IAM OIDC Provider and Service Accounts

# Associate IAM OIDC provider
eksctl utils associate-iam-oidc-provider \
  --region=us-east-1 \
  --cluster=eksdemo \
  --approve

# Create IAM service account
eksctl create iamserviceaccount \
  --cluster=eksdemo \
  --name=aws-load-balancer-controller \
  --namespace=kube-system \
  --attach-policy-arn=arn:aws:iam::<ACCOUNT_ID>:policy/AWSLoadBalancerControllerIAMPolicy \
  --approve

Cluster Info and kubeconfig

eksctl get cluster --region=us-east-1
eksctl utils write-kubeconfig --cluster=eksdemo --region=us-east-1
kubectl config current-context

Delete Cluster

eksctl delete cluster --name=eksdemo --region=us-east-1

kubectl Command Syntax and Examples

Full syntax reference for kubectl with practical examples for daily Kubernetes operations.

Command Syntax

kubectl [command] [type] [name] [flags]
  • command: create, get, describe, delete, apply, exec, logs, scale, rollout
  • type: pods (po), namespaces (ns), deployments (deploy), replicasets (rs), services (svc), nodes, configmaps (cm), secrets
  • flags: -n <namespace>, -o yaml, -o wide, --all-namespaces

Get Resources

kubectl get pods -n production
kubectl get pods -o wide
kubectl get all --all-namespaces
kubectl get events --sort-by=.metadata.creationTimestamp

Describe and Debug

kubectl describe pod <name> -n <ns>
kubectl logs <pod> -c <container> --tail=100
kubectl logs <pod> --previous
kubectl exec -it <pod> -- /bin/sh
kubectl port-forward svc/<service> 8080:80

Create and Apply

kubectl apply -f deployment.yaml
kubectl create deployment myapp --image=nginx --replicas=2
kubectl create configmap myconfig --from-file=config.properties
kubectl create secret generic mysecret --from-literal=password=s3cr3t

Update and Scale

kubectl scale deployment myapp --replicas=5
kubectl set image deployment/myapp container=nginx:1.25
kubectl rollout status deployment/myapp
kubectl rollout history deployment/myapp
kubectl rollout undo deployment/myapp

Delete Resources

kubectl delete pod <name>
kubectl delete -f manifest.yaml
kubectl delete deployment myapp

Create a ClusterIP Service in Kubernetes

A ClusterIP service exposes a set of pods on a stable internal IP address accessible only within the cluster. This guide shows how to create one.

Prerequisites

  • A running Kubernetes cluster
  • kubectl configured
  • A deployment to expose

Step 1 — Create a Deployment

kubectl create deployment my-app --image=nginx --replicas=2

Step 2 — Expose as ClusterIP Service

Using kubectl expose:

kubectl expose deployment my-app --port=80 --target-port=80 --type=ClusterIP --name=my-app-svc

Or using a YAML manifest:

cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Service
metadata:
  name: my-app-svc
spec:
  selector:
    app: my-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: ClusterIP
EOF

Step 3 — Verify the Service

kubectl get svc my-app-svc
kubectl describe svc my-app-svc

Step 4 — Test Connectivity from Inside the Cluster

# Run a temporary pod to test
kubectl run test-pod --image=busybox --rm -it -- wget -O- my-app-svc

Notes

  • ClusterIP is the default service type — internal only.
  • Use NodePort to expose externally on each node's IP.
  • Use LoadBalancer for cloud-managed external load balancers.

Deploy an Amazon EKS Cluster with Terraform

How to provision a production-ready Amazon EKS cluster using Terraform, including VPC, node groups, and kubeconfig configuration.

Prerequisites

  • Terraform ≥ 1.0 installed
  • AWS CLI configured with admin credentials
  • kubectl and aws-iam-authenticator installed

Step 1 — Create the Terraform Configuration

# main.tf
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"
  name    = "eks-vpc"
  cidr    = "10.0.0.0/16"
  azs             = ["us-east-1a", "us-east-1b"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24"]
  enable_nat_gateway = true
  single_nat_gateway = true
}

module "eks" {
  source          = "terraform-aws-modules/eks/aws"
  version         = "~> 20.0"
  cluster_name    = "production-eks"
  cluster_version = "1.29"
  vpc_id          = module.vpc.vpc_id
  subnet_ids      = module.vpc.private_subnets

  eks_managed_node_groups = {
    default = {
      min_size     = 2
      max_size     = 5
      desired_size = 2
      instance_types = ["t3.medium"]
    }
  }
}

Step 2 — Initialize and Apply

terraform init
terraform plan
terraform apply

Step 3 — Configure kubectl

aws eks --region us-east-1 update-kubeconfig --name production-eks
kubectl get nodes

Step 4 — Verify Cluster

kubectl get pods --all-namespaces
kubectl get svc

Notes

  • Always use private subnets for worker nodes in production.
  • Enable cluster logging (API, audit, authenticator) via cluster_enabled_log_types.
  • Manage add-ons (CoreDNS, kube-proxy, VPC CNI) via Terraform's cluster_addons block.

Connect kubectl to a Manually Created EKS Cluster

If your EKS cluster was created manually via the AWS Console or CLI (not eksctl), you need to update your local kubeconfig to connect to it.

Step 1 — Update kubeconfig

aws eks --region <region> update-kubeconfig --name <cluster-name>

# Example:
aws eks --region us-east-1 update-kubeconfig --name test-eks-cluster

This adds a new context to ~/.kube/config.

Step 2 — Set the Context

kubectl config get-contexts
kubectl config use-context arn:aws:eks:us-east-1:<account-id>:cluster/test-eks-cluster

Step 3 — Verify Connectivity

kubectl get nodes
kubectl get pods --all-namespaces

Step 4 — Manage Node Groups

# Add a managed node group
aws eks create-nodegroup \
  --cluster-name test-eks-cluster \
  --nodegroup-name ng-workers \
  --node-role arn:aws:iam::<account-id>:role/EKSNodeRole \
  --subnets subnet-xxxx subnet-yyyy \
  --scaling-config minSize=2,maxSize=5,desiredSize=2 \
  --instance-types t3.medium

# List node groups
aws eks list-nodegroups --cluster-name test-eks-cluster

Troubleshooting

  • If kubectl returns Unauthorized: ensure your IAM user/role is in the cluster's aws-auth ConfigMap.
  • Check IAM permissions: you need eks:DescribeCluster at minimum.
  • Use --profile flag if using a non-default AWS profile: aws eks update-kubeconfig --profile myprofile ...