kubernetes doc

This commit is contained in:
2025-06-30 13:21:52 +03:30
parent 1b7774ebab
commit fba77d8bf6
26 changed files with 314 additions and 231 deletions

View File

@@ -0,0 +1,72 @@
# Kubernetes Namespaces Guide
Kubernetes **namespaces** allow you to organize and isolate resources within your cluster.
---
## 🧾 Listing Namespaces
To list all namespaces:
```bash
kubectl get namespaces
```
or the shorthand:
```bash
kubectl get ns
```
---
## 🛠️ Creating a Namespace
Create a new namespace:
```bash
kubectl create namespace <namespace-name>
```
or:
```bash
kubectl create ns <namespace-name>
```
---
## 🗑️ Deleting a Namespace
Delete a namespace:
```bash
kubectl delete ns <namespace-name>
```
---
## ⚠️ Best Practices & Notes
* **Namespaces are isolated**, but they **can still communicate** with each other by default.
* It is **not recommended to create namespaces that start with `kube-`**, as those are typically reserved for system components.
---
## 📄 Creating a Namespace with a Manifest
You can define a namespace using a YAML manifest:
```yaml
apiVersion: v1
kind: Namespace
metadata:
name: namespace-test
```
Apply it using:
```bash
kubectl apply -f namespace.yaml
```

View File

@@ -0,0 +1,189 @@
### **1st Document: Namespace**
```yaml
apiVersion: v1
```
* Specifies the API version used. Here, it's version 1 of the core Kubernetes API.
```yaml
kind: Namespace
```
* Declares the resource type. This is a **Namespace**, which logically isolates groups of resources.
```yaml
metadata:
name: ns
```
* Metadata block.
* `name: ns` sets the name of the namespace to `ns`.
---
### **2nd Document: Service**
```yaml
---
```
* Separates multiple documents in the YAML file.
```yaml
apiVersion: v1
```
* Uses the core v1 API again.
```yaml
kind: Service
```
* Declares a **Service** resource, which provides stable networking to access pods.
```yaml
metadata:
name: nginx-service
namespace: ns
labels:
app: nginx
```
* Metadata block:
* `name: nginx-service`: name of the Service.
* `namespace: ns`: places this service in the previously created `ns` namespace.
* `labels`: key-value pairs used for organizing and selecting resources. Here, `app: nginx`.
```yaml
spec:
type: ClusterIP
```
* `spec` describes the behavior.
* `type: ClusterIP`: exposes the service internally within the cluster using a virtual IP.
```yaml
selector:
app: nginx
```
* This selects pods with the label `app: nginx` to receive traffic from this service.
```yaml
ports:
- name: http
port: 80
targetPort: 8080
```
* Defines port configuration:
* `name: http`: a name for the port (optional but useful for readability).
* `port: 80`: the port that the service exposes internally.
* `targetPort: 8080`: the port on the pod that receives the traffic.
---
### **3rd Document: Deployment**
```yaml
---
```
* Separates from the previous document.
```yaml
apiVersion: apps/v1
```
* Uses the `apps/v1` API group, suitable for deployments and other controllers.
```yaml
kind: Deployment
```
* Declares a **Deployment**, which ensures a specified number of pod replicas are running.
```yaml
metadata:
name: nginx-deployment
namespace: ns
labels:
app: nginx
```
* Metadata block:
* `name: nginx-deployment`: name of the deployment.
* `namespace: ns`: places this in the `ns` namespace.
* `labels: app: nginx`: used for matching with selectors.
```yaml
spec:
replicas: 2
```
* Desired number of pod replicas to run: 2.
```yaml
selector:
matchLabels:
app: nginx
```
* Tells the deployment which pods to manage, by matching labels (`app: nginx`).
```yaml
template:
metadata:
labels:
app: nginx
```
* Template for creating new pods:
* Each pod created will have `app: nginx` label.
```yaml
spec:
containers:
- name: nginx
image: nginx:latest
```
* Pod spec:
* One container named `nginx`, using the latest official Nginx image.
```yaml
ports:
- containerPort: 8080
```
* The container exposes port 8080 (must match the `targetPort` in the Service).
```yaml
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "250m"
memory: "256Mi"
```
* **Resource management**:
* `requests`: the minimum guaranteed resources.
* `cpu: 100m` = 0.1 CPU core.
* `memory: 128Mi` = 128 MiB RAM.
* `limits`: the maximum resources the container can use.
* `cpu: 250m` = 0.25 CPU core.
* `memory: 256Mi` = 256 MiB RAM.

View File

@@ -0,0 +1,138 @@
# 🌐 Kubernetes Pod Management Guide
A concise guide for managing Kubernetes Pods using `kubectl` and YAML manifests.
---
## 📋 Listing Pods
### 🔹 Default Namespace
List all Pods in the **default** namespace:
```bash
kubectl get pods
```
### 🔹 Wide Output (More Info)
List Pods with extended details (e.g., IP, node, etc.):
```bash
kubectl get pods -o wide
```
### 🔹 Specific Namespace
List Pods in a specific namespace:
```bash
kubectl get pods -o wide -n <namespace-name>
```
---
## 🚀 Running a Pod
> **Note:** `kubectl run` is ideal for quick tests or running **single** Pods. For production workloads, use **YAML manifests** or **Deployments**.
### 🔹 Run a Pod in Default Namespace
```bash
kubectl run <pod-name> --image=<image-name>
```
### 🔹 Run a Pod in a Specific Namespace
```bash
kubectl run <pod-name> --image=<image-name> -n <namespace>
```
---
## ❌ Deleting Pods
### 🔹 Standard Delete
```bash
kubectl delete pod <pod-name> -n <namespace-name>
```
### 🔹 Force Delete
```bash
kubectl delete pod <pod-name> -n <namespace-name> --force
```
### 🔹 Immediate Force Delete (No Grace Period)
```bash
kubectl delete pod <pod-name> -n <namespace-name> --force --grace-period=0
```
---
## ✏️ Editing a Pod
> **Warning:** Pods are **not directly editable**. Attempting to edit a running pod will result in a temporary patch but not persistent changes.
```bash
kubectl edit pod -n <namespace> <pod-name>
```
---
## 🔧 Executing into a Pod
Use this to start a shell or run commands inside a container:
```bash
kubectl exec -it -n <namespace> <pod-name> -- <command>
```
Example for a shell:
```bash
kubectl exec -it -n dev my-pod -- /bin/bash
```
---
## 🧾 Example Pod YAML Manifest
A multi-container Pod with resource limits and node selector:
```yaml
apiVersion: v1
kind: Pod
metadata:
namespace: dev
name: pod-1
labels:
label1: test
label2: test2
app.kubernetes.io/label3: test3
app.kubernetes.io/label4: test4
spec:
containers:
- name: nginx-server
image: nginx
- name: nginx-exporter
image: nginx-exporter
- name: ubuntu-c0
image: ubuntu
command: ["/bin/bash", "-c", "while true; do echo hello-world; sleep 5; done"]
resources:
limits:
memory: "256Mi"
cpu: "250m"
requests:
memory: "128Mi"
cpu: "125m"
nodeSelector:
hostname: k3s
app.kubernetes.io/disk: ssd
```

View File

@@ -0,0 +1,80 @@
# 🧩 Kubernetes ReplicaSet Management
A guide to working with **ReplicaSets** in Kubernetes, including inspection, editing behavior, and configuration examples.
---
## 📦 Listing Pods and ReplicaSets
### 🔹 List Pods in a Namespace
```bash
kubectl get pod -n <namespace>
```
### 🔹 List ReplicaSets in a Namespace
```bash
kubectl get rs -n <namespace>
```
---
## ✏️ Editing a ReplicaSet
You can attempt to edit a ReplicaSet:
```bash
kubectl edit rs -n <namespace> <replica-set-name>
```
> ⚠️ **Note:**
> Editing the **image** in a ReplicaSet directly will not automatically update existing Pods.
> This is because ReplicaSets do not perform **rolling updates**.
> Pods will only use the new image **after the old ones are deleted and new ones are created**.
**To apply image changes effectively:**
1. **Delete existing Pods** manually:
```bash
kubectl delete pod -l <label-selector> -n <namespace>
```
2. **Or**, use a higher-level controller like a **Deployment** for image updates and rolling behavior.
---
## 🧾 Example ReplicaSet YAML
Below is a minimal and clear ReplicaSet configuration:
```yaml
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: app-1
namespace: dev
labels:
label1: test1
app.kubernetes.io/label2: test2
spec:
replicas: 3
selector:
matchLabels:
app.kubernetes.io/label2: test2
template:
metadata:
labels:
app.kubernetes.io/label2: test2
os: linux
spec:
containers:
- name: nginx
image: nginx
```
> ✅ **Tip:**
> Ensure that the `template.metadata.labels` **matches exactly** with `spec.selector.matchLabels`.
> This is critical for proper ReplicaSet Pod matching.

View File

@@ -0,0 +1,107 @@
# 🚀 Kubernetes Deployment Management
A guide to managing **Deployments** in Kubernetes, including listing, editing, scaling, rollbacks, and version history.
---
## 📋 Listing & Editing Deployments
### 🔹 List Deployments in a Namespace
```bash
kubectl get deploy -n <namespace>
```
### 🔹 Edit a Deployment
```bash
kubectl edit deployment.apps -n <namespace> <deployment-name>
```
> 🛠️ **Note:**
> Unlike ReplicaSets, Deployments **automatically update** existing Pods when the image or spec is changed. This makes Deployments ideal for rolling updates and version control.
---
## 📈 Scaling a Deployment
Scale the number of replicas (Pods) for a Deployment:
```bash
kubectl scale -n <namespace> deployment <deployment-name> --replicas=<number>
```
---
## 🔁 Rollout Management
### 🔹 View Rollout History
```bash
kubectl rollout history deployment -n <namespace> <deployment-name>
```
### 🔹 View Specific Revision
```bash
kubectl rollout history deployment -n <namespace> <deployment-name> --revision=<revision-number>
```
### 🔹 Roll Back to a Previous Revision
```bash
kubectl rollout undo deployment -n <namespace> <deployment-name> --to-revision=<revision-number>
```
> ✅ **Tip:**
> Deployments maintain revision history. This allows you to **roll back to a previous working version** in case of failure.
---
## 🧾 Example Deployment YAML
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-1
namespace: dev
labels:
label1: test1
app.kubernetes.io/label2: test2
spec:
replicas: 3
selector:
matchLabels:
app.kubernetes.io/label2: test2
template:
metadata:
labels:
app.kubernetes.io/label2: test2
os: linux
spec:
containers:
- name: nginx
image: nginx
```
> 🎯 **Why use Deployments?**
> They offer:
* Rolling updates
* Rollbacks
* Declarative Pod management
* History tracking
---
## ✅ Summary
| Feature | Pod | ReplicaSet | Deployment |
| ---------------- | --- | ---------- | ---------- |
| Manual creation | ✅ | 🚫 | 🚫 |
| Scales Pods | ❌ | ✅ | ✅ |
| Self-healing | ❌ | ✅ | ✅ |
| Rolling updates | ❌ | ❌ | ✅ |
| Revision history | ❌ | ❌ | ✅ |

View File

@@ -0,0 +1,67 @@
# 📈 Horizontal Pod Autoscaler (HPA)
The Horizontal Pod Autoscaler automatically scales the number of pods in a deployment based on observed CPU utilization (or other select metrics).
---
## ⚙️ Basic Commands
### 🚀 Create an HPA
Create an HPA for a deployment, scaling based on CPU usage:
```bash
kubectl -n <namespace> autoscale deployment <deployment-name> --cpu-percent=20 --min=4 --max=10
````
### 📊 View Existing HPAs
List all HPAs in a specific namespace:
```bash
kubectl get hpa -n <namespace>
```
### ❌ Delete an HPA
Remove a Horizontal Pod Autoscaler:
```bash
kubectl delete hpa -n <namespace> <hpa-name>
```
### 🛠️ Edit an HPA
Manually edit an existing HPA configuration:
```bash
kubectl edit hpa -n <namespace> <hpa-name>
```
---
## 🧾 Example HPA Manifest
You can define an HPA using a YAML file for more control:
```yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: hpa-test
namespace: dev
spec:
minReplicas: 1
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
```
> **Note:** The above manifest uses API version `autoscaling/v2` for enhanced metric support.
---

View File

@@ -0,0 +1,40 @@
# 🧩 DaemonSet in Kubernetes
A **DaemonSet** ensures that a copy of a specific pod runs on **every (or some) node** in the cluster. Its typically used for background system-level services like log collection, monitoring, or networking tools.
---
## 📌 Key Characteristics
- Automatically deploys one pod per worker node.
- Ensures the pod stays on each node as long as the DaemonSet exists.
- Automatically adds pods to new nodes when they join the cluster.
---
## 📄 Example DaemonSet YAML
Below is a simple DaemonSet example that deploys `nginx` to every node in the `web` namespace:
```yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: nginx
namespace: web
labels:
app: web-servers
spec:
selector:
matchLabels:
app: web-servers
template:
metadata:
labels:
app: web-servers
spec:
containers:
- name: nginx
image: nginx:1.27
````

View File

@@ -0,0 +1,48 @@
# ⏳ Kubernetes Jobs
A **Job** in Kubernetes runs a pod to completion. It ensures that a specified number of pods successfully terminate.
Use Jobs for **batch processing**, **one-off tasks**, or **short-lived workloads**.
---
## 🔍 Job Commands
### 📄 List Jobs in a Namespace
```bash
kubectl get jobs.batch -n <namespace>
````
### ❌ Delete a Job
```bash
kubectl delete jobs.batch -n <namespace> <job-name>
```
---
## 🧾 Example Job Manifest
Heres a minimal example of a Job that runs a simple `echo` command:
```yaml
apiVersion: batch/v1
kind: Job
metadata:
name: myjob
namespace: ns
spec:
template:
spec:
containers:
- name: job1
image: alpine
command:
- echo
- "hello world"
restartPolicy: Never
```
> 💡 **Note:** Always set `restartPolicy` to `Never` or `OnFailure` for jobs.
> 📌 Jobs are useful for tasks like backups, report generation, or database migrations.

View File

@@ -0,0 +1,51 @@
# ⏰ Kubernetes CronJobs
A **CronJob** in Kubernetes allows you to run jobs on a recurring schedule, similar to traditional UNIX `cron` jobs. Ideal for periodic tasks like backups, reports, or scheduled notifications.
---
## 🔍 CronJob Commands
### 📄 List CronJobs in a Namespace
```bash
kubectl get cronjobs.batch -n <namespace>
````
### ❌ Delete a CronJob
```bash
kubectl delete cronjobs.batch -n <namespace> <cronjob-name>
```
---
## 🧾 Example CronJob Manifest
This CronJob runs every minute and prints the date followed by "Kubernetes":
```yaml
apiVersion: batch/v1
kind: CronJob
metadata:
name: cronjob1
namespace: ns
spec:
schedule: "* * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: cronjob
image: debian:bookworm
command:
- /bin/bash
- -c
- date; echo Kubernetes
restartPolicy: Never
```
> 🛠 **Fix:** Changed `JobTemplate` to `jobTemplate` (YAML keys are case-sensitive).
> 🕐 The `schedule` field follows standard cron format: `minute hour day-of-month month day-of-week`.
> 🧠 **Tip:** Always test cron timing carefully to avoid unintentional frequent runs.

View File

@@ -0,0 +1,73 @@
# 🔗 Services in Kubernetes (SVC)
A **Service** in Kubernetes provides a stable networking interface to access a set of pods. It allows for decoupling between client applications and the underlying pods by using DNS names and selectors.
---
## 🌐 Service Basics
### 📌 Service Flow
```
Service ➡️ Endpoint ➡️ Pods
````
- Services abstract access to a group of pods.
- Services automatically get a DNS name in the cluster.
- They use selectors to route traffic to matching pods.
---
## 🧭 Service Types
1. **ClusterIP** (default)
- Accessible only within the cluster.
2. **NodePort**
- Exposes the service on a static port on each node.
3. **LoadBalancer**
- Provisions an external IP via a cloud provider to expose the service.
---
## 🧪 Useful Commands
### 🔍 Get Endpoints
```bash
kubectl get ep -n <namespace>
````
### 📄 Get Services
```bash
kubectl get svc -n <namespace>
```
---
## 🧾 Example Service Manifest
```yaml
apiVersion: v1
kind: Service
metadata:
name: nginx
namespace: ns
labels:
app: web-server
spec:
type: ClusterIP # Options: ClusterIP, NodePort, LoadBalancer
selector:
app: nginx
ports:
- name: http # Port name is optional but useful
port: 80 # Service port
targetPort: 8080 # Container port
```
> 🔍 **Note:** The `selector` must match pod labels for the service to route traffic correctly.
> 🧠 **Tip:** Use `kubectl describe svc <svc-name>` to troubleshoot or verify service-to-pod connectivity.
> 🌐 Services are resolved by DNS using the format: `<service-name>.<namespace>.svc.cluster.local`.

View File

@@ -1,208 +0,0 @@
# Kubernetes YAML Files
This document provides explanations and details for various Kubernetes YAML configurations, describing how different Kubernetes objects such as Namespaces, Pods, and other specifications are defined and utilized. The examples cover creating namespaces, deploying pods, setting resource limits, and using node selectors.
## Namespace Definition
```yaml
apiVersion: v1
kind: Namespace
metadata:
name: my-ns
```
- **apiVersion**: Specifies the version of the Kubernetes API.
- **kind**: Defines the type of Kubernetes object, here it's a `Namespace`.
- **metadata**: Contains data that helps uniquely identify the object, including a `name`.
This YAML file creates a namespace named `my-ns` which isolates a group of resources within Kubernetes.
## Pod Definitions
### Nginx Pod
```yaml
apiVersion: v1
kind: Pod
metadata:
namespace: my-ns
name: nginx-pod
labels:
app: app1
zone: staging
version: v1.0.1
app.kubernetes.io/product: nginx-pod
spec:
containers:
- name: naginx-container
image: nginx:latest
ports:
- containerPort: 80
```
- **metadata.namespace**: Specifies the namespace the pod belongs to (`my-ns`).
- **metadata.name**: The name of the pod (`nginx-pod`).
- **metadata.labels**: Key-value pairs for organizing and selecting resources.
- **spec.containers**: Specifies the containers within the pod. Each container has:
- **name**: Container name.
- **image**: The Docker image to run (`nginx:latest`).
- **ports**: List of ports to expose from the container (`containerPort: 80`).
This file defines a pod named `nginx-pod` running the latest Nginx container in the `my-ns` namespace.
### Test Pod 1
```yaml
apiVersion: v1
kind: Pod
metadata:
namespace: my-ns
name: testpod1
spec:
containers:
- name: c00
image: ubuntu
command: ["/bin/bash", "-c", "while true; do echo Hello-Coder; sleep 5 ; done"]
- name: c01
image: ubuntu
command: ["/bin/bash", "-c", "while true; do echo Hello-Programmer; sleep 5 ; done"]
```
- **spec.containers.command**: Overrides the default command for the container, in this case, running a looped bash script that prints a message every 5 seconds.
This defines a pod named `testpod1` with two Ubuntu containers in the `my-ns` namespace, each running a different command.
## Pod with Resource Requests and Limits
```yaml
apiVersion: v1
kind: Pod
metadata:
namespace: my-ns
name: testpod1
spec:
containers:
- name: c00
image: ubuntu
command:
- /bin/bash
- -c
- while true; do echo Hello-Coder; sleep 5 ; done
- name: c01
image: ubuntu
command:
- /bin/bash
- -c
- while true; do echo Hello-Programmer; sleep 5 ; done
resources:
limits:
memory: "128Mi"
cpu: "500m"
requests:
memory: "64Mi"
cpu: "250m"
```
- **resources.limits**: Specifies the maximum amount of resources a container can use.
- **resources.requests**: Specifies the amount of resources a container is guaranteed.
This pod configuration defines resource limits and requests for the containers to ensure they do not exceed specific memory and CPU usage.
## Pod with NodeSelector
```yaml
apiVersion: v1
kind: Pod
metadata:
namespace: my-ns
name: testpod3
spec:
containers:
- name: c00
image: ubuntu
command:
- /bin/bash
- -c
- while true; do echo Hello-Coder; sleep 5 ; done
- name: c01
image: ubuntu
command:
- /bin/bash
- -c
- while true; do echo Hello-Programmer; sleep 5 ; done
resources:
limits:
memory: "128Mi"
cpu: "500m"
requests:
memory: "64Mi"
cpu: "250m"
nodeSelector:
kubernetes.io/hostname: k8s2
kubernetes.io/disk: ssd
```
- **nodeSelector**: Ensures the pod is scheduled on nodes with the specified labels (`kubernetes.io/hostname: k8s2` and `kubernetes.io/disk: ssd`).
This configuration places the pod on specific nodes that match the given labels.
## Simple Pod Templates
### Basic Pod
```yaml
apiVersion: v1
kind: Pod
metadata:
name: myapp
labels:
name: myapp
spec:
containers:
- name: myapp
image: <Image>
resources:
limits:
memory: "128Mi"
cpu: "500m"
ports:
- containerPort: <Port>
```
This is a template for a basic pod named `myapp` with configurable image and port settings.
### Nginx Pod
```yaml
apiVersion: v1
kind: Pod
metadata:
name: my-pod
labels:
app: MyApp
spec:
containers:
- name: my-container
image: nginx:latest
ports:
- containerPort: 80
```
This defines a pod named `my-pod` running an Nginx container exposing port 80.
## Useful Kubernetes Commands
### View Pod Details
```bash
kubectl get pod -n my-ns <pod-name> -o yaml
```
This command retrieves and displays the YAML configuration of the pod `testpod1` in the namespace `my-ns`.
### Label a Node
```bash
kubectl label node <node-name> kubernetes.io/<var-name>=<var-value>
kubectl get nodes --show-labels
```

View File

@@ -1,23 +0,0 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-deployment
namespace: ns-test
labels:
name: deployment-test
app: nginx
spec:
replicas: 2
selector:
matchLabels:
name: app1
app: nginx
template:
metadata:
labels:
name: app1
app: nginx
spec:
containers:
- name: nginx-deployment
image: nginx:1.26

View File

@@ -0,0 +1,52 @@
apiVersion: v1
kind: Namespace
metadata:
name: ns
---
apiVersion: v1
kind: Service
metadata:
name: nginx-service
namespace: ns
labels:
app: nginx
spec:
type: ClusterIP
selector:
app: nginx
ports:
- name: http
port: 80
targetPort: 8080
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
namespace: ns
labels:
app: nginx
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 8080
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "250m"
memory: "256Mi"