sudo apt-mark unhold kubeadm && \
sudo apt-get update && sudo apt-get install -y kubeadm='1.29.4-2.1' && \
sudo apt-mark hold kubeadm
rm -rf $HOME/.kube || true
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
Run the above commands after running kubeadm init
Python Frontend to Redis Service:
kube-proxy’s Role:
CNI’s Role:
Redis Pod Response:
Return Path:
Key Roles in This Interaction:
CNI (Container Network Interface):
kube-proxy:
Redis Service:
Python Frontend Pod Sends Request:
redis-service:6379
).kube-proxy Intercepts Traffic:
Traffic Forwarded to Redis Pod:
Redis Pod Processes the Request:
This process ensures seamless communication between services in the Kubernetes cluster, with kube-proxy handling the routing of traffic to the appropriate Pods.
Additional Considerations:
Plugin | Description |
---|---|
Calico | Supports network policies and BGP routing; ideal for security-focused environments. |
Cilium | High-performance with eBPF-based networking; excels in observability and security. |
Flannel | Lightweight and simple; lacks network policy support. |
Weave Net | Provides encrypted pod-to-pod communication; supports multi-cluster setups. |
Plugin | Description |
---|---|
containerd | Default for most Kubernetes setups; lightweight, optimized, and follows OCI standards. |
CRI-O | Minimal runtime designed for Kubernetes; integrates tightly with OpenShift. |
Kata Containers | Uses lightweight VMs for security; ideal for isolating untrusted workloads. |
gVisor (by Google) | User-space sandboxing for enhanced security; limits direct host access. |
Plugin | Description |
---|---|
Amazon EBS CSI | Provides block storage for Kubernetes workloads on AWS; supports dynamic provisioning. |
Azure Disk CSI | Offers high-performance, persistent storage for Kubernetes on Azure. |
Google PD CSI | Integrates with Google Cloud Persistent Disks; supports snapshots and resizing. |
Ceph RBD CSI | Ideal for scalable, distributed storage; supports snapshots and cloning. |
Portworx CSI | Enterprise-grade storage with high availability, backups, and replication. |
OpenEBS CSI | Lightweight and cloud-native storage for Kubernetes; optimized for local PVs. |
Longhorn CSI | Rancher’s distributed block storage for Kubernetes; supports snapshots and disaster recovery. |
Command:
The user runs kubectl apply -f python-frontend-deployment.yaml
to create a new Deployment.
kubectl Action:
The API Server receives the validated Deployment object and performs the following tasks:
Authentication and Authorization:
Verifies that the user has the correct permissions to create the Deployment.
Validation:
Ensures the Deployment object conforms to the complete Kubernetes schema.
Storage:
Response:
The Deployment Controller is part of the Controller Manager and ensures that the desired number of Pods are running in your cluster.
If the actual number of Pods doesn’t match the desired state:
ReplicaSet Creation:
Pod Creation:
Status Update:
The Scheduler is responsible for assigning unscheduled Pods (Pods without a nodeName
) to appropriate nodes.
nodeName
.nodeName
to indicate where the Pod will run.nodeName
to indicate the assigned node.The Kubelet on the assigned node monitors the API Server for changes to Pod objects.
Container Runtime Interface (CRI):
The Kubelet interacts with the container runtime (e.g., containerd
, CRI-O
) to:
Health Monitoring:
sudo apt-get update
# apt-transport-https may be a dummy package; if so, you can skip that package
sudo apt-get install -y apt-transport-https ca-certificates curl gpg
apt
package index, install kubelet, kubeadm and kubectl, and pin their version:
sudo apt-get update
sudo apt-get install -y kubelet kubeadm kubectl
sudo apt-mark hold kubelet kubeadm kubectl
#!/bin/bash # Update package lists # Install Docker # Install dependencies for Kubernetes # Add Kubernetes apt repository and key # Update package lists again # Install Kubernetes components |
#!/bin/bash # Initialize Kubernetes master # Configure kubectl for current user # Deploy Calico network plugin # Deploy NGINX Ingress Controller |
#!/bin/bash # Install AWSCLI curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" sudo apt install -y unzip unzip awscliv2.zip sudo ./aws/install # Install kubectl curl -o kubectl https://amazon-eks.s3.us-west-2.amazonaws.com/1.19.6/2021-01-05/bin/linux/amd64/kubectl chmod +x ./kubectl sudo mv ./kubectl /usr/local/bin kubectl version --short --client # Install eksctl curl --silent --location "https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz" | tar xz -C /tmp sudo mv /tmp/eksctl /usr/local/bin eksctl version
apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: app-role namespace: webapps rules: - apiGroups: - "" - apps - autoscaling - batch - extensions - policy - rbac.authorization.k8s.io resources: - pods - secrets - componentstatuses - configmaps - daemonsets - deployments - events - endpoints - horizontalpodautoscalers - ingress - jobs - limitranges - namespaces - nodes - pods - persistentvolumes - persistentvolumeclaims - resourcequotas - replicasets - replicationcontrollers - serviceaccounts - services verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: app-rolebinding namespace: webapps roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: app-role subjects: - namespace: webapps kind: ServiceAccount name: jenkins
Generate token using service account in the namespace
apiVersion: v1
kind: Secret
type: kubernetes.io/service-account-token
metadata:
name: mysecretname
annotations:
kubernetes.io/service-account.name: myserviceaccount
To view secret run
$kubectl -n webapps describe secret mysecretname
#!/bin/bash
# Script to install Terraform on an instance
# Update package list and install dependencies
sudo apt-get update && sudo apt-get install -y gnupg software-properties-common
# Add HashiCorp GPG key
wget -O- https://apt.releases.hashicorp.com/gpg | \
gpg --dearmor | \
sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg > /dev/null
# Verify the key fingerprint
gpg --no-default-keyring \
--keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg \
--fingerprint
# Add HashiCorp repository to sources list
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \
https://apt.releases.hashicorp.com $(lsb_release -cs) main" | \
sudo tee /etc/apt/sources.list.d/hashicorp.list
# Update package lists
sudo apt update
# Install Terraform
sudo apt-get install terraform -y
## Verify installation
terraform -v
# Add Docker's official GPG key:
sudo apt-get update
sudo apt-get install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
# Add the repository to Apt sources:
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
$(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}") stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
sudo apt-get update
# apt-transport-https may be a dummy package; if so, you can skip that package
sudo apt-get install -y apt-transport-https ca-certificates curl gnupg
curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.34/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
sudo chmod 644 /etc/apt/keyrings/kubernetes-apt-keyring.gpg # allow unprivileged APT programs to read this keyring
# This overwrites any existing configuration in /etc/apt/sources.list.d/kubernetes.list
echo 'deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.34/deb/ /' | sudo tee /etc/apt/sources.list.d/kubernetes.list
sudo chmod 644 /etc/apt/sources.list.d/kubernetes.list # helps tools such as command-not-found to work correctly
echo fs.inotify.max_user_watches=655360 | sudo tee -a /etc/sysctl.conf
echo fs.inotify.max_user_instances=1280 | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
# Add Docker's official GPG key:
sudo apt-get update
sudo apt-get install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
# Add the repository to Apt sources:
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
$(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}") stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get updatecd
kind | apiVersion |
Pod | v1 |
Service | v1 |
Namespace | v1 |
Replica Controller | v1 |
ReplicaSet | apps/v1 |
Deployment | apps/v1 |
Docker Compose | Ansible | Kubernetes |
version: services: |
- Name: hosts: tasks: |
apiversion: kind: metadata: specs: |
localhost
).https://kubernetes.io. Ensure this API is accessible before launching the main application.
https://kubernetes.io
) in th above case, ensure that an internal Kubernetes Service (main-app-svc) is also available before the main application starts.check-api
):
https://kubernetes.io
before proceeding.check-svc
):
sh -c
→
sh
) to run the entire block of commands as a single script.echo 'Checking main-app Service availability...'
→
until nslookup main-app-svc.default.svc.cluster.local > /dev/null; do
→
nslookup
to check if the DNS entry for the Service main-app-svc.default.svc.cluster.local
is resolvable.until
loop keeps running until DNS resolution succeeds (i.e., until nslookup
returns exit code 0).> /dev/null
discards any output, keeping logs clean.echo 'Waiting for Service DNS resolution...'
→
sleep 5
→
done
→
echo 'Service is reachable, proceeding to main-app container!'
→
In-Summary:
main-app-svc
is DNS-resolvable and available before starting the main container.It blocks the main container until that condition is met—perfect use of an init container to handle dependency readiness.
main-app
):
Main Application Container (main-app
):
80
.Sidecar Container (health-logger
):
||
operator explanation clearly:sh
shell with -c
flag to execute the entire script as a single command.while true; do ... done
to continuously check the main app's health.http://localhost:80
using curl -s
to check if the main app is reachable./dev/null
to discard response content and keep logs clean.&& echo 'Main app is healthy'
to print the message only if the curl
command succeeds (exit code 0).|| echo 'Main app is unhealthy'
to print the message only if the curl
command fails (non-zero exit code).&&
and ||
are logical operators; &&
executes the next command on success, while ||
executes the next command on failure.sleep 5
before repeating the loop.Aspect | Init Containers | Sidecar / Ambassador / Adapter Containers |
---|---|---|
Lifecycle | Run to completion before main container starts | Run alongside main container, continue as long as the pod runs |
Order of Execution | Always run before the main container, in sequence if multiple | Start in parallel with the main container |
Dependency on Success | Main container won’t start unless all init containers complete successfully | Main container can run independently of helper containers (but may rely on their functionality) |
Restart Behavior | Re-run only if they fail before completion | Restart policies apply same as main container (Always , OnFailure , etc.) |
Purpose | Setup, preparation, environment bootstrapping, preconditions check | Enhance, complement, or adapt runtime behavior of the main container |
Resource Consumption | Consume resources temporarily, freed once completed | Consume resources throughout the pod’s lifetime |
Common Use-Cases | - Database migrations - Configuration fetch - Waiting for dependencies - Permission setup |
- Log collection - Proxying (Service Mesh) - External communication handling (Ambassador) - Metrics/log format adaptation |
Visibility to Main Container | Prepare shared volumes or environment, not visible as active containers | Main container and helpers can interact live via shared network & volumes |
Network Behavior | Share network namespace, but only active until completion | Share network namespace, actively communicate during pod lifetime |
Fail Impact | Pod won’t proceed if init fails | If they fail, pod continues, but functionality (e.g., logging, proxying) may degrade |
--- apiVersion: v1 kind: Pod metadata: name: postgress-pod labels: author: aziz type: database spec: containers: - name: mydb image: postgres ... |
--- apiVersion: v1 kind: Pod metadata: name: sql-pod labels: author: aziz type: database spec: containers: - name: mysql image: mysql:5 env: - name: MYSQL_ROOT_PASSWORD value: India123 ... |
--- kind: Pod |
In docker container we define port in run command -p 8080:5050 where 8080 is default container port mapped to 5050, here container port is 8080 which is mapped to 8080 so you can access from your laptop with 8080 port. |
--- version: '3' services: mydb: image: mysql:5 environment: MYSQL_ROOT_PASSWORD: India123 mywordpress: image: wordpress ports: - 9090:80 deploy: replicas: 3 ... |
--- apiVersion: apps/v1 kind: ReplicaSet metadata: name: httpd-rs labels: author: aziz type: webserver spec: replicas: 4 selector: matchLabels: type: webserver template: metadata: name: httpd-pod labels: type: webserver spec: containers: - name: myhttpd: image: httpd ports: -containerPort: 80 hostPort: 8888 ... |
MatchLabels- rs.yaml
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: star-rs
spec:
replicas: 3
selector:
matchLabels:
team: dev
app: star
template:
metadata:
name: dev
labels:
team: dev
app: star
spec:
containers:
- name: webserver2
image: nginx
ports:
- containerPort: 80
|
MatchExpressions: rs1.yaml apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: star-rs
spec:
replicas: 4
selector:
matchExpressions:
- key: team
operator: In
values:
- dev
- prod
template:
metadata:
name: dev
labels:
team: dev
spec:
containers:
- name: webserver2
image: nginx
ports:
- containerPort: 80
|
apiVersion: apps/v1
kind: Deployment
metadata:
name: star-deployment
labels:
app: webserver
spec:
replicas: 4
selector:
matchLabels:
app: webserver
template:
metadata:
labels:
app: webserver
spec:
containers:
- name: nginxpod
image: nginx
ports:
- containerPort: 80
|
ReplicaSet with 3 replicas is created, labels team=prod has been used. you an define multiple labels using matchExpressions, if any pod is deleted then it will be created automatically to maintain desired value. operator = In or NotIn can be used to included or exclude labels. if both define then NotIn will take precedence. |
root@master:~# kubectl get deployment,rs,pod
NAME READY UP-TO-DATE AVAILABLE AGE # deployment
deployment.apps/replication-deployment 3/3 3 3 3m30s # deployment name = replication-deployment
NAME DESIRED CURRENT READY AGE # replica set
replicaset.apps/replication-deployment-d556bf558 3 3 3 3m30s # replica set name= deployment+replicaset number
NAME READY STATUS RESTARTS AGE # list of pods
pod/replication-deployment-d556bf558-gffs7 1/1 Running 0 3m30s # pod name = deployment+rs+pod name
pod/replication-deployment-d556bf558-kqwh7 1/1 Running 0 3m30s
pod/replication-deployment-d556bf558-mx8h8 1/1 Running 0 3m30s
Replication Deployment, nginx 1.14 apiVersion: apps/v1 |
Rolling update with rolling deployment,nginx 1.22 apiVersion: apps/v1 |
Create deployment with nginx 1.14 apiVersion: apps/v1 |
Rolling update with recreate deployment to nginx1.22 apiVersion: apps/v1 |
apiVersion: metallb.io/v1beta1 |
//1.yaml apiVersion: v1 |
//2.yaml
apiVersion: v1 |
apiVersion: v1 kind: Pod metadata: name: memory-demo labels: author: aziz spec: containers: - name: webserver1 image: nginx resources: requests: memory: "100Mi" limits: memory: "100Mi" - name: webserver2 image: tomcat resources: requests: memory: "100Mi" limits: memory: "200Mi" |
Namespace | Purpose |
default | Kubernetes includes this namespace so that you can start using your new cluster without first creating a namespace. |
kube-system | The namespace for objects created by the Kubernetes system. Holds Kubernetes control plane components (e.g., kube-dns, kube-proxy). |
kube-public | This namespace is readable by all clients (including those not authenticated). Publicly accessible data, primarily used for cluster information. |
kube-node-lease | Heartbeats of nodes in the cluster, used by the control plane for node health. |
nodeName
field in the pod’s YAML manifest. This completely bypasses the Kubernetes scheduler.kube-apiserver
, etcd
, and scheduler
run as static pods. /etc/kubernetes/manifests/
.kubectl get pods
, Kubelet creates a "mirror pod" on the API server.kubectl
.Effect | Behaviour |
NoSchedule | New pods will not be scheduled unless they have a matching toleration. |
PreferNoSchedule | Kubernetes tries to avoid scheduling pods but doesn’t enforce it strictly. |
NoExecute | Existing pods without a matching toleration will be evicted from the node. |
In
, NotIn
, Exists
, etc.), unlike nodeSelector
.Limitation | Explanation |
Strict Placement | If no node matches the label, the pod remains in the Pending state. |
No Preferences | It does not allow "soft" preferences—either a node matches or it does not. |
No or Condition | You cannot specify "schedule on nodes with storage=ssd OR storage=hdd ". |
storage=ssd
, the pods remain in the Pending
state. both node and pod spec has the same key=value pair.storage=ssd
and env=prod.
storage=ssd
or storage=hdd
Operator | Behavior |
---|---|
In |
Matches if the node’s label exists in the provided values. |
NotIn |
Matches if the node’s label does not exist in the provided values. |
Exists |
Matches if the node has the specified key, regardless of its value. |
DoesNotExist |
Matches if the node does not have the specified key. |
Gt |
Matches if the label’s value is greater than the specified number. |
Lt |
Matches if the label’s value is less than the specified number. |
Condition | Effect |
---|---|
storage In (ssd, hdd) |
✅ Pod can be scheduled if the node has storage=ssd OR storage=hdd. |
env NotIn (dev) |
✅ Pod is not scheduled on nodes labeled env=dev . |
high-memory Exists |
✅ Pod can be scheduled only on nodes that have a high-memory label. |
dedicated DoesNotExist |
✅ Pod avoids nodes with dedicated label. |
cpu Gt 4 |
✅ Pod can be scheduled only on nodes with CPU > 4. |
disk Lt 500 |
✅ Pod can be scheduled only on nodes with disk < 500. |
replicas
field)apiVersion: v1 kind: Pod metadata: name: prod-server spec: containers: - image: nginx name: prod-server nodeSelector: node: "star1 |
apiVersion: v1 kind: Pod metadata: name: prod-server spec: containers: - image: nginx name: prod-server nodeSelector: node: "star2" |
ImagePullBackOff
and CrashLoopBackOff
with troubleshooting tips, ensuring you can effectively debug and manage pods in any Kubernetes environment.terminationGracePeriodSeconds
in the pod spec) for the container to exit gracefully.SIGKILL
signal to the container's process.
--grace-period=0
, it still tries to respect the pod's default termination grace period (which is usually 30 seconds) unless overridden by the pod's spec.SIGKILL
):Command | API Server (Pod object) | Kubelet (Container termination) | Grace Period Behavior | Explanation |
---|---|---|---|---|
kubectl delete pod mypod |
Deletes Pod gracefully | Kubelet follows normal process | Graceful shutdown | Pod object removed, Kubelet gracefully stops container (SIGTERM, waits for grace period, then SIGKILL). |
kubectl delete pod mypod --force=true |
Deletes Pod immediately | Kubelet still respects terminationGracePeriodSeconds | Graceful unless explicitly overridden | Pod object deleted immediately, but Kubelet still monitors the running container and honors the grace period. |
kubectl delete pod mypod --force=true --grace-period=0 |
Deletes Pod immediately | Kubelet kills container immediately | No grace period, immediate SIGKILL | Pod deleted from API server, Kubelet stops monitoring and forcefully kills the container instantly. |
NAME STATUS AGE default Active 11d kube-node-lease Active 11d kube-public Active 11d kube-system Active 11d metallb-system Active 3d22h |
apiVersion: v1
|
apiVersion: v1 kind: ResourceQuota metadata: name: namespace1-quota namespace: namespace1 spec: hard: pods: "2" configmaps: "10" secrets: "10" services : "10" persistentvolumeclaims: "50" limits.memory: "800Mi" limits.cpu: "10" |
apiVersion: v1 kind: LimitRange metadata: name: cpu-resource-constraint spec: limits: - max: # max and min define the limit range cpu: "500m" min: cpu: 100m type: Container |
apiVersion: v1 kind: LimitRange metadata: name: cpu-resource-constraint spec: limits: - default: # If you do not define max cpu while creating container, it will take default as max cpu: "700m" defaultRequest: # If you do not define min cpu while creating container, it will take defaultRequest as min cpu: "110m" max: # max milicore cpu a container can get cpu: "800m" min: cpu: "100m" #min milicore cpu a container can get type: Container |
apiVersion: v1 kind: Pod metadata: name: busybox1 spec: containers: - name: busybox-cnt01 image: busybox:1.28 command: ["/bin/sh"] args: ["-c", "while true; do echo hello from cnt01; sleep 10;done"] resources: requests: cpu: "100m" limits: cpu: "500m" |
|
apiVersion: v1
|
apiVersion: v1 kind: Pod metadata: name: busybox1 spec: containers: - name: busybox-cnt01 #first container image: busybox:1.28 command: ["/bin/sh"] args: ["-c", "while true; do echo hello from cnt01; sleep 10;done"] resources: requests: cpu: "100m" limits: cpu: "900m" - name: busybox-cnt02 #second container image: busybox:1.28 command: ["/bin/sh"] args: ["-c", "while true; do echo hello from cnt02; sleep 10;done"] resources: requests: cpu: "100m" - name: busybox-cnt03 #third container image: busybox:1.28 command: ["/bin/sh"] args: ["-c", "while true; do echo hello from cnt03; sleep 10;done"] resources: limits: cpu: "500m" - name: busybox-cnt04 #fourth container image: busybox:1.28 command: ["/bin/sh"] args: ["-c", "while true; do echo hello from cnt04; sleep 10;done"] |
apiVersion: v1
kind: LimitRange
metadata:
name: limit-mem-cpu-per-pod
spec:
limits:
- max:
cpu: "2"
memory: "2Gi"
min:
cpu: "1"
memory: "1Gi"
type: Pod
|
apiVersion: v1
kind: Pod
metadata:
name: busybox2
spec:
containers:
- name: busybox-cnt01
image: busybox:1.28
command: ["/bin/sh"]
args: ["-c", "while true; do echo hello from cnt01; sleep 10;done"]
resources:
requests:
memory: "100Mi"
cpu: "100m"
limits:
memory: "200Mi"
cpu: "500m"
|
apiVersion: v1
kind: LimitRange
metadata:
name: storagelimits
spec:
limits:
- type: PersistentVolumeClaim
max:
storage: 2Gi
min:
storage: 1Gi
|
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: pvc-limit-lower
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
|
apply | It applies changes to Kubernetes resources defined in YAML or JSON files | |
kubectl apply -f deployment.yaml | This command applies the code specified in the deployment.yaml file to the cluster. | |
kubectl apply -f deployment.yaml --record | This command applies the changes specified in the deployment.yaml file to the deployment and records the changes in the revision history. | |
kubectl apply -f pod.yaml --namespace=my-namespace | This command applies the configuration specified in pod.yaml to the namespace my-namespace. | |
kubectl apply -f deployment.yaml --namespace=my-namespace --record | This command applies the changes specified in deployment.yaml to the deployment in the namespace my-namespace and records the changes. | |
kubectl apply -f ./my-resources/ --recursive | This command applies all YAML files located in the my-resources directory and its subdirectories | |
kubectl apply -f pod.yaml --validate=true | This command validates the pod.yaml file before applying changes to the cluster. | |
kubectl apply -f pod.yaml --dry-run=client | This command checks if the configuration in pod.yaml can be applied without actually applying it. | |
annotate | This command adds or updates annotations on Kubernetes resources. | |
kubectl annotate pod my-pod description="This is my pod" | This command adds the annotation description="This is my pod" to the pod named my-pod | |
alias | alias k=kubectl | it sets k as alias for kubectl, you can run k get nodes instead of kubectl get nodes. |
api-resources | This command lists all available API resources. | |
ai-versions | ||
attach | ||
auth | ||
kubectl api-resources | This command lists all the API resources supported by the Kubernetes API server. | |
config | ||
completion | ||
cp | ||
create | This command is used to create Kubernetes resources from files or stdin. | |
kubectl create -f pod.yaml | This command creates a pod using the configuration specified in the pod.yaml file | |
kubectl create namespace my-namespace | This command creates a new namespace named my-namespace | |
kubectl create -f ./my-resources/ | This command creates Kubernetes resources defined in all .yaml files located in the my-resources directory. | |
kubectl create secret generic my-secret --from-literal=username=admin --from-literal=password=passw0rd | This command creates a secret named my-secret with two key-value pairs: username=admin and password=passw0rd. | |
kubectl create deployment my-deployment --image=my-image:tag | This command creates a deployment named my-deployment using the image my-image:tag. | |
kubectl create secret generic my-secret --from-file=./my-secret-file | This command creates a generic secret named my-secret from the contents of the file my-secret-file. | |
kubectl create service nodeport my-service --tcp=80:8080 | This command creates a NodePort service named my-service to expose a deployment on port 8080. | |
kubectl create -f pod.yaml --dry-run=client | This command validates the configuration in pod.yaml without actually creating the pod. | |
kubectl create role my-role --verb=get --resource=pods | This command creates a role named my-role with permissions to get pods within the namespace. | |
kubectl create serviceaccount my-service-account | This command creates a service account named my-service-account within the current namespace. | |
kubectl create configmap my-config --from-literal=key1=value1 --from-literal=key2=value2 | This command creates a config map named my-config with two key-value pairs: key1=value1 and key2=value2. | |
cluster-info | It displays cluster info such as server URL and Kubernetes version. | |
kubectl cluster-info | This command displays information about the Kubernetes cluster. | |
delete | ||
debug |
kubectl describe pod podname kubectl logs podname |
|
describe | ||
edit | ||
exec | ||
explain | ||
expose | ||
kubectl get: It is used to retrieve Kubernetes resources. For instance:
kubectl get pods (This command retrieves all pods in the current namespace).
kubectl describe: This command provides detailed information about a Kubernetes resource. For example:
kubectl describe pod my-pod
This command describes the pod named my-pod, displaying detailed information including its status, containers, and events.
kubectl delete: It is used to delete Kubernetes resources. For instance:
kubectl delete pod my-pod
This command deletes the pod named my-pod.
kubectl exec: This command executes commands inside a running container in a pod. For example:
kubectl exec -it my-pod -- /bin/bash
This command starts an interactive shell (/bin/bash) inside the pod named my-pod.
kubectl logs: It retrieves the logs of a pod. For instance:
kubectl logs my-pod
This command displays the logs of the pod named my-pod.
kubectl port-forward: This command forwards one or more local ports to a pod. For example:
kubectl port-forward my-pod 8080:80
This command forwards local port 8080 to port 80 on the pod named my-pod.
kubectl scale: It scales the number of replicas of a resource. For instance:
kubectl scale --replicas=3 deployment/my-deployment
This command scales the number of replicas of the deployment named my-deployment to 3.
kubectl edit: This command edits the resource definition in a text editor. For example:
kubectl edit pod my-pod
This command opens the resource definition of the pod named my-pod in a text editor, allowing you to make changes.
kubectl rollout: This command manages rollouts of updates to Kubernetes resources. For example:
kubectl rollout status deployment/my-deployment
This command checks the status of the rollout for the deployment named my-deployment.
kubectl label: It adds or updates labels on Kubernetes resources. For instance:
kubectl label pod my-pod app=backend
This command adds the label app=backend to the pod named my-pod.
kubectl rollout history: This command views rollout history of a deployment. For instance:
kubectl rollout history deployment/my-deployment
This command displays the rollout history of the deployment named my-deployment.
kubectl rollout undo: It rolls back a deployment to a previous revision. For example:
kubectl rollout undo deployment/my-deployment
This command rolls back the deployment named my-deployment to the previous revision.
kubectl apply --dry-run: It simulates the apply of configuration without actually executing it. For example:
kubectl apply -f pod.yaml --dry-run=client
This command checks if the configuration in pod.yaml can be applied without actually applying it.
kubectl get pods -o wide: It retrieves pods with additional details including node name and IP address. For instance:
kubectl get pods -o wide
This command displays pods along with additional details such as the node they are running on and their IP addresses.
kubectl describe node: This command provides detailed information about a Kubernetes node. For example:
kubectl describe node my-node
This command describes the node named my-node, displaying detailed information including its capacity, allocatable resources, and conditions.
kubectl rollout pause: It pauses a rollout of a deployment. For instance:
kubectl rollout pause deployment/my-deployment
This command pauses the rollout of the deployment named my-deployment.
kubectl rollout resume: This command resumes a paused rollout of a deployment. For example:
kubectl rollout resume deployment/my-deployment
This command resumes the paused rollout of the deployment named my-deployment.
kubectl delete namespace: It deletes a Kubernetes namespace and all resources within it. For instance:
kubectl delete namespace my-namespace
This command deletes the namespace named my-namespace along with all resources within it.
kubectl get events: This command retrieves events from the cluster. For example:
kubectl get events
This command retrieves all events from the cluster, displaying information such as type, reason, and message.
kubectl get pods --show-labels: It displays additional labels associated with pods. For instance:
kubectl get pods --show-labels
This command displays pods along with all labels associated with them.
kubectl exec -it my-pod -- ls /app: This command executes a command (ls /app) inside a running container in a pod interactively. For example:
kubectl exec -it my-pod -- ls /app
This command lists the contents of the /app directory inside the pod named my-pod.
kubectl edit deployment: This command opens the deployment configuration in a text editor, allowing you to make changes. For example:
kubectl edit deployment/my-deployment
This command opens the configuration of the deployment named my-deployment in a text editor.
kubectl rollout restart: It restarts a rollout of a deployment by reapplying the current configuration. For instance:
kubectl rollout restart deployment/my-deployment
This command restarts the rollout of the deployment named my-deployment.
kubectl rollout status: This command checks the status of a rollout for a deployment. For example:
kubectl rollout status deployment/my-deployment
This command checks the status of the rollout for the deployment named my-deployment.
kubectl exec -it my-pod -- sh -c 'echo $ENV_VAR': This command executes a shell command (echo $ENV_VAR) inside a running container in a pod. For instance:
kubectl exec -it my-pod -- sh -c 'echo $ENV_VAR'
This command prints the value of the environment variable ENV_VAR inside the pod named my-pod.
kubectl get pods --field-selector=status.phase=Running: This command retrieves pods with a specific status phase, such as Running. For instance:
kubectl get pods --field-selector=status.phase=Running
This command retrieves all pods in the current namespace that are in the Running phase.
kubectl delete pod --grace-period=0 --force my-pod: It forcefully deletes a pod without waiting for the grace period. For example:
kubectl delete pod --grace-period=0 --force my-pod
This command forcefully deletes the pod named my-pod without waiting for the grace period to elapse.
kubectl describe service: This command provides detailed information about a Kubernetes service. For instance:
kubectl describe service my-service
This command describes the service named my-service, displaying detailed information including its endpoints and selectors.
kubectl get deployment -o yaml: This command retrieves deployments and outputs the result in YAML format. For instance:
kubectl get deployment -o yaml
This command retrieves all deployments in the current namespace and outputs the result in YAML format.
kubectl scale deployment: This command scales the number of replicas of a deployment. For example:
kubectl scale deployment/my-deployment --replicas=3
This command scales the deployment named my-deployment to have 3 replicas.
kubectl rollout history deployment: It displays the revision history of a deployment. For instance:
kubectl rollout history deployment/my-deployment
This command shows the revision history of the deployment named my-deployment.
kubectl rollout undo deployment --to-revision=: This command rolls back a deployment to a specific revision. For example:
kubectl rollout undo deployment/my-deployment --to-revision=3
This command rolls back the deployment named my-deployment to the third revision.
kubectl logs -f my-pod: This command streams the logs of a pod continuously. For instance:
kubectl logs -f my-pod
This command continuously streams the logs of the pod named my-pod to the terminal.
kubectl get svc: It retrieves information about services in the cluster. For example:
kubectl get svc
This command retrieves information about all services in the current namespace.
kubectl get pods -n : This command retrieves pods from a specific namespace. For instance:
kubectl get pods -n my-namespace
This command retrieves all pods from the namespace my-namespace.
kubectl delete -f pod.yaml: It deletes resources specified in a YAML file. For example:
kubectl delete -f pod.yaml
This command deletes the resources specified in the pod.yaml file.
kubectl rollout status deployment/my-deployment: This command checks the status of a deployment rollout. For instance:
kubectl rollout status deployment/my-deployment
This command checks the status of the rollout for the deployment named my-deployment.
kubectl exec -it my-pod -- /bin/bash: This command starts an interactive shell inside a pod. For example:
kubectl exec -it my-pod -- /bin/bash
This command opens an interactive shell (/bin/bash) inside the pod named my-pod, allowing you to execute commands within it.
kubectl rollout history deployment/my-deployment --revision=3: It displays details of a specific revision in the rollout history of a deployment. For instance:
kubectl rollout history deployment/my-deployment --revision=3
This command shows details of the third revision in the rollout history of the deployment named my-deployment.
kubectl rollout undo deployment/my-deployment --to-revision=2: This command rolls back a deployment to a specific revision. For example:
kubectl rollout undo deployment/my-deployment --to-revision=2
This command rolls back the deployment named my-deployment to the second revision.
kubectl logs my-pod --tail=100: This command retrieves the last 100 lines of logs from a pod. For example:
kubectl logs my-pod --tail=100
This command retrieves the last 100 lines of logs from the pod named my-pod.
kubectl get services -o wide: It retrieves services with additional details including node port and cluster IP. For instance:
kubectl get services -o wide
This command retrieves services along with additional details such as node port and cluster IP.
kubectl get pods --field-selector=status.phase!=Running: This command retrieves pods with a status phase other than Running. For example:
kubectl get pods --field-selector=status.phase!=Running
This command retrieves all pods in the current namespace that are not in the Running phase.
kubectl delete pod my-pod --force --grace-period=0: It forcefully deletes a pod without waiting for the grace period. For example:
kubectl delete pod my-pod --force --grace-period=0
This command forcefully deletes the pod named my-pod without waiting for the grace period to elapse.
kubectl describe service my-service: This command provides detailed information about a Kubernetes service. For instance:
kubectl describe service my-service
This command describes the service named my-service, displaying detailed information including its endpoints and selectors.
kubectl expose deployment my-deployment --type=LoadBalancer --port=80 --target-port=8080: It exposes a deployment as a service with a specified type, port, and target port. For example:
kubectl expose deployment my-deployment --type=LoadBalancer --port=80 --target-port=8080
This command exposes the deployment named my-deployment as a LoadBalancer service on port 80, targeting port 8080 on the pods.
kubectl get deployments -l app=my-app: This command retrieves deployments labeled with app=my-app. For example:
kubectl get deployments -l app=my-app
This command retrieves all deployments labeled with app=my-app.
kubectl rollout pause deployment/my-deployment: It pauses the rollout of a deployment. For instance:
kubectl rollout pause deployment/my-deployment
This command pauses the rollout of the deployment named my-deployment.
kubectl rollout resume deployment/my-deployment: This command resumes the rollout of a deployment. For example:
kubectl rollout resume deployment/my-deployment
This command resumes the paused rollout of the deployment named my-deployment.
kubectl logs my-pod --container=nginx: It retrieves logs from a specific container within a pod. For instance:
kubectl logs my-pod --container=nginx
This command retrieves logs from the container named nginx within the pod my-pod.
kubectl get pods --sort-by=.metadata.creationTimestamp: It retrieves pods sorted by creation timestamp. For instance:
kubectl get pods --sort-by=.metadata.creationTimestamp
This command retrieves all pods in the current namespace sorted by their creation timestamp in ascending order.
kubectl describe persistentvolumeclaim my-pvc: This command provides detailed information about a persistent volume claim. For example:
kubectl describe persistentvolumeclaim my-pvc
This command describes the persistent volume claim named my-pvc, displaying detailed information including its status and storage class.
kubectl rollout status deployment/my-deployment --watch: It continuously monitors the status of a deployment rollout. For instance:
kubectl rollout status deployment/my-deployment --watch
This command continuously monitors the status of the rollout for the deployment named my-deployment.
kubectl get pods --field-selector=status.phase=Pending: This command retrieves pods with a status phase of Pending. For example:
kubectl get pods --field-selector=status.phase=Pending
This command retrieves all pods in the current namespace that are in the Pending phase.
kubectl rollout restart deployment/my-deployment: This command restarts a rollout of a deployment by reapplying the current configuration. For example:
kubectl rollout restart deployment/my-deployment
This command restarts the rollout of the deployment named my-deployment.
kubectl label namespace my-namespace env=dev: It adds a label to a namespace. For instance:
kubectl label namespace my-namespace env=dev
This command adds the label env=dev to the namespace named my-namespace.
kubectl delete deployment my-deployment: This command deletes a deployment. For example:
kubectl delete deployment my-deployment
This command deletes the deployment named my-deployment.
kubectl get pods --namespace=my-namespace: It retrieves pods from a specific namespace. For instance:
kubectl get pods --namespace=my-namespace
This command retrieves all pods from the namespace my-namespace.
kubectl describe secret my-secret: This command provides detailed information about a secret. For example:
kubectl describe secret my-secret
This command describes the secret named my-secret, displaying detailed information including its type and data.
kubectl delete service my-service: It deletes a service. For instance:
kubectl delete service my-service
This command deletes the service named my-service.
kubectl get nodes: This command retrieves information about nodes in the cluster. For example:
kubectl get nodes
This command retrieves information about all nodes in the cluster.
kubectl rollout history deployment/my-deployment --revision=3: This command displays details of a specific revision in the rollout history of a deployment. For example:
kubectl rollout history deployment/my-deployment --revision=3
This command shows details of the third revision in the rollout history of the deployment named my-deployment.
kubectl top pods: It displays resource usage (CPU and memory) of pods in the cluster. For instance:
kubectl top pods
This command displays resource usage of all pods in the cluster.
kubectl explain pod: This command provides documentation about the Pod resource, including all its fields and their descriptions. For example:
kubectl explain pod
This command displays detailed documentation about the Pod resource.
kubectl delete namespace my-namespace: It deletes a namespace and all resources within it. For instance:
kubectl delete namespace my-namespace
This command deletes the namespace named my-namespace along with all resources within it.
kubectl get pv: This command retrieves information about persistent volumes in the cluster. For example:
kubectl get pv
This command retrieves information about all persistent volumes in the cluster.
kubectl rollout status deployment/my-deployment --timeout=2m: It checks the status of a rollout and waits for a specific timeout before exiting. For instance:
kubectl rollout status deployment/my-deployment --timeout=2m
This command checks the status of the rollout for the deployment named my-deployment and waits for a maximum of 2 minutes.
kubectl get secrets: It retrieves information about secrets in the cluster. For instance:
kubectl get secrets
This command retrieves information about all secrets in the current namespace.
kubectl rollout undo deployment/my-deployment --to-revision=2 --dry-run: It simulates rolling back a deployment to a specific revision without actually performing the rollback. For example:
kubectl rollout undo deployment/my-deployment --to-revision=2 --dry-run
This command simulates rolling back the deployment named my-deployment to the second revision without actually performing the rollback.
kubectl exec -it my-pod --container=my-container -- /bin/bash: This command starts an interactive shell inside a specific container within a pod. For example:
kubectl exec -it my-pod --container=my-container -- /bin/bash
This command opens an interactive shell (/bin/bash) inside the container named my-container within the pod named my-pod.
kubectl describe persistentvolume my-pv: This command provides detailed information about a persistent volume. For example:
kubectl describe persistentvolume my-pv
This command describes the persistent volume named my-pv, displaying detailed information including its capacity and access modes.
kubectl get events --sort-by=.metadata.creationTimestamp: This command retrieves events sorted by creation timestamp. For example:
kubectl get events --sort-by=.metadata.creationTimestamp
This command retrieves all events in the current namespace sorted by their creation timestamp in ascending order.
kubectl describe ingresses.extensions: It provides detailed information about an Ingress resource. For instance:
kubectl describe ingresses.extensions
This command describes all Ingress resources in the current namespace, displaying detailed information about each Ingress.
kubectl rollout undo deployment/my-deployment --dry-run=client: It simulates rolling back a deployment to the previous revision without actually performing the rollback. For example:
kubectl rollout undo deployment/my-deployment --dry-run=client
This command simulates rolling back the deployment named my-deployment to the previous revision without actually performing the rollback.
kubectl scale deployment/my-deployment --replicas=5 --record: This command scales the number of replicas of a deployment to 5 and records the change. For example:
kubectl scale deployment/my-deployment --replicas=5 --record
This command scales the deployment named my-deployment to have 5 replicas and records the change.
kubectl delete secret my-secret: It deletes a secret. For instance:
kubectl delete secret my-secret
This command deletes the secret named my-secret.
kubectl get ingress: This command retrieves information about Ingress resources in the cluster. For example:
kubectl get ingress
This command retrieves information about all Ingress resources in the current namespace.
#!/bin/bash # Update package lists # Install Docker # Install dependencies for Kubernetes # Add Kubernetes apt repository and key # Update package lists again # Install Kubernetes components |
#!/bin/bash # Initialize Kubernetes master # Configure kubectl for current user # Deploy Calico network plugin # Deploy NGINX Ingress Controller |
wget -O /usr/share/keyrings/jenkins-keyring.asc \
https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key
echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] \
https://pkg.jenkins.io/debian-stable binary/ | sudo tee \
/etc/apt/sources.list.d/jenkins.list > /dev/null
# Add Docker's official GPG key:
sudo apt-get update
sudo apt-get install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
# Add the repository to Apt sources:
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
$(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
# Add Docker's official GPG key:
sudo apt-get update
sudo apt-get install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
# Add the repository to Apt sources:
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
$(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
#!/bin/bash # Install AWSCLI curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" sudo apt install -y unzip unzip awscliv2.zip sudo ./aws/install # Install kubectl curl -o kubectl https://amazon-eks.s3.us-west-2.amazonaws.com/1.19.6/2021-01-05/bin/linux/amd64/kubectl chmod +x ./kubectl sudo mv ./kubectl /usr/local/bin kubectl version --short --client # Install eksctl curl --silent --location "https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz" | tar xz -C /tmp sudo mv /tmp/eksctl /usr/local/bin eksctl version
wget -O /usr/share/keyrings/jenkins-keyring.asc \
https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key
echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] \
https://pkg.jenkins.io/debian-stable binary/ | sudo tee \
/etc/apt/sources.list.d/jenkins.list > /dev/null
# Add Docker's official GPG key:
sudo apt-get update
sudo apt-get install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
# Add the repository to Apt sources:
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
$(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
# Add Docker's official GPG key:
sudo apt-get update
sudo apt-get install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
# Add the repository to Apt sources:
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
$(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
apiVersion: v1 kind: ServiceAccount metadata: name: jenkins namespace: webapps
apiVersion: v1
kind: ConfigMap
metadata:
name: mongodb-configmap
data:
db_host: mongodb-service
apiVersion: v1
kind: Secret
metadata:
name: mongodb-secret
type: Opaque
data:
username: dXNlcm5hbWU=
password: cGFzc3dvcmQ=
apiVersion: apps/v1
kind: Deployment
metadata:
name: mongodb
labels:
app: mongodb
spec:
replicas: 1
selector:
matchLabels:
app: mongodb
template:
metadata:
labels:
app: mongodb
spec:
containers:
- name: mongodb
image: mongo
ports:
- containerPort: 27017
env:
- name: MONGO_INITDB_ROOT_USERNAME
valueFrom:
secretKeyRef:
name: mongodb-secret
key: username
- name: MONGO_INITDB_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mongodb-secret
key: password
apiVersion: v1
kind: Service
metadata:
name: mongodb-service
spec:
selector:
app: mongodb
ports:
- protocol: TCP
port: 27017
targetPort: 27017
apiVersion: apps/v1
kind: Deployment
metadata:
name: mongo-express
labels:
app: mongo-express
spec:
replicas: 1
selector:
matchLabels:
app: mongo-express
template:
metadata:
labels:
app: mongo-express
spec:
containers:
- name: mongo-express
image: mongo-express
ports:
- containerPort: 8081
env:
- name: ME_CONFIG_MONGODB_ADMINUSERNAME
valueFrom:
secretKeyRef:
name: mongodb-secret
key: username
- name: ME_CONFIG_MONGODB_ADMINPASSWORD
valueFrom:
secretKeyRef:
name: mongodb-secret
key: password
- name: ME_CONFIG_MONGODB_SERVER
valueFrom:
configMapKeyRef:
name: mongodb-configmap
key: db_host
apiVersion: v1
kind: Service
metadata:
name: mongo-express-service
spec:
selector:
app: mongo-express
type: LoadBalancer
ports:
- protocol: TCP
port: 8081
targetPort: 8081
nodePort: 30000
These YAML configuration are Kubernetes manifest file that defines various resources for deploying a MongoDB database and a web-based MongoDB management tool called "mongo-express." Let's break down the different sections and resources defined in this configuration:
In summary, this YAML configuration sets up a Kubernetes cluster with a MongoDB database and a web-based MongoDB management tool (mongo-express). It uses ConfigMaps and Secrets to manage configuration and sensitive data and defines Services to allow external access to the MongoDB and mongo-express components. |