Merge branch 'main' into dev

This commit is contained in:
2025-11-26 10:26:42 +03:30
153 changed files with 10356 additions and 1880 deletions

View File

@@ -1,172 +0,0 @@
# کد نویسی برای بات تلگرام
ربات **تلگرام** (**telegram** bot) یک نوع حساب کاربری ویژه در **تلگرام** است که به صورت اتوماتیک پیام ها را ارسال و دریافت می نماید . کاربران از طریق ارسال دستورات گوناگون با ربات ها در ارتباط هستند و امکان مدیریت ربات ها از طریق API **تلگرام** و درخواست های HTTPS وجود دارد . عبارت bot برای ربات ها نمایش داده می شود.
## ساخت بات با BotFather
اولین مرحله برای کد نویسی بات تلگرام ساختن بات است. از طریق [BotFather](https://telegram.me/BotFather) بات را خواهیم ساخت. پیام `start/` را در BotFather وارد کنید سپس روی **newbot - create a new bot/** کلیک کنید. بعد از مشاهده پیام **Alright, a new bot. How are we going to call it? Please choose a name for your bot.** یک اسم برای بات خود وارد کنید.
سپس بعد از مشاهده پیام **Good. Now let's choose a username for your bot. It must end in bot. Like this, for example: TetrisBot or tetris_bot.** یک نام **خاص و Unique انگلیسی** که حتما در آخرش کلمه **bot** را دارد وارد کنید.
زمانی که بات شما ساخته شد توکن بات را که زیر **Use this token to access the HTTP API** قرار دارد را کپی کنید و در محل امنی قرار دهید.
## آماده سازی محیط کد نویسی
به طور کلی از دو روش می توان برای بات های تلگرام برنامه نویسی کرد.
**روش اول: استفاده از Rest API رسمی تلگرام که نحوه استفاده از در سایت core.telegram.org/bots/api قابل دسترس است**
**روش دوم: استفاده از پکیج هایی که کد های پایه بات را برای زبان برنامه نویسی مورد نظر شما ساخته اند**
برخی از این پکیج های عبارت اند از:
برای سی شارپ ([Telegram.Bot](https://www.nuget.org/packages/Telegram.Bot))
این پکیج از طریق کامند زیر در **Dotnet CLI** نصب می شود
dotnet add package Telegram.Bot --version 19.0.0
برای پایتون ( [python-telegram-bot](https://pypi.org/project/python-telegram-bot/2.4/))
این پکیج نیز از طریق کامند زیر قابل نصب است
pip install python-telegram-bot==2.4
برای اینکه این آموزش بر Core و Universal بودن تاکید دارد ما از از طریق روش اول برای بات خود کد نویسی هر چند این روش کمی سخت تر است اما اگر به خوبی این روش را یادبگرید خود می توانید کتابخانه مانند دو نمونه بالا بنوسید
## کد نویسی برای بات
پروژه ای با زبان مورد نظر خود ایجاد کنید و کتابخانه هایی مورد نیاز برای **Rest API** را روی پروژه نصب یا Import کنید.
برای مثال اگر از زبان برنامه نویسی سی شارپ استفاده می کنید باید **RestSharp** را نصب کنید و نحوه کار با آن را بلد باشید و اگر از پایتون استفاده می کنید باید کتابخانه **Request** را نصب و Import کنید.
**قبل از شروع به این نکات درباره API تلگرام توجه کنید.**
+ تلگرام به حروف بزرگ و کوچک در API حساس است
+ تلگرام فقط از **POST** و **GET** پشتیبانی می کند
+ همه درخواست ها باید کاملا با **UTF-8** باشند
+ تلگرام از هر 4 روش رایج ارسال درخواست **(application/json, multipart/form-data ,QueryString, application/x-www-form-urlencoded)** پشتیبانی می کند
**پیشنهاد:** من به شما پیشنهاد می کنم از QueryString یا application/json استفاده کنید.
### روش QueryString چیست؟
در این روش پارامتر های تابع که می خواهیم اجرا کنیم به عنوان QueryString در Url گذاشته می شوند مانند:
https://test.ir/APIFunction?param1=inp1&param2=inp2
همانطور که در مثال بالا آشکار است هر چه بعد از **?** قرا ر می گیرد **Query String** است.
پارامتر 1 یا **param1** اسم متغیر اول ماست و **inp1** ورودی متغیر **param1** است.
سپس پارامتر های ورودی با علامت **&** جدا شده اند. و پارمتر دوم یا **param2** و ورود آن قرار گرفته است.
### روش application/json
در این روش Url فقط به آدرس تابع اشاره دارد نه به ورود های آن مانند:
https://test.ir/APIFunction
در این روش پارامتر ها به عنوان Json در بدنه ارسال می شوند. مانند زیر
{
"Body":{
"param1":"inp1",
"param2":"inp2",
},
البته ارسال بدنه با توجه به کتابخانه که برای API استفاده می کنید. متفاوت مثلا برای **RestSharp** از Request.AddBody باید استفاده کنید.
## استاندارد های استفاده از API تلگرام
**آدرس پایه API:**
https://api.telegram.org/bot<token>/<FuncName>
**توکن:** به جای **<token>** توکنی را که از بات فادر گرفتید قرار دهید
**نام تابع:** تابعی که می خواهید فراخوانی کنید را به جای **<Funcname>** قرار دهید
**موفق بودن یا نا موفق بودن درخواست**
اگر درخواست شما **موفقیت آمیز** باشد با **OK:True** مواجه می شوید و جواب درخواست را به عنوان **Result** به شما برگردانده می شود
**مثال:**
{
"ok":true,
"result":[]
}
اگر درخواست شما **ناموفق** باشد. **OK: False** می شود و شما پارامتر به عنوان **Result** نخواهید داشت همچنین **error_code** و **description** را به ترتیب برای شماره خطا و توصیف خطا دریافت خواهید کرد.
**مثال: **
{
"ok":false,
"error_code":404,
"description":"Not Found"
}
**بروزرسانی بات:**
هر بار که پیامی برای بات ارسال می شود را می توان با **getUpdate** بدست آورد. برای بدست آوردن لیست آپدیت می توانید Url زیر را GET کنید
https://api.telegram.org/bot<token>/getUpdates
این درخواست لیستی از Update ها بر می گرداند.
برای مشاهده شئ Update به https://core.telegram.org/bots/api#update مراجعه کنید
**دریافت اطلاعات کلی بات:**
برای دریافت اطلاعات کلی از آدرس زیر استفاده کنید
https://api.telegram.org/bot<token>/getMe
**جواب:**
{
"ok": true,
"result": {
"id": 6775339167,
"is_bot": true,
"first_name": "ForDocumentPack",
"username": "ForDocumentPackBot",
"can_join_groups": true,
"can_read_all_group_messages": false,
"supports_inline_queries": false
}
}
## ساخت پروژه ساده
می خواهیم یک پروژه کد نویسی کنیم که زمانی که بات روشن می شود یک پیام خوش آمد گویی ارسال کند.
برای این کار از طریق تابع **getUpdates** پیام هایی که بات داده شده است را مشاهده می کنیم مانند زیر:
{
"ok": true,
"result": [
{
"update_id": 529754041,
"message": {
"message_id": 1,
"from": {
"id": 407692495,
"is_bot": false,
"first_name": "Mahdiyar",
"last_name": "Abdollahi",
"username": "Mdr_abdollahi",
"language_code": "en"
},
"chat": {
"id": 407692495,
"first_name": "Mahdiyar",
"last_name": "Abdollahi",
"username": "Mdr_abdollahi",
"type": "private"
},
"date": 1697995311,
"text": "/start",
"entities": [
{
"offset": 0,
"length": 6,
"type": "bot_command"
}
]
}
}
]
}
**نکته: get_updates را در حلقه بی نهایت بی اندازید تا همیشه بروزرسانی شود**
**نکته: بررسی کنید تا به کسانی که به آنها پاسخ داده اید دوباره پاسخ ندهید.**
**نکته: اگر به جای getUpdates از** [WebHooks](https://core.telegram.org/bots/api#getting-updates) **استفاده کنید نیاز به بررسی پاسخ های تکراری نیست**
برای ارسال پیام نیاز به **chat_id** داریم.
result => message => chat => id
بعد از دریافت **chat_id** می توانیم با تابع **sendMessage** پیام برای کاربر ارسال کنید.
https://api.telegram.org/bot<token>/sendMessage
**نکته: حتما باید پارامتر chat_id و text ارسال شود**
**نکته: حتما باید بصورت POST ارسال شود و پارامتر ها به صورت application/json باشد**
شما می توانید تمامی تابع های API تلگرام را از سایت تلگرام مشاهده کنید -> https://core.telegram.org/bots/api

View File

@@ -1,41 +0,0 @@
# آموزش اجرای سرور بات تلگرام
در این سند قصد داریم که سرور بات تلگرام را به صورت لوکال بالا بیاوریم. توجه داشته باشید که شما می توانید از سرور های پیشفرض تلگرام به آدرس **api.telegram.org** استفاده کنید اما اگر قصد دارید که از قابلیت های ویژه مانند اتصال webhook لوکال استفاده نیاز به این سند دارید.
[کاربرد های سرور لوکال تلگرام](https://github.com/tdlib/telegram-bot-api#usage)
**این آموزش فقط برای سیستم های بر پایه Ubuntu 22.04 تست شده است**
## مرحله اول: نصب وابستگی ها
یک سری نرم افزار ها و پکیج ها را باید قبل از اجرای سرور نصب کرد
**اوپن اس اس ال - Open SSL**
sudo apt-get install libssl-dev
**کامپایلر سی پلاس پلاس نسخه 14 ما از g++ 14 استفاده خواهیم کرد**
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt update
sudo apt install g++
**زی لیب - zlib**
sudo apt install zlib1g
**جی پرف - gperf**
sudo apt install gperf
**سی میک - cmake**
sudo apt install cmake
## مرحله دوم: نصب
برای نصب دستورات زیر را در ترمینال وارد کنید
git clone --recursive https://github.com/tdlib/telegram-bot-api.git
cd telegram-bot-api
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
cmake --build . --target install
```

View File

@@ -1,53 +0,0 @@
# استفاده از Web Hooks در گرفتن پیام های بات تلگرام
**توجه: پیش نیاز این سند Getting Started.MD است**
دو روش برای دریافت پیام ارسالی به بات در تلگرام وجود دارد. **Get Updates Function** و **Web Hooks** روش **Get Updates Function** را در سند قبلی استفاده و بررسی کردیم. برای درک Web Hook باید اول Get Updates را خوب متوجه شویم
## روش اول: Get Updates
در این روش که در سندی قبل از آن استفاده کردیم. شما به تلگرام مراجعه می کنید و تلگرام همه پیام هایی تاریخ بات را برای شما می فرستد در این روش چند چالش وجود دارد
+ **در هر درخواست تمامی پیام ها ارسال می شود این به معنی است که در یک بات با مخاطبان متوسط هر درخواست شامل صد ها هزار پیام است که قبلا به آن پاسخ داده اید و به آن ها دیگر نیازی ندارید**
+ **باید بررسی کنید که به کدام پیام پاسخ داده شده و به کدام پاسخ نداده شده است**
+ **باید از حلقه بی نهایت استفاده کنید تا همیشه از تلگرام درخواست کند. پیاده سازی حلقه بی نهاییت در بسیاری از نرم افزار ها مانند وب سایت بسیار چالش بر انگیز یا غیر ممکن است.**
راه کار بهتر روش Web Hooks است.
## روش دوم: Web Hooks
در این روش به جای اینکه مانند روش **Get Updates** شما به تلگرام مراجعه کنید. تلگرام به شما مراجعه می کند. **پیام های جدید را که قبلا دریافت نکرده اید** به شما می دهد. این روش هر سه مشکل **Get Updates** را بر طرف می کند. البته این روش نیز بی نقص نیست و چالش به همراه دارد. مانند:
+ **چون تلگرام باید برای شما چیزی ارسال کند نمی توان از این روش در فضای Local استفاده کرد**
+ **محدودیت توسط تلگرام برای این روش اعمال شده است که ممکن است رفع این محدودیت ها هزینه بر یا وقت گیر باشد**
### محدودیت های Web Hooks
+ **اگر از وب هوکس استفاده کنید دیگر نمی توانید از getUpdates استفاده کنید**
+ **فقط پورت های 443, 80, 88, 8443 برای اینکار قابل استفاده اند**
+ **فقط تلگرام به سایت هایی که دارای SSL هستند. پیام ها را ارسال می کند**
## تنظیم از Web Hooks
برای تنظیم وب هوک از طریق تابع **setWebhook** آدرسی که می خواهیم به آن پیام ها ارسال شود را به عنوان **Url** ارسال می کنیم
https://api.telegram.org/bot<token>/setWebhook
**نکنه: حتما از متد POST استفاده کنید و Url را با روش application/json بفرستید**
برای مشاهده پارامتر های اختیاری Web Hooks به لینک زیر مراجعه کنید
[https://core.telegram.org/bots/api#setwebhook](Web%20Hooks)
## پاک کردن Web Hooks
اگر به هر دلیلی خواستید وب هوک را پاک کنید یا از get Updates استفاده کنید با استفاده از تابع زیر وب هوکس پاک شده و Get Updates دوباره فعال می شود
https://api.telegram.org/bot<token>/deleteWebhook
## مشاهده وضعیت Web Hooks
با تابع زیر می توان وضعیت وب هوک، سرعت پاسخ دهی، آخرین خطا ها، آخرین هشدار ها و... را مشاهده کرد
https://api.telegram.org/bot<token>/getwebhookinfo
[برای مشاهده اطلاعات دریافتی از این تابع کلیک کنید](https://core.telegram.org/bots/api#webhookinfo)

View File

@@ -0,0 +1,28 @@
from fastapi import FastAPI
from pydantic import BaseModel
import redis
# Connect to Redis
r = redis.Redis(host="192.168.6.160", port=30553, db=0, decode_responses=True)
app = FastAPI()
# For sending JSON data
class Item(BaseModel):
key: str
value: str | None = None # make value optional
@app.get("/")
def home():
return {"message": "Redis API is working!"}
# Set key/value using JSON body
@app.post("/set")
def set_json(item: Item):
r.set(item.key, item.value)
return {"message": f"Saved {item.key} = {item.value}"}
@app.post("/get")
def get_json(item: Item):
value = r.get(item.key)
return {"Key": f"{value}"}

View File

@@ -0,0 +1,26 @@
from fastapi import FastAPI
import redis
# connect to redis (make sure redis is running locally)
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
app = FastAPI()
@app.get("/")
def home():
return {"message": "Redis API is working!"}
# Set a key/value
@app.post("/set/{key}/{value}")
def set_key(key: str, value: str):
r.set(key, value)
return {"message": f"Key '{key}' set with value '{value}'"}
# Get a key/value
@app.get("/get/{key}")
def get_key(key: str):
value = r.get(key)
if value:
return {"key": key, "value": value}
else:
return {"error": f"Key '{key}' not found"}

View File

@@ -0,0 +1,22 @@
import redis
method=int(input("Enter Method: (1.Read/2.Write): "))
r = redis.Redis(host="ip", port=6379,db=0)
if (method == 1):
key=str(input("enter key name: "))
value=r.get(key)
if value == None:
print("Undefined Key")
exit
else:
print(value.decode('utf-8'))
elif (method == 2):
key=str(input("enter key name: "))
value=str(input("enter value: "))
r.set(key,value)
else:
print("Incorrect Input")
exit

View File

@@ -0,0 +1,172 @@
# Python + Redis Quick Guide
This document explains how to set up Python, connect to Redis, and perform basic cache operations.
---
## 1. Setup
Install Python and create a virtual environment:
```bash
sudo apt install python3-full
python3 -m venv .venv
source .venv/bin/activate
```
---
## 2. Connect and Test Redis Connection
```python
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
print(r.ping()) # Should print True
```
**Expected Output:**
```
True
```
---
## 3. Caching Scenario Example
This example demonstrates caching data in Redis with a TTL (Time To Live).
```python
import redis
import time
r = redis.Redis(host='localhost', port=6379, db=0)
def get_data_from_db():
print("Fetching from DB...")
time.sleep(2) # Simulate slow query
return {"user": "alice", "age": 30}
def get_user(user_id):
cache_key = f"user:{user_id}"
# Check cache first
cached = r.get(cache_key)
if cached:
print("Cache hit")
return eval(cached)
# Fetch from DB
data = get_data_from_db()
# Store in Redis with TTL (10 seconds)
r.set(cache_key, str(data), ex=10)
return data
print(get_user(1))
print(get_user(1)) # Should hit cache
```
---
## 4. Connect, Set, and Get Example
```python
import redis
r = redis.Redis(host="192.168.6.160", port=6379, db=0)
r.set('name', 'radin')
name = r.get('name')
print(name)
print(name.decode("utf-8"))
```
---
## 5. Interactive Read/Write Example
```python
import redis
method = int(input("Enter Method: (1.Read/2.Write) "))
r = redis.Redis(host="192.168.6.160", port=6379, db=0)
if method == 1:
key = str(input("Enter key name: "))
value = r.get(key)
if value is None:
print("Undefined Key")
else:
print(value)
elif method == 2:
key = str(input("Enter key name: "))
value = str(input("Enter value: "))
r.set(key, value)
else:
print("Incorrect Input")
```
---
## 6. Professional Version (Improved Code)
```python
import redis
import sys
def connect_redis(host="192.168.6.160", port=6379, db=0):
"""Establish a connection to Redis."""
try:
client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
# Test connection
client.ping()
return client
except redis.ConnectionError as e:
print(f"Error connecting to Redis: {e}")
sys.exit(1)
def read_key(client):
"""Read a key from Redis."""
key = input("Enter key name: ").strip()
value = client.get(key)
if value is None:
print("Undefined Key")
else:
print(f"Value: {value}")
def write_key(client):
"""Write a key-value pair to Redis."""
key = input("Enter key name: ").strip()
value = input("Enter value: ").strip()
client.set(key, value)
print(f"Successfully set key '{key}' with value '{value}'.")
def main():
client = connect_redis()
print("Select Method:")
print("1. Read")
print("2. Write")
try:
method = int(input("Enter method (1 or 2): ").strip())
except ValueError:
print("Invalid input. Please enter 1 or 2.")
sys.exit(1)
if method == 1:
read_key(client)
elif method == 2:
write_key(client)
else:
print("Incorrect input. Please enter 1 or 2.")
sys.exit(1)
if __name__ == "__main__":
main()
```

View File

@@ -0,0 +1,25 @@
job1:
stage: hello_stage
script: echo "Hi :)"
job2:
stage: hello_stage
script: echo "Hello :)"
job3:
stage: hello_stage
script: echo "How Are You :)"
needs:
- job2
Build_job1:
stage: build_stage
script: echo "Building Code"
needs:
- job3
tags:
- build_runner
stages:
- hello_stage
- build_stage

View File

@@ -0,0 +1,189 @@
# GitLab CI/CD Cache Guide
GitLab CI/CD provides a caching mechanism to speed up pipeline execution by reusing dependencies and build artifacts such as `node_modules`, Ruby gems, or compiled binaries. This guide covers how to configure, optimize, and manage caching effectively.
---
## Key Features of GitLab Cache
* **Cache Storage**: Cache data is stored in the GitLab Runner and can optionally be persisted in external storage such as S3, MinIO, Google Cloud Storage (GCS), or Azure Blob Storage.
* **Branch-Specific Caching**: Create independent caches per branch, job, or pipeline stage to avoid conflicts.
* **Fallbacks**: Jobs can retrieve cache from other branches if the current branch has no cache yet.
* **Simple & Efficient**: Uses file locks and directory caching to maximize efficiency without complex configurations.
---
## Basic Cache Example
A typical caching configuration for Ruby gems and Yarn modules:
```yaml
test-job:
stage: build
cache:
- key:
files:
- Gemfile.lock
paths:
- vendor/ruby
- key:
files:
- yarn.lock
paths:
- .yarn-cache/
script:
- bundle config set --local path 'vendor/ruby'
- bundle install
- yarn install --cache-folder .yarn-cache
- echo "Run tests..."
```
**Behavior**:
If the lock file (`Gemfile.lock` or `yarn.lock`) changes, the cache is updated automatically, ensuring dependencies remain consistent with the project.
---
## Configuring GitLab Runner to Use S3 Cache
You can configure the GitLab Runner to save cache to S3 storage as follows:
```toml
[[runners]]
[runners.cache]
Type = "s3"
[runners.cache.s3]
ServerAddress = "s3.example.com"
AccessKey = "access-key"
SecretKey = "secret-key"
BucketName = "runner"
Insecure = true # true = http, false = https
[runners.cache.gcs]
[runners.cache.azure]
[runners.docker]
```
---
## Branch-Specific Cache with Fallbacks
When a new branch does not yet have a cache, it can use fallback caches from other branches:
```yaml
test-job:
stage: build
cache:
- key: cache-$CI_COMMIT_REF_SLUG
fallback_keys:
- cache-$CI_DEFAULT_BRANCH
- cache-default
paths:
- vendor/ruby
script:
- bundle config set --local path 'vendor/ruby'
- bundle install
- echo "Run tests..."
```
---
## Default Cache Configuration
Define a global cache and override it per job as necessary:
```yaml
default:
cache: &global_cache
key: $CI_COMMIT_REF_SLUG
paths:
- node_modules/
- public/
- vendor/
policy: pull-push
job:
cache:
<<: *global_cache
policy: pull # Overrides global policy for this job
```
---
## Cache Policies
| Policy | Description |
| --------- | ------------------------------------------------- |
| pull | Fetches cache without updating it |
| pull-push | Fetches cache and updates it after job completion |
---
## Cache Examples
**Per Job & Branch**:
```yaml
cache:
key: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"
```
**Per Stage & Branch**:
```yaml
cache:
key: "$CI_JOB_STAGE-$CI_COMMIT_REF_SLUG"
```
---
## Conditional Cache Policy
Update cache only on the default branch while other branches only fetch:
```yaml
conditional-policy:
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
variables:
POLICY: pull-push
- if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
variables:
POLICY: pull
stage: build
cache:
key: gems
policy: $POLICY
paths:
- vendor/bundle
script:
- echo "This job pulls and pushes the cache depending on the branch"
- echo "Downloading dependencies..."
```
---
## Cache Based on Lock Files
Automatically update cache when lock files change, e.g., `package-lock.json`:
```yaml
default:
cache:
key:
files:
- package-lock.json
paths:
- .npm/
```
**Tip**: Using lock files ensures that cached dependencies are always consistent with the projects declared versions.
---
## Best Practices Summary
* Use **branch-specific keys** for independent caches to avoid conflicts.
* Use **fallback_keys** to share caches across branches.
* Use **cache policies** to control whether cache is updated or only fetched.
* Leverage **lock files** to trigger cache updates automatically.
Proper caching can dramatically reduce build times, improve pipeline efficiency, and ensure consistent builds across branches and environments.

View File

@@ -1,148 +0,0 @@
## What is a Dockerfile?
A **Dockerfile** is a simple text file containing instructions to create a Docker image. Docker images provide a consistent and reproducible environment for running applications in containers. By defining dependencies, configurations, and the operating system, Dockerfiles automate the image creation process, ensuring version-controlled and portable environments.
### Key Concepts:
- **Base Image**: The foundational layer of your image, typically an official operating system like Ubuntu, CentOS, or Alpine Linux.
- **Instructions**: Commands such as `RUN`, `COPY`, and `CMD` define whats installed, how the image behaves, and which files to include.
Common instructions include:
- **`RUN`**: Executes commands (e.g., installing software) inside the container.
- **`COPY`**: Copies files from your local machine to the image.
- **`CMD`**: Specifies the default command to run when the container starts.
---
## Step-by-Step Guide to Creating a Dockerfile
### 1. Create a File Named `Dockerfile`
Start by creating a file called `Dockerfile` in your project directory. If you name it something else, you'll need to specify the file name during the build process.
#### Example Dockerfile:
```dockerfile
# Use Ubuntu 22.04 as the base image
FROM ubuntu:22.04
# Add metadata such as version information
LABEL version="0.0.1"
# Update package lists and install essential tools
RUN apt update && apt install -y bash vim curl
# Install Nginx web server
RUN apt install -y nginx
```
#### Breakdown of Instructions:
- **`FROM ubuntu:22.04`**: Defines Ubuntu 22.04 as the base image.
- **`LABEL version="0.0.1"`**: Adds metadata, such as the version label.
- **`RUN`**: Runs commands inside the container. In this case, it updates package lists and installs `bash`, `vim`, `curl`, and `nginx`.
---
### 2. Example Using Alpine Linux
Alpine Linux is a lightweight option that results in smaller images. Here's an example of a Dockerfile using Alpine:
```dockerfile
# Use Alpine as the base image
FROM alpine
# Add version metadata
LABEL version="0.0.1"
# Update package lists and install essential tools
RUN apk update && apk add bash vim curl
```
This example is perfect for when you need a compact, minimalistic image.
---
### 3. Complex Dockerfile with a Script
In this example, you'll learn how to copy a script into the container, set a working directory, and make the script executable.
```dockerfile
# Start with Alpine as the base image
FROM alpine
# Add metadata
LABEL version="0.0.1"
# Update package lists and install essential tools
RUN apk update && apk add bash vim curl iputils-ping
# Copy the script into the image
COPY <local-file-path> <container-destination-path>
# Set the working directory for subsequent commands
WORKDIR <container-destination-path>
# Add environment variables
ENV API_KEY="123445"
# Set user and expose ports
USER deploy
EXPOSE 3210
# Give execution permissions to the script
RUN chmod +x app.sh
# Define the default command to run
CMD ["./app.sh"]
# Alternatively, you can use ENTRYPOINT
ENTRYPOINT ["bash", "./app.sh"]
```
#### Key Concepts in This Example:
- **`COPY`**: Copies a file from your local machine to the container.
- **`WORKDIR`**: Sets the working directory inside the container for subsequent commands.
- **`RUN chmod +x app.sh`**: Grants execution permissions to the `app.sh` script.
- **`CMD` vs. `ENTRYPOINT`**: `CMD` provides default behavior, while `ENTRYPOINT` is used when you want to ensure the container always runs a specific executable.
---
### 4. Build Your Docker Image
Once your `Dockerfile` is ready, build the Docker image using the `docker build` command.
```bash
docker build -t <app-name> <path-to-dockerfile>
```
#### Usage Examples:
- To build with a `Dockerfile` in the current directory:
```bash
docker build -t app-test .
```
Here, the `.` indicates the current directory as the build context.
- If your file is named something other than `Dockerfile` (e.g., `CustomDockerfile`):
```bash
docker build -t app-test -f <CustomDockerfile> .
```
- If you want build file without use cache
```bash
docker build -t app-test:v1 -f <Custom-Dir> . --no-cache
```
#### Explanation:
- **`docker build`**: Builds a Docker image.
- **`-t <app-name>`**: Tags the image with a name (e.g., `app-test`).
- **`<path-to-dockerfile>`**: Specifies the location of the `Dockerfile`. Use `.` for the current directory or provide an absolute path.
---
## Summary
A **Dockerfile** is a powerful tool for automating the creation of Docker images. Heres a quick recap:
1. **Create a Dockerfile**: Use instructions like `FROM`, `RUN`, `COPY`, and `CMD` to define the image.
2. **Build the Image**: Run the `docker build` command to turn your Dockerfile into a Docker image.
3. **Run the Container**: Once the image is built, use `docker run` to create and run a container based on it.

View File

@@ -1,192 +0,0 @@
# Docker Swarm Documentation
This guide covers key commands and workflows for managing a Docker Swarm cluster. It includes information on initializing the cluster, node management, service management, and best practices to ensure your cluster remains operational.
---
## Table of Contents
1. [Cluster Health & Manager Count](#cluster-health--manager-count)
2. [Example Workflow: Setting Up Nginx](#example-workflow-setting-up-nginx)
3. [Cluster Initialization and Management](#cluster-initialization-and-management)
4. [Node Management](#node-management)
5. [Service Management](#service-management)
6. [Join Tokens](#join-tokens)
---
## Cluster Health & Manager Count
To maintain a healthy and functional Docker Swarm cluster, **the number of manager nodes must exceed 50% of the total nodes**. If the manager nodes fall below 51% of the cluster, the system will lose quorum and become non-operational. Always monitor your manager count to ensure high availability.
---
## Example Workflow: Setting Up Nginx
When deploying services such as Nginx, the typical workflow in Docker Swarm is:
1. **API**: Handle incoming requests.
2. **Allocator**: Distribute workload to available nodes.
3. **Dispatcher**: Manage task assignments.
4. **Scheduler**: Ensure tasks run on the optimal nodes.
This workflow ensures that your service is efficiently distributed and scaled across the cluster.
---
## Cluster Initialization and Management
### Create Cluster
Initialize a new Docker Swarm cluster:
```bash
docker swarm init
```
This command sets up the current node as the manager of a new cluster.
### Create Cluster with a Specific Interface
Specify an IP address or interface name when initializing the cluster:
```bash
docker swarm init --advertise-addr <ip or interface name>
```
This ensures that the node advertises the correct network interface for other nodes to join.
### Join Cluster
Add a node to an existing Docker Swarm cluster:
```bash
docker swarm join
```
### Leave Cluster
Remove a node from the cluster:
```bash
docker swarm leave
```
### Unlock Locked Manager
Unlock a manager node that has been locked:
```bash
docker swarm unlock
```
---
## Node Management
### List Nodes
View the status and details of all nodes in your cluster:
```bash
docker node ls
```
**Example Output:**
```
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
8yw8jrjeqczaci0qkuy060g09 * docker-1 Ready Active Leader 24.0.5
v4gvf7xenw0izmxgvhr6hb2rj docker-2 Ready Active 24.0.5
kd3ujmt1ey3pw6v9189fouxfa docker-3 Ready Active Reachable 24.0.5
tm1msy58ztcltt36rs1lb76p7 docker-4 Down Active 24.0.5
```
### Remove Node
Remove a node from the cluster by specifying its ID:
```bash
docker node rm <node-id>
```
**Example:**
```bash
docker node rm tm1msy58ztcltt36rs1lb76p7
```
### Promote Node to Manager
Upgrade a worker node to a manager node:
```bash
docker node promote <hostname or ID>
```
**Example:**
```bash
docker node promote v4gvf7xenw0izmxgvhr6hb2rj
```
This command promotes the specified node, enabling it to participate in cluster management decisions.
---
## Service Management
### Show Task Status on Cluster
Display the status of tasks running on each node:
```bash
docker node ps
```
### List Services
List all services currently running in the cluster:
```bash
docker service ls
```
### Create Service
Create a new service with the specified name and Docker image:
```bash
docker service create --name <service-name> <image-name>
```
### Scale Service
Adjust the number of replicas for an existing service:
```bash
docker service scale <service-name>=<replica-count>
```
**Example:**
```bash
docker service scale nginx=5
```
This command scales the `nginx` service to 5 replicas.
### Inspect Service
View detailed information about a specific service:
```bash
docker service inspect <service-name>
```
### Create Service with Replicas and Environment Variables
Launch a new service with multiple replicas, environment variables, and port publishing:
```bash
docker service create --name <service-name> --replicas <replica-count> --env <env-variable> --publish <host-port>:<container-port> <image-name>
```
**Example:**
```bash
docker service create --name nginx --replicas 3 --env MY_ENV_VAR=value --publish 8080:80 nginx
```
This creates an `nginx` service with 3 replicas, sets the environment variable `MY_ENV_VAR` to `value`, and maps port 8080 on the host to port 80 in the container.
---
## Join Tokens
To securely add new nodes to the swarm, use the join tokens provided by Docker Swarm.
### Get Worker Join Token
Display the token required for a node to join as a worker:
```bash
docker swarm join-token worker
```
### Get Manager Join Token
Display the token required for a node to join as a manager:
```bash
docker swarm join-token manager
```

View File

@@ -1,65 +0,0 @@
# Kubernetes (K8s) Documentation
## Overview
**Kubernetes (K8s)** is an open-source container orchestration platform designed to automate the deployment, scaling, and operation of containerized applications.
---
## Control Plane (CP)
The **Control Plane** is the core management component of a Kubernetes cluster. It makes global decisions about the cluster (e.g., scheduling), and it maintains the desired state of the cluster by managing workloads and directing communication within the system.
> **Note:** By default, the Control Plane does not directly manage or run application containers.
### Key Components of the Control Plane:
- **API Server (`kube-apiserver`)**:
Exposes the Kubernetes API and serves as the entry point to the cluster. It handles communication between internal components and external clients.
- **Scheduler (`kube-scheduler`)**:
Assigns work (e.g., pods) to nodes based on resource availability and policies.
- **Controller Manager (`kube-controller-manager`)**:
Runs controllers that regulate the state of the cluster (e.g., Node Controller, Replication Controller, etc.).
- **etcd**:
A consistent, highly-available key-value store that stores all cluster data, configurations, and states. This is the "database" of Kubernetes.
---
## Worker Nodes
Worker nodes are the machines where containerized applications run. Each worker node contains essential components for managing containers.
### Key Components of a Worker Node:
- **Kubelet**:
An agent that ensures containers are running as specified in their Pod definitions. It communicates with the Control Plane to receive and execute tasks.
- **Kube Proxy**:
Maintains network rules and handles routing for communication between services within the cluster and with external traffic.
---
## Data Flow
- **Kubelet** and **Kube Proxy** on each worker node communicate with the **API Server** in the Control Plane for task execution and resource updates.
- The **Scheduler** assigns pods to nodes based on resource requirements, while the **Controller Manager** ensures that the cluster state remains consistent.
---
## Administration Tools
- **`kubeadm`**:
A tool for bootstrapping Kubernetes clusters. It simplifies the setup and configuration of the Control Plane and worker nodes.
- **`kubectl`**:
The command-line interface (CLI) for interacting with the Kubernetes API. It is used to manage resources, deploy applications, and inspect cluster components.
---
## Kubernetes Version Compatibility
### Kubernetes and Container Runtimes:
- **Kubernetes ≤ 1.23**:
Compatible with Docker as the default container runtime.
- **Kubernetes 1.24 to 1.25**:
Docker is not supported as a runtime. These versions require `containerd` or another Container Runtime Interface (CRI) implementation.
- **Kubernetes ≥ 1.25**:
Docker can be installed on the server but must be used indirectly through `containerd` or another CRI-compliant runtime. Docker itself is not a supported runtime.

View File

@@ -1,67 +0,0 @@
---
# Containerd and Kubernetes Installation Guide
## 1. Disable Swap
Turn off swap and disable it permanently.
```bash
swapoff -a
sed -i '/swap/d' /etc/fstab
```
## 2. Enable Required Kernel Modules
Create a configuration file to load necessary kernel modules and load them temporarily.
```bash
echo -e "overlay\nbr_netfilter" | sudo tee /etc/modules-load.d/containerd.conf
sudo modprobe overlay
sudo modprobe br_netfilter
```
## 3. Enable IPv4 Forwarding
Enable IPv4 forwarding in the sysctl configuration and apply the changes.
```bash
sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf
sysctl -p
```
## 4. Configure Containerd
Generate the default configuration for Containerd and modify it to use systemd as the cgroup driver.
```bash
containerd config default | sudo tee /etc/containerd/config.toml
sudo sed -i 's/SystemdCgroup = false/SystemdCgroup = true/' /etc/containerd/config.toml
```
## 5. Install Kubernetes
Add the Kubernetes package repository and install the required packages.
```bash
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.30/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
echo 'deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.30/deb/ /' | 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
```
## 6. Enable kubelet
Enable and start the kubelet service.
```bash
sudo systemctl enable --now kubelet
```
## 7. Initialize the Kubernetes Cluster
Initialize the Kubernetes control plane with the specified parameters.
```bash
sudo kubeadm init --control-plane-endpoint 192.168.2.100 --apiserver-advertise-address 192.168.2.100 --pod-network-cidr 10.244.0.0/16 | tee kuber-install.log
```
## 8. Create Control Plane Join Command
Create the control plane join command and save it for later use.
```bash
sudo kubeadm init phase upload-certs --upload-certs
Copy the output certificate key and run the following command, replacing <CERTIFICATE_KEY> with the copied key.
sudo kubeadm token create --certificate-key <CERTIFICATE_KEY> --print-join-command | tee cp-command.txt
```
## 9. Join Control Plane and Worker Nodes
Use the command from cp-command.txt on your control plane nodes to join them. Additionally, get the join command for worker nodes from kuber-install.log and run it on each worker node.
---
This revised guide provides clear, step-by-step instructions, making it easier to follow and ensuring all necessary actions are covered.

View File

@@ -1,243 +0,0 @@
# Kubernetes Command Reference
This document provides a reference for common `kubectl` commands used for managing Kubernetes clusters. Use the examples and explanations below to help manage nodes, namespaces, pods, deployments, and more.
## Table of Contents
- [Kubernetes Command Reference](#kubernetes-command-reference)
- [Table of Contents](#table-of-contents)
- [General Commands](#general-commands)
- [Node Management](#node-management)
- [Namespace Management](#namespace-management)
- [Pod Management](#pod-management)
- [Listing Pods](#listing-pods)
- [Running a Pod](#running-a-pod)
- [Deleting a Pod](#deleting-a-pod)
- [API Resources and Documentation](#api-resources-and-documentation)
- [Logs and Pod Information](#logs-and-pod-information)
- [Applying YAML Files](#applying-yaml-files)
- [Managing Nodes and Labels](#managing-nodes-and-labels)
- [Viewing Cluster Resources](#viewing-cluster-resources)
- [ReplicaSet and Deployment Management](#replicaset-and-deployment-management)
- [Additional Information](#additional-information)
---
## General Commands
- **List API Resources**
```bash
kubectl api-resources
```
---
## Node Management
- **Show all nodes**
```bash
kubectl get node
```
- **Set a label on a node**
```bash
kubectl label nodes <node-name> kubernetes.io/<label-key>=<label-value>
```
---
## Namespace Management
- **List all namespaces**
```bash
kubectl get namespaces
# or the abbreviated version:
kubectl get ns
```
- **Create a custom namespace**
```bash
kubectl create ns <namespace-name>
```
---
## Pod Management
### Listing Pods
- **List pods in the default namespace**
```bash
kubectl get pod
```
- **List pods with detailed information (wide output) in the default namespace**
```bash
kubectl get pod -o wide
```
- **List pods with detailed information in a specific namespace**
```bash
kubectl get pod -o wide -n <namespace-name>
```
### Running a Pod
- **Run a new pod**
Use the following command structure to run a pod with various options:
```bash
kubectl run <pod-name> <switch> {
--image=<image-name>, # Container image to use
--port=<port-number>, # Port that the container exposes
-n <namespace-name>, # Namespace in which to run the pod
--env="KEY=VALUE", # Environment variables for the container
--command, # Treat the following arguments as the command
--replicas=<number>, # Number of pod replicas to create
--labels="key=value,key2=value2", # Labels to assign to the pod(s)
--dry-run=client, # Print the object without creating it
--restart=<Always|OnFailure|Never>, # Pod restart policy
--overrides='<json>', # JSON override for the generated object
--image-pull-policy=<policy>, # Image pull policy (Always, IfNotPresent, Never)
--limits=cpu=<cpu>,memory=<memory>, # Resource limits for the container
--requests=cpu=<cpu>,memory=<memory> # Resource requests for the container
}
```
- **Example:**
```bash
kubectl run mypod --image=nginx --port=80 -n mynamespace \
--env="ENV_VAR_NAME=VALUE" --command -- nginx -g "daemon off;" \
--replicas=3 --labels="app=myapp,env=prod" --dry-run=client \
--restart=Always --overrides='{"spec": {"containers": [{"name": "nginx", "image": "nginx"}]}}' \
--image-pull-policy=IfNotPresent --limits=cpu=100m,memory=256Mi \
--requests=cpu=50m,memory=128Mi
```
### Deleting a Pod
- **Delete a pod in a custom namespace**
```bash
kubectl delete pod -n <namespace-name> <pod-name>
```
---
## API Resources and Documentation
- **Get documentation for an API resource**
```bash
kubectl explain <api-resource-name>
```
- *Example:*
```bash
kubectl explain pod
```
---
## Logs and Pod Information
- **Stream logs for a running pod**
```bash
kubectl logs -f -n <namespace-name> <pod-name>
```
- **Get detailed state and log information for a pod**
```bash
kubectl describe pod -n <namespace-name> <pod-name>
```
---
## Applying YAML Files
- **Apply configuration from a YAML file to a specific namespace**
```bash
kubectl apply -f <yaml-file> -n <namespace-name>
```
---
## Managing Nodes and Labels
- **Label a node with a custom key-value pair**
```bash
kubectl label nodes <node-name> kubernetes.io/<label-key>=<label-value>
```
---
## Viewing Cluster Resources
- **Display all resources loaded in a namespace**
```bash
kubectl get all -n <namespace-name>
```
- **Display replica sets, pods, and deployments in a specific namespace**
```bash
kubectl get rs,pod,deployment -n <namespace-name>
```
---
## ReplicaSet and Deployment Management
- **Scale a ReplicaSet**
```bash
kubectl scale rs <replicaset-name> -n <namespace-name> --replicas=<count>
```
- **View rollout history of a deployment**
```bash
kubectl rollout history deployment -n <namespace-name> <deployment-name>
```
- **View details of a specific revision in a deployment's rollout history**
```bash
kubectl rollout history deployment -n <namespace-name> <deployment-name> --revision <number>
```
- **Roll back a deployment to a specific revision**
```bash
kubectl rollout undo deployment -n <namespace-name> <deployment-name> --to-revision=<number>
```
> **Note:** The command for rolling back to a specific revision is `kubectl rollout undo` rather than using `--to-revision` with `kubectl rollout history`.
---
## Additional Information
- **Static Manifest Files**
All YAML files located under `/etc/kubernetes/manifests/` are automatically loaded after a server reboot.
---

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

@@ -0,0 +1,160 @@
# 🚢 Understanding Dockerfile: A Complete Guide
---
## 📄 What is a Dockerfile?
A **Dockerfile** is a simple text file containing instructions to create a **Docker image**. Docker images provide a consistent, reproducible environment to run applications inside containers. By defining dependencies, configurations, and the operating system, Dockerfiles automate image creation, ensuring version-controlled and portable environments.
---
### 🔑 Key Concepts:
* 🏗️ **Base Image**: The foundational layer of your image, usually an official OS like Ubuntu, CentOS, or Alpine Linux.
* 📝 **Instructions**: Commands that tell Docker what to install, how the image behaves, and which files to include.
Common instructions include:
| Instruction | Description |
| ----------- | ---------------------------------------------------------------- |
| 🏃‍♂️ `RUN` | Executes commands inside the container (e.g., install software). |
| 📁 `COPY` | Copies files from your local machine to the image. |
| ▶️ `CMD` | Specifies the default command when the container starts. |
---
## 🛠️ Step-by-Step Guide to Creating a Dockerfile
---
### 1⃣ Create a File Named `Dockerfile`
Create a file called `Dockerfile` in your project directory. If named differently, specify the filename during build.
#### Example Dockerfile:
```dockerfile
# 🐧 Use Ubuntu 22.04 as the base image
FROM ubuntu:22.04
# 🏷️ Add metadata such as version information
LABEL version="0.0.1"
# 🔄 Update package lists and install essential tools
RUN apt update && apt install -y bash vim curl
# 🌐 Install Nginx web server
RUN apt install -y nginx
```
**Explanation:**
* `FROM ubuntu:22.04` — Use Ubuntu 22.04 as the base image.
* `LABEL version="0.0.1"` — Adds version metadata.
* `RUN` — Executes commands inside the container to install tools and software.
---
### 2⃣ Example Using Alpine Linux
Alpine Linux is lightweight and creates smaller images.
```dockerfile
# 🐧 Use Alpine as the base image
FROM alpine
# 🏷️ Add version metadata
LABEL version="0.0.1"
# 🔄 Update package lists and install essential tools
RUN apk update && apk add bash vim curl
```
Perfect for a compact, minimalistic image.
---
### 3⃣ Complex Dockerfile with a Script
```dockerfile
# 🐧 Start with Alpine as the base image
FROM alpine
# 🏷️ Add metadata
LABEL version="0.0.1"
# 🔄 Update packages and install essential tools
RUN apk update && apk add bash vim curl iputils-ping
# 📂 Copy the script into the image
COPY <local-file-path> <container-destination-path>
# 🏠 Set working directory
WORKDIR <container-destination-path>
# 🌿 Add environment variables
ENV API_KEY="123445"
# 👤 Set user and expose ports
USER deploy
EXPOSE 3210
# ⚙️ Make the script executable
RUN chmod +x app.sh
# ▶️ Default command to run
CMD ["./app.sh"]
# Alternatively, ENTRYPOINT ensures always running the executable
ENTRYPOINT ["bash", "./app.sh"]
```
---
### ❤️ Health Check Setup
```dockerfile
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
CMD curl -f http://localhost/ || exit 1
```
* ⏲️ **interval**: time between checks
***timeout**: fail if check takes longer than 5 seconds
* 🔄 **retries**: mark container unhealthy after failed attempts
* 🛡️ **start-period**: grace period before counting failures
---
### 4⃣ Build Your Docker Image
```bash
docker build -t <app-name> <path-to-dockerfile>
```
**Examples:**
* Build with Dockerfile in current directory:
```bash
docker build -t app-test .
```
* Use custom Dockerfile name:
```bash
docker build -t app-test -f <CustomDockerfile> .
```
* Build without cache:
```bash
docker build -t app-test:v1 -f <Custom-Dir> . --no-cache
```
---
## 📋 Summary
A **Dockerfile** is a powerful tool for automating Docker image creation:
1. 📝 **Create a Dockerfile**: Define the image with `FROM`, `RUN`, `COPY`, and `CMD`.
2. 🏗️ **Build the Image**: Use `docker build` to generate your image.
3. 🚀 **Run the Container**: Use `docker run` to start your container.

View File

@@ -0,0 +1,228 @@
# 📦 Docker Swarm Documentation
Comprehensive guide to managing a **Docker Swarm** cluster. This document includes core commands, workflows, and best practices for maintaining a healthy and operational environment.
---
## 📚 Table of Contents
1. [🔧 Cluster Health & Manager Count](#-cluster-health--manager-count)
2. [🚀 Example Workflow: Setting Up Nginx](#-example-workflow-setting-up-nginx)
3. [⚙️ Cluster Initialization and Management](#-cluster-initialization-and-management)
4. [🖥️ Node Management](#-node-management)
5. [🛠️ Service Management](#-service-management)
6. [🔑 Join Tokens & Node Configuration](#-join-tokens--node-configuration)
---
## 🔧 Cluster Health & Manager Count
A Docker Swarm cluster requires a **majority of manager nodes** to be functional for quorum.
> **Best Practice:** Always maintain **more than 50%** manager nodes online. Losing quorum will render the cluster non-operational.
---
## 🚀 Example Workflow: Setting Up Nginx
Docker Swarm handles service deployment through several internal components:
1. **API** Receives service requests.
2. **Allocator** Determines resource allocation.
3. **Dispatcher** Assigns tasks to nodes.
4. **Scheduler** Places tasks on optimal nodes.
This process ensures resilient and efficient service distribution.
---
## ⚙️ Cluster Initialization and Management
### 🔹 Initialize Cluster
```bash
docker swarm init
```
### 🔹 Initialize with Specific Interface
```bash
docker swarm init --advertise-addr <ip-or-interface>
```
### 🔹 Join Existing Cluster
```bash
docker swarm join
```
### 🔹 Leave Cluster
```bash
docker swarm leave
```
### 🔹 Unlock a Manager Node
```bash
docker swarm unlock
```
---
## 🖥️ Node Management
### 🔸 List Nodes
```bash
docker node ls
```
**Example Output:**
```
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSION
8yw8jrjeqczaci0qkuy060g09 * docker-1 Ready Active Leader 24.0.5
v4gvf7xenw0izmxgvhr6hb2rj docker-2 Ready Active 24.0.5
kd3ujmt1ey3pw6v9189fouxfa docker-3 Ready Active Reachable 24.0.5
tm1msy58ztcltt36rs1lb76p7 docker-4 Down Active 24.0.5
```
### 🔸 Remove a Node
```bash
docker node rm <node-id>
```
### 🔸 Promote to Manager
```bash
docker node promote <hostname-or-id>
```
### 🔸 Inspect a Node
```bash
docker node inspect <nodename>
```
### 🔸 Change Node Role
```bash
docker node update --role manager <nodename>
docker node update --role worker <nodename>
```
### 🔸 Change Node Availability
```bash
docker node update --availability active <nodename>
docker node update --availability pause <nodename>
docker node update --availability drain <nodename>
```
### 🔸 Add or Remove Labels
**Add:**
```bash
docker node update --label-add env=development <nodename>
docker node update --label-add env=testing <nodename>
```
**Remove:**
```bash
docker node update --label-rm env= <nodename>
docker node update --label-rm env <nodename>
```
**Use label constraints in service deployment:**
```yaml
deploy:
placement:
constraints:
- node.labels.env == development
```
---
## 🛠️ Service Management
### 🔹 Show Tasks on a Node
```bash
docker node ps
```
### 🔹 List All Services
```bash
docker service ls
```
### 🔹 Create a New Service
```bash
docker service create --name <service-name> <image-name>
```
### 🔹 Scale a Service
```bash
docker service scale <service-name>=<replica-count>
```
**Example:**
```bash
docker service scale nginx=5
```
### 🔹 Inspect a Service
```bash
docker service inspect <service-name>
```
### 🔹 Create Service with Replicas, Env Vars, and Port Mapping
```bash
docker service create \
--name <service-name> \
--replicas <count> \
--env <ENV_VAR=value> \
--publish <host-port>:<container-port> \
<image-name>
```
**Example:**
```bash
docker service create \
--name nginx \
--replicas 3 \
--env MY_ENV_VAR=value \
--publish 8080:80 \
nginx
```
---
## 🔑 Join Tokens & Node Configuration
Securely add nodes to your Swarm using join tokens.
### 🔹 Get Worker Token
```bash
docker swarm join-token worker
```
### 🔹 Get Manager Token
```bash
docker swarm join-token manager
```

View File

@@ -0,0 +1,74 @@
version: "3.8"
services:
web:
image: nginx:alpine
ports:
- "80:80"
deploy:
# Service mode: use "replicated" for a set number of replicas,
# or "global" to run one instance on every node.
mode: replicated
# Number of container replicas to run (only applicable in replicated mode)
replicas: 3
# Rolling update configuration (applies when updating the service)
update_config:
# Number of containers to update at the same time
parallelism: 2
# Delay between updating groups of containers (e.g., "10s" for 10 seconds)
delay: 10s
# Action to take if an update fails: rollback, pause, or continue
failure_action: rollback
# Time to monitor each updated container before proceeding to the next batch
monitor: 10s
# Maximum failure ratio (0.0 to 1.0) acceptable during the update
max_failure_ratio: 0.3
# Rollback configuration (applies if a deployment needs to be undone)
rollback_config:
parallelism: 1
delay: 10s
# Action to take if rollback fails
failure_action: pause
monitor: 10s
max_failure_ratio: 0.2
# Restart policy for containers in the service
restart_policy:
# Restart condition can be "none", "on-failure", or "any"
condition: on-failure
# Delay between restart attempts
delay: 5s
# Maximum number of restart attempts before considering the container as failed
max_attempts: 3
# Time window used to evaluate restart attempts (e.g., "120s")
window: 120s
# Resource constraints and reservations for containers
resources:
limits:
# Maximum number of CPUs the container can use (as a fraction or whole number)
cpus: "0.50"
# Maximum memory (e.g., "50M" for 50 megabytes)
memory: 50M
reservations:
# Guaranteed minimum CPUs for the container
cpus: "0.25"
# Guaranteed minimum memory
memory: 20M
# Placement constraints and preferences to control which nodes run the service
placement:
# Constraints ensure that only nodes meeting certain conditions are eligible.
constraints:
- node.role == manager
- node.labels.region == us-east
# Preferences allow you to influence (but not enforce) distribution.
preferences:
- spread: node.labels.az
# Custom metadata labels for the service
labels:
com.example.description: "Sample web service using all deploy parameters"

View File

@@ -0,0 +1,87 @@
# 🚢 Kubernetes (K8s) Documentation
## 🌐 Overview
**Kubernetes (K8s)** is an open-source container orchestration platform designed to automate the deployment, scaling, and operation of containerized applications.
---
## 🧠 Control Plane (CP)
The **Control Plane** is the core management component of a Kubernetes cluster. It makes global decisions about the cluster (e.g., scheduling) and maintains the desired state of the cluster by managing workloads and directing communication within the system.
> 💡 **Note:** By default, the Control Plane does not directly manage or run application containers.
### 🔑 Key Components of the Control Plane
- **API Server (`kube-apiserver`)**
Exposes the Kubernetes API and serves as the cluster's entry point. It handles communication between internal components and external clients.
- **Scheduler (`kube-scheduler`)**
Assigns workloads (e.g., Pods) to nodes based on resource availability and defined policies.
- **Controller Manager (`kube-controller-manager`)**
Runs controllers that monitor and regulate the cluster's state, such as the Node Controller and Replication Controller.
- **etcd**
A consistent and highly available key-value store that stores all cluster data, configurations, and state. This is the "database" of Kubernetes.
---
## 🧱 Worker Nodes
**Worker nodes** are the machines where containerized applications run. Each node contains essential components for managing containers.
### 🔧 Key Components of a Worker Node
- **Kubelet**
An agent that ensures containers run as specified in their Pod definitions. It communicates with the Control Plane to execute assigned tasks.
- **Kube Proxy**
Maintains network rules and manages routing for communication within the cluster and with external systems.
---
## 🔄 Data Flow
- **Kubelet** and **Kube Proxy** on each worker node interact with the **API Server** to perform operations and update resource states.
- The **Scheduler** selects suitable nodes for pod placement based on available resources.
- The **Controller Manager** ensures the actual state of the cluster matches the desired state.
---
## 🛠️ Administration Tools
- **`kubeadm`**
A command-line tool to bootstrap and configure Kubernetes clusters. It streamlines the setup of both the Control Plane and worker nodes.
- **`kubectl`**
The CLI for interacting with the Kubernetes API. It's used to deploy apps, inspect cluster resources, and manage configurations.
---
## 🧩 Kubernetes Version Compatibility
### Kubernetes and Container Runtimes
- **Kubernetes ≤ 1.23**
✅ Compatible with **Docker** as the default container runtime.
- **Kubernetes 1.24 1.25**
❌ Docker is **not supported** directly. Use `containerd` or another CRI-compliant runtime.
- **Kubernetes ≥ 1.25**
⚠️ Docker may be installed on the system but must be used **indirectly** through `containerd` or another supported CRI.
---
## 👥 Kubernetes Roles
- **Control Plane (Manager)**
Requires an **odd number** of nodes for high availability (e.g., 1, 3, 5, ...). This ensures quorum in distributed consensus.
- **Worker (none)**
These nodes run application workloads and do not participate in control decisions.
image pull policy in kubernetes:
example of all work loads:
https://k8s-examples.container-solutions.com/

View File

@@ -0,0 +1,161 @@
# 🐳 Containerd and Kubernetes Installation Guide
A comprehensive step-by-step guide for setting up a Kubernetes cluster using **Containerd** as the container runtime. This guide is intended for Ubuntu-based systems.
---
## ⚙️ 1. Disable Swap
Kubernetes requires swap to be disabled for proper scheduling and memory management.
```bash
sudo swapoff -a
sudo sed -i '/swap/d' /etc/fstab
```
---
## 🧩 2. Enable Required Kernel Modules
Load the necessary kernel modules for networking and overlay file systems.
```bash
cat <<EOF | sudo tee /etc/modules-load.d/containerd.conf
overlay
br_netfilter
EOF
sudo modprobe overlay
sudo modprobe br_netfilter
```
---
## 🌐 3. Enable IPv4 Forwarding
Enable packet forwarding to allow pods to communicate across the network.
```bash
sudo tee /etc/sysctl.d/99-kubernetes-cri.conf <<EOF
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-ip6tables = 1
EOF
sudo sysctl --system
```
---
## 📦 4. Install and Configure Containerd
Install and configure **Containerd** with `systemd` as the cgroup driver.
```bash
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 sed -i 's/SystemdCgroup = false/SystemdCgroup = true/' /etc/containerd/config.toml
sudo systemctl restart containerd
sudo systemctl enable containerd
```
---
## ⎈ 5. Install Kubernetes Components
Add the Kubernetes repository and install the core components: `kubelet`, `kubeadm`, and `kubectl`.
```bash
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.30/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
echo "deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.30/deb/ /" | 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
```
---
## 🔁 6. Enable Kubelet Service
Start and enable the kubelet to run on system boot.
```bash
sudo systemctl enable --now kubelet
```
---
## 🚀 7. Initialize the Kubernetes Control Plane
Initialize the cluster. Replace the IP with your master node's IP address.
```bash
sudo kubeadm init \
--control-plane-endpoint 192.168.2.100 \
--apiserver-advertise-address 192.168.2.100 \
--pod-network-cidr 10.244.0.0/16 | tee kuber-install.log
```
---
## 🛠 8. Configure kubectl Access
Set up `kubectl` for the current (non-root) user.
```bash
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
```
---
## 🧾 9. Create Control Plane Join Command
Generate a command for other control plane nodes to join the cluster.
```bash
sudo kubeadm init phase upload-certs --upload-certs
```
Copy the **certificate key** from the output above and run:
```bash
sudo kubeadm token create --certificate-key <CERTIFICATE_KEY> --print-join-command | tee cp-command.txt
```
Replace `<CERTIFICATE_KEY>` with the actual key.
---
## 🧑‍🤝‍🧑 10. Join Control Plane and Worker Nodes
* **Control Plane Nodes**: Use the command from `cp-command.txt` on each node.
* **Worker Nodes**: Use the `kubeadm join` command printed at the end of the `kubeadm init` output or found in `kuber-install.log`.
---
## ✅ Final Step: Install a Pod Network Add-on
Choose and apply a pod network add-on (e.g., Flannel, Calico, Cilium). Here's an example with Flannel:
```bash
kubectl apply -f https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml
```
---
🎉 **Your Kubernetes cluster is now up and running!**
Ensure all nodes are ready by running:
```bash
kubectl get nodes
```

View File

@@ -0,0 +1,13 @@
```bash
kubectl complation <shell>
```
exapmles:
```bash
kubectl completion zsh > "${fpath[1]}/_kubectl"
```
```bash
kubectl completion bash > ~/.kube/completion.bash.inc
```

View File

@@ -0,0 +1,121 @@
# Kubernetes Command Reference
This guide provides a concise reference for common `kubectl` commands used to manage Kubernetes clusters. Whether youre managing nodes, namespaces, pods, deployments, or autoscaling, the examples below will help you perform everyday tasks with confidence.
## General Commands
- **List API Resources**
Display all available API resources along with their short names:
```bash
kubectl api-resources
```
---
## API Resources & Documentation
- **Get Detailed Documentation for an API Resource**
```bash
kubectl explain <api-resource-name>
```
*Example:*
```bash
kubectl explain pod
```
```bash
kubectl explain pod.metadata
```
---
## Applying YAML Files
- **Apply a Configuration from a YAML File**
Apply a YAML configuration to a specific namespace:
```bash
kubectl apply -f <yaml-file> -n <namespace-name>
```
---
## Viewing Cluster Resources
- **Display All Resources in a Namespace**
```bash
kubectl get all -n <namespace-name>
```
- **Display ReplicaSets, Pods, and Deployments in a Specific Namespace**
```bash
kubectl get rs,pods,deployments -n <namespace-name>
```
---
## ReplicaSet & Deployment Management
### Scaling and Rollouts
- **Scale a ReplicaSet**
```bash
kubectl scale rs <replicaset-name> --replicas=<count> -n <namespace-name>
```
- **View Rollout History of a Deployment**
```bash
kubectl rollout history deployment <deployment-name> -n <namespace-name>
```
- **View Details of a Specific Revision**
```bash
kubectl rollout history deployment <deployment-name> -n <namespace-name> --revision=<number>
```
- **Roll Back a Deployment to a Specific Revision**
```bash
kubectl rollout undo deployment <deployment-name> -n <namespace-name> --to-revision=<number>
```
### Autoscaling
- **Autoscale a Deployment**
Automatically scale a deployment based on CPU utilization:
```bash
kubectl autoscale deployment <deployment-name> -n <namespace-name> --cpu-percent=<target-cpu-percentage> --min=<min-pods> --max=<max-pods>
```
- **View Horizontal Pod Autoscalers (HPA)**
```bash
kubectl get hpa -n <namespace-name>
```
---
---
## Additional Information
- **Static Manifest Files**
Any YAML files placed in `/etc/kubernetes/manifests/` are automatically loaded when the kubelet starts (for example, after a server reboot).
```bash
kubectl cp -n <ns> <pod-name>:dir/ ./
```

View File

@@ -0,0 +1,9 @@
- **Set a Custom Label on a Node**
```bash
kubectl label node <node-name> kubernetes.io/<label-key>=<label-value>
```
> **Note:** Replace `<node-name>`, `<label-key>`, and `<label-value>` with your desired values.

View File

@@ -0,0 +1,27 @@
- **Stream Logs for a Running Pod**
```bash
kubectl logs -f -n <namespace-name> <pod-name>
```
```bash
kubectl logs -f -n <namespace-name> <pod-name> -c <container-name>
```
- **Get Detailed Information About a Pod**
```bash
kubectl describe pod <pod-name> -n <namespace-name>
```
in log swith the pod need to be up
but in describe dont need to pod be up
describe work on all components

View File

@@ -0,0 +1,63 @@
# 🌐 Node Management with Kubernetes
Efficient management of Kubernetes nodes ensures cluster stability and workload flexibility. Below are key commands for listing and maintaining nodes.
---
## 📋 Listing Nodes
### 🔹 Show All Nodes
```bash
kubectl get nodes
````
### 🔹 Show Nodes with Labels
```bash
kubectl get nodes --show-labels
```
---
## 🔧 Node Maintenance (Cordon / Drain)
### 🚫 Cordon a Node
Prevent new pods from being scheduled on the node.
```bash
kubectl cordon <node-name>
```
### ✅ Uncordon a Node
Mark the node as schedulable again.
```bash
kubectl uncordon <node-name>
```
### 🧹 Drain a Node
Evict all pods from the node (excluding those managed by DaemonSets).
* Forcefully drain the node:
```bash
kubectl drain <node-name> --ignore-daemonsets --force
```
* Drain and delete local data:
```bash
kubectl drain <node-name> --ignore-daemonsets --delete-local-data
```
#### 🔄 Undo Drain (Uncordon)
```bash
kubectl uncordon <node-name>
```
> ⚠️ **Warning:** Draining a node will evict running pods. Ensure that this is planned to avoid service disruption.

View File

@@ -0,0 +1,180 @@
# **crictl: CLI for CRI-Compatible Container Runtimes**
## Overview
`crictl` is a **command-line interface** for **Container Runtime Interface (CRI)**compatible runtimes such as **containerd** and **CRI-O**, primarily used within Kubernetes environments.
It provides node-level visibility and control over pods, containers, and images. While it resembles Docker CLI in syntax, it is designed for **debugging** and **inspection**, not for managing workloads outside Kubernetes control.
`crictl` is part of the **[cri-tools](https://github.com/kubernetes-sigs/cri-tools)** project, which also includes `critest`.
---
## Installation
1. Navigate to the [cri-tools releases page](https://github.com/kubernetes-sigs/cri-tools/releases) to find the version compatible with your Kubernetes or CRI runtime.
2. Download and install `crictl`:
```bash
VERSION="v1.33.0"
wget https://github.com/kubernetes-sigs/cri-tools/releases/download/$VERSION/crictl-$VERSION-linux-amd64.tar.gz
tar zxvf crictl-$VERSION-linux-amd64.tar.gz
sudo mv crictl /usr/local/bin/
```
*(Adjust version and architecture as needed.)*
3. Clean up the tarball if desired.
4. Verify installation:
```bash
crictl --version
```
---
## Configuration and Endpoints
`crictl` communicates with CRI runtimes using socket endpoints.
### Configuration Methods
You can configure endpoints via:
* **Command-line flags**: `--runtime-endpoint`, `--image-endpoint`
* **Environment variables**:
`CONTAINER_RUNTIME_ENDPOINT`, `IMAGE_SERVICE_ENDPOINT`
* **Configuration file**: Default path `/etc/crictl.yaml`
* **Custom config file**: Use `--config=<path>`
### Example `/etc/crictl.yaml`
```yaml
runtime-endpoint: unix:///var/run/containerd/containerd.sock
image-endpoint: unix:///var/run/containerd/containerd.sock
timeout: 10
debug: true
```
If no endpoint is provided, `crictl` attempts to connect to a list of known sockets, which can slow operations.
### Modifying Configuration
```bash
crictl config --set debug=true
crictl config --get debug
```
Additional configuration parameters include:
* `pull-image-on-create`
* `disable-pull-on-run`
---
## Global Options
| Flag | Description |
| --------------------------- | ------------------------------------------ |
| `-h`, `--help` | Display help and usage information |
| `-v`, `--version` | Display crictl and runtime version details |
| `--runtime-endpoint <path>` | Specify CRI runtime socket |
| `--image-endpoint <path>` | Specify CRI image service socket |
| `--timeout <duration>` | Connection timeout (e.g., `5s`) |
| `-D`, `--debug` | Enable verbose output |
| `--config <path>` | Specify a custom config file |
---
## Common Commands
### Status and Information
| Command | Description |
| ---------------- | ----------------------------------------------------- |
| `crictl version` | Display version and runtime API info |
| `crictl info` | Show runtime health, plugin states, and configuration |
### Pods / Pod Sandboxes
| Command | Description |
| ----------------------------------- | ---------------------------------- |
| `crictl pods` | List all pod sandboxes on the node |
| `crictl inspectp <POD_ID>` | Inspect a specific pod sandbox |
| `crictl runp <sandbox-config.json>` | Create a new pod sandbox |
| `crictl stopp <POD_ID>` | Stop a pod sandbox |
| `crictl rmp <POD_ID>` | Remove a pod sandbox |
### Containers
| Command | Description |
| ---------------------------------------------------------------------- | ---------------------------------------- |
| `crictl ps` / `crictl ps -a` | List running / all containers |
| `crictl inspect <CONTAINER_ID>` | Inspect a specific container |
| `crictl create <POD_ID> <container-config.json> <sandbox-config.json>` | Create a container in a pod |
| `crictl start <CONTAINER_ID>` | Start a container |
| `crictl exec -i -t <CONTAINER_ID> <command>` | Execute a command inside a container |
| `crictl stop <CONTAINER_ID>` | Stop a running container |
| `crictl rm <CONTAINER_ID>` | Remove a stopped container |
| `crictl stats` | Show CPU and memory usage for containers |
### Images
| Command | Description |
| ------------------------- | ----------------------------- |
| `crictl images` | List available images |
| `crictl inspecti <IMAGE>` | Inspect image metadata |
| `crictl pull <IMAGE>` | Pull an image from a registry |
| `crictl rmi <IMAGE>` | Remove an image |
| `crictl load <tarball>` | Load an image from a tar file |
---
## Best Practices and Caveats
* **Kubelet cleanup:** Containers or pods created manually with `crictl` may be removed by the kubelet since theyre not managed by the Kubernetes control plane. Use for debugging only.
* **Permissions:** Root privileges or socket access are often required to communicate with the runtime.
* **Version compatibility:** Always match your `crictl` version to your Kubernetes or CRI runtime.
* **Timeout tuning:** Adjust `--timeout` or configuration to avoid connection failures.
* **Not a Docker replacement:** Although similar in command structure, `crictl` interacts directly with the CRI layer and may not support all Docker features.
---
## Example Debugging Workflow
1. SSH into a Kubernetes node.
2. Check runtime health:
```bash
crictl info
crictl version
```
3. List pod sandboxes:
```bash
crictl pods
```
4. Inspect a pod:
```bash
crictl inspectp <POD_ID>
```
5. List and inspect containers:
```bash
crictl ps -a
crictl inspect <CONTAINER_ID>
```
6. Execute into or inspect logs:
```bash
crictl exec -it <CONTAINER_ID> sh
```
7. Clean up stuck containers or unused images:
```bash
crictl stop <CONTAINER_ID>
crictl rm <CONTAINER_ID>
crictl rmi <IMAGE>
```
This workflow is typically used for **node-level debugging**, especially when `kubectl` cannot access or display runtime state.

View File

@@ -0,0 +1,58 @@
# 📦 Deploying Longhorn with `kubectl`
This guide walks you through installing **Longhorn**, a cloud-native distributed block storage solution for Kubernetes, using `kubectl`.
---
## 🚀 Prerequisites
* A Kubernetes cluster (v1.21 or newer recommended)
* `kubectl` configured and connected to your cluster
* Internet access for downloading manifests
---
## 🧩 Step 1: Apply Longhorn YAML
Apply the official Longhorn deployment manifest in the `longhorn-system` namespace:
```bash
kubectl apply -f https://raw.githubusercontent.com/longhorn/longhorn/v1.9.0/deploy/longhorn.yaml
```
This will create all required resources under the `longhorn-system` namespace.
---
## 🔍 Step 2: Monitor Longhorn Pods
Watch the pods being created to ensure Longhorn is deploying properly:
```bash
kubectl get pods \
--namespace longhorn-system \
--watch
```
Wait until all pods show a `Running` or `Completed` status.
---
## 📦 Step 3: Verify Storage Classes
Once Longhorn is running, verify that the storage classes have been registered:
```bash
kubectl get storageclasses
```
You should see a storage class named `longhorn`, which can now be used in your PersistentVolumeClaims (PVCs).
---
## ✅ Success!
Longhorn is now successfully deployed and ready to provide persistent block storage for your workloads.
For more information, visit the [official Longhorn documentation](https://longhorn.io/docs/).

View File

@@ -0,0 +1,64 @@
## 📦 Pod Volume Lifecycle & `emptyDir` Usage in Kubernetes
This document describes how volumes work in the context of Kubernetes Pods, focusing on `emptyDir` and its lifecycle behavior.
---
### 🔁 Pod Lifecycle & Volumes
* **Volumes are defined at the Pod level.**
They are not tied to a specific container, but can be shared among containers within the same Pod.
* **Volumes are attached to containers through `volumeMounts`.**
This enables containers to access the volumes filesystem at the specified `mountPath`.
* **Data in `emptyDir` volumes is ephemeral.**
The volume is created when the Pod starts and **deleted when the Pod is removed**, erasing all stored data.
---
### ⚠️ Visibility Across Pods & Containers
* A **Pod cannot access another Pods volume**, even if it's of type `emptyDir`.
For example:
* Pod A cannot see Pod Bs `emptyDir`.
* However, **containers within the same Pod can share and access the same `emptyDir`** volume.
---
### 🧪 Example: Pod with `emptyDir` Volume in Memory
```yaml
apiVersion: v1
kind: Pod
metadata:
namespace: ns-test
name: pod-tests
spec:
containers:
- name: nginx
image: nginx
resources:
limits:
memory: "150Mi"
cpu: "500m"
volumeMounts:
- name: nginx-log
mountPath: /var/log/nginx
volumes:
- name: nginx-log
emptyDir:
medium: Memory # Uses memory for faster read/write operations
sizeLimit: 64Mi # Volume size limited to 64Mi
```
---
### 🧠 Key Points
* `emptyDir` is ideal for temporary storage like logs, scratch space, or caches.
* Using `medium: Memory` stores data in memory (RAM) instead of disk, offering higher performance.
* `sizeLimit` restricts the amount of memory that the `emptyDir` can consume.

View File

@@ -0,0 +1,181 @@
# 🌐 Kubernetes: Persistent Volumes (PV) Cheat Sheet
## 📦 What is a Persistent Volume (PV)?
A **Persistent Volume** is a piece of storage in a Kubernetes cluster that has been provisioned by an administrator or dynamically provisioned using **StorageClasses**.
---
## 📁 PV Storage Options
1. **HostPath**
* Mounts a file or directory from the host nodes filesystem into your Pod.
2. **Using PV and PVC**
* **PV (Persistent Volume):** The actual storage resource.
* **PVC (Persistent Volume Claim):** A request for storage by a user.
---
## 🧱 Kubernetes Storage Layers
1. **Persistent Volume (PV)**
2. **Persistent Volume Claim (PVC)**
---
## 🔄 PV Lifecycle States
| State | Description |
| ------------ | ---------------------------------------------------- |
| Provisioning | Kubernetes is preparing the PV. |
| Binding | The PV is bound to a PVC. |
| Using | The bound PV is being used by a Pod. |
| Releasing | PVC is deleted; PV is no longer bound. |
| Reclaiming | PV is reclaimed using one of the following policies: |
| |     • `Delete` Remove the storage |
| |     • `Recycle` Basic scrub (deprecated) |
| |     • `Retain` Manual reclaim |
---
## 🔒 PV Access Modes
| Mode | Description |
| ------ | ------------------------------------------- |
| `RWO` | **ReadWriteOnce** One node can read/write |
| `ROX` | **ReadOnlyMany** Many nodes read-only |
| `RWX` | **ReadWriteMany** Many nodes read/write |
| `RWOP` | **ReadWriteOncePod** One Pod only |
---
## 🛠️ Check PVs via CLI
```bash
kubectl get pv
```
```bash
kubectl get pvc
```
---
## 🚀 Example: Deployment using HostPath Volume
```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
ports:
- containerPort: 80
volumeMounts:
- name: nginx-log
mountPath: /var/log/nginx
volumes:
- name: nginx-log
hostPath:
path: /root/nginx/logs
```
---
## 📂 Example: PersistentVolume with NFS
```yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv1
spec:
capacity:
storage: 5Gi
volumeMode: Filesystem
accessModes:
- ReadWriteMany
persistentVolumeReclaimPolicy: Recycle
storageClassName: custom-name
mountOptions:
- hard
- nfsvers=4.1
nfs:
path: /nfs/data
server: 192.168.1.10
```
```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
ports:
- containerPort: 80
volumeMounts:
- name: nginx-log
mountPath: /var/log/nginx
volumes:
- name: nginx-log
persisentVolumeClaim:
claimName: pv1
---
apiVersion: v1
kind: persisentVolumeClaim
metadata:
name: pvc1
namespace: ns-test
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 1Gi
limits:
storage: 2Gi
storageClassName: custom-name
```

View File

@@ -0,0 +1,172 @@
# 🛠️ Setting Up a High Availability etcd Cluster for Kubernetes
This guide walks you through installing a 3-node etcd cluster and using it as an **external HA datastore for Kubernetes**.
---
## 📦 Step 1: Install etcd
Download the etcd binary:
```bash
wget https://github.com/etcd-io/etcd/releases/download/v3.6.2/etcd-v3.6.2-linux-amd64.tar.gz
```
Extract it:
```bash
tar -xzvf etcd-v3.6.2-linux-amd64.tar.gz
```
Move binaries to the system path:
```bash
cp etcd-v3.6.2-linux-amd64/etcd* /usr/local/bin
```
Create the data directory:
```bash
mkdir -p /var/lib/etcd
```
---
## ⚙️ Step 2: Configure etcd Systemd Services
Create a systemd service config at:
```bash
/etc/systemd/system/etcd.conf
```
### 🔹 Server 1 (`192.168.6.170`)
```ini
[Service]
ExecStart=/usr/local/bin/etcd \
--name etcd-1 \
--listen-client-urls http://192.168.6.170:2379,http://127.0.0.1:2379 \
--advertise-client-urls http://192.168.6.170:2379 \
--initial-advertise-peer-urls http://192.168.6.170:2380 \
--listen-peer-urls http://192.168.6.170:2380 \
--initial-cluster-token etcd-cluster-1 \
--initial-cluster etcd-1=http://192.168.6.170:2380,etcd-2=http://192.168.6.171:2380,etcd-3=http://192.168.6.172:2380 \
--initial-cluster-state new \
--data-dir /var/lib/etcd
Restart=always
User=root
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
```
### 🔹 Server 2 (`192.168.6.171`)
```ini
[Service]
ExecStart=/usr/local/bin/etcd \
--name etcd-2 \
--listen-client-urls http://192.168.6.171:2379,http://127.0.0.1:2379 \
--advertise-client-urls http://192.168.6.171:2379 \
--initial-advertise-peer-urls http://192.168.6.171:2380 \
--listen-peer-urls http://192.168.6.171:2380 \
--initial-cluster-token etcd-cluster-1 \
--initial-cluster etcd-1=http://192.168.6.170:2380,etcd-2=http://192.168.6.171:2380,etcd-3=http://192.168.6.172:2380 \
--initial-cluster-state new \
--data-dir /var/lib/etcd
Restart=always
User=root
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
```
### 🔹 Server 3 (`192.168.6.172`)
```ini
[Service]
ExecStart=/usr/local/bin/etcd \
--name etcd-3 \
--listen-client-urls http://192.168.6.172:2379,http://127.0.0.1:2379 \
--advertise-client-urls http://192.168.6.172:2379 \
--initial-advertise-peer-urls http://192.168.6.172:2380 \
--listen-peer-urls http://192.168.6.172:2380 \
--initial-cluster-token etcd-cluster-1 \
--initial-cluster etcd-1=http://192.168.6.170:2380,etcd-2=http://192.168.6.171:2380,etcd-3=http://192.168.6.172:2380 \
--initial-cluster-state new \
--data-dir /var/lib/etcd
Restart=always
User=root
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
```
---
## ▶️ Step 3: Start etcd Service
Enable and start the etcd service on **each server**:
```bash
systemctl start etcd
systemctl enable etcd
```
---
## ✅ Step 4: Verify etcd Cluster Health
Check endpoint health:
```bash
etcdctl --endpoints http://<IP>:2379 endpoint health
```
Check cluster membership:
```bash
etcdctl --endpoints http://<IP-SERVER-1>:2379 member list
```
If all members are healthy and visible, you're ready to move on.
---
## ☸️ Step 5: Install Kubernetes (Using External etcd)
Create a configuration file `config.yaml` on the **master node**:
```yaml
apiVersion: kubeadm.k8s.io/v1beta3
kind: ClusterConfiguration
etcd:
external:
endpoints:
- http://192.168.6.170:2379
- http://192.168.6.171:2379
- http://192.168.6.172:2379
networking:
podSubnet: 10.244.0.0/16
```
Initialize Kubernetes:
```bash
kubeadm init --config config.yaml
```
---
## 🎉 Done!
You now have a **Kubernetes cluster with external, high availability etcd**. :)

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,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,144 @@
# 🔗 **Kubernetes Services (SVC)**
A **Service** in Kubernetes provides a stable network endpoint to access a set of Pods. It abstracts access through selectors and DNS names, enabling loose coupling between client applications and Pods.
---
## 🌐 **Service Basics**
### 📌 **Service Flow**
```
Service ➡️ Endpoint ➡️ Pods
```
* Services **group Pods** behind a single access point.
* They get a **cluster-wide DNS name** automatically.
* Use **label selectors** to forward traffic to matching Pods.
---
## 🧭 **Types of Services**
1. **ClusterIP** (default)
* Only reachable within the cluster.
2. **NodePort**
* Exposes the service via a static port on each node.
3. **LoadBalancer**
* Creates an external IP address using a cloud provider.
---
## 🧪 **Useful Commands**
### 🔍 Get Endpoints
```bash
kubectl get ep -n <namespace>
```
### 📄 Get Services
```bash
kubectl get svc -n <namespace>
```
```bash
kubectl expose deployment web-server-dep -n dev --port 80
```
---
## 🔁 **Port Forwarding**
To access a service from your local machine, forward a local port to the service port:
```bash
kubectl port-forward -n <namespace> svc/<service-name> <local-port>:<target-port>
```
> **Example:**
> Forward local port `8080` to port `80` of `my-service` in the `mynamespace` namespace:
>
> ```bash
> kubectl port-forward -n mynamespace svc/my-service 8080:80
> ```
You can also bind to all network interfaces:
```bash
kubectl port-forward -n <namespace> svc/nginx 80:80 --address 0.0.0.0
```
> 🌐 **DNS format:**
> `<service-name>.<namespace>.svc.cluster.local`
---
## 🧾 **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: 80
targetPort: 8080
```
> 🔍 **Note:** The `selector` must match the labels of the target Pods.
> 🧠 **Tip:** Use `kubectl describe svc <service-name>` to inspect the service and verify connectivity.
```yaml
apiVersion: v1
kind: Service
metadata:
name: nginx
namespace: ns
labels:
app: web-server
spec:
type: LoadBalancer
selector:
app: nginx
ports:
- name: http
port: 80
targetPort: 8080
```
```yaml
apiVersion: v1
kind: Service
metadata:
name: db-svc
namespace: db
spec:
type: NodePort
ports:
- name: sql
port: 3306
targetPort: 3306
nodePort: 30000
selector:
app: db
```

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,188 @@
# 🧾 Kubernetes ConfigMap Guide
Manage configuration without hardcoding! `ConfigMaps` let you store external configurations as key-value pairs and inject them into Kubernetes workloads.
---
## 📘 What is a ConfigMap?
A **ConfigMap** is a Kubernetes object used to store **non-confidential configuration data** in **key-value** format. You can:
* 📄 Mount it as files inside a Pod
* 🌿 Use it as environment variables
* 🧩 Keep your container images decoupled from configuration
---
## ⚙️ Creating a ConfigMap
You can create a ConfigMap from files or directories:
```bash
kubectl -n <namespace> create configmap <configmap-name> --from-file=<file-or-directory>
```
### ✅ Examples
```bash
# From a single file
kubectl -n <ns> create configmap nginx-conf --from-file=./nginx.conf
# From multiple files
kubectl -n <ns> create configmap nginx-conf \
--from-file=./nginx.conf \
--from-file=./site.conf
```
---
## 📂 Viewing & Editing ConfigMaps
```bash
# List all ConfigMaps in a namespace
kubectl get cm -n <namespace>
# View detailed ConfigMap info
kubectl describe configmap <name> -n <namespace>
# Edit in-place
kubectl -n <namespace> edit configmap <configmap-name>
```
---
## 📄 YAML: ConfigMap Example
```yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: game-demo
data:
player_initial_lives: "3"
ui_properties_file_name: "user-interface.properties"
game.properties: |
enemy.types=aliens,monsters
player.maximum-lives=5
user-interface.properties: |
color.good=purple
color.bad=yellow
allow.textmode=true
```
---
## 💡 Usage Examples
### 📌 ConfigMap as Environment Variables
**ConfigMap:**
```yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
namespace: default
data:
APP_MODE: "production"
LOG_LEVEL: "info"
FEATURE_FLAG_X: "enabled"
```
**Pod:**
```yaml
apiVersion: v1
kind: Pod
metadata:
name: my-app
spec:
containers:
- name: my-container
image: busybox
command: ["/bin/sh", "-c", "env && sleep 3600"]
envFrom:
- configMapRef:
name: app-config
```
---
### 🧾 Mounting ConfigMap as a File (nginx.conf example)
**ConfigMap:**
```yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: nginx-config
namespace: default
data:
nginx.conf: |
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
```
**Pod:**
```yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
spec:
containers:
- name: nginx
image: nginx:latest
volumeMounts:
- name: nginx-config-volume
mountPath: /etc/nginx/nginx.conf
subPath: nginx.conf
volumes:
- name: nginx-config-volume
configMap:
name: nginx-config
```
---
## 🛠 Pro Tips
* 🔐 For **sensitive data**, use **Secrets** instead of ConfigMaps.
* 🧪 Combine ConfigMaps with **Deployment** objects for flexible, versioned config management.
* 📦 Use `--from-env-file` to load multiple key-value pairs from a `.env` style file:
```bash
kubectl create configmap my-config --from-env-file=env.list
```

View File

@@ -0,0 +1,21 @@
resource Quota:
```bash
kubectl get resourcequota -n <ns>
```
```yaml
apiVersion: v1
kind: ResourceQuota
metadata:
name: my-ns-quota
namcespace: dev
spec:
hard:
pod: 10
requests.cpu: "1"
requests.memory: "1024Mb"
service: "5"
configmap: "2"
```

View File

@@ -0,0 +1,78 @@
# 🔐 Kubernetes Secrets Guide
Kubernetes **Secrets** are used to store and manage sensitive information such as passwords, OAuth tokens, and SSH keys. Unlike ConfigMaps, they are specifically designed for confidential data.
---
## 📌 Types of Kubernetes Secrets
| **Built-in Type** | **Usage** |
| ------------------------------------- | --------------------------------------- |
| `Opaque` | Arbitrary user-defined data |
| `kubernetes.io/service-account-token` | ServiceAccount token |
| `kubernetes.io/dockercfg` | Serialized `~/.dockercfg` file |
| `kubernetes.io/dockerconfigjson` | Serialized `~/.docker/config.json` file |
| `kubernetes.io/basic-auth` | Credentials for basic authentication |
| `kubernetes.io/ssh-auth` | Credentials for SSH authentication |
| `kubernetes.io/tls` | Data for a TLS client or server |
| `bootstrap.kubernetes.io/token` | Bootstrap token data |
---
## 📂 Creating a Secret
You can create a Secret directly with `kubectl`:
```bash
kubectl create secret generic db-pass --from-literal=password='123'
```
Verify it exists:
```bash
kubectl get secret db-pass
```
---
## 📜 Secret YAML Example
```yaml
apiVersion: v1
kind: Secret
metadata:
name: db-pass
type: Opaque
stringData:
password: '123'
```
---
## 🚀 Using a Secret in a Pod
Secrets can be injected into a Pod as **environment variables**:
```yaml
apiVersion: v1
kind: Pod
metadata:
name: mariadb-db
spec:
containers:
- name: mariadb
image: mariadb
env:
- name: MARIADB_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: db-pass
key: password
```
This example sets the MariaDB root password from the `db-pass` Secret.
---
**Pro Tip**: Always base64-encode values when writing Secrets directly in YAML. Kubernetes expects the `data` field in base64, not plaintext.

View File

@@ -0,0 +1,2 @@
traffic input --> ingress
traffic output --> egress

View File

@@ -0,0 +1,140 @@
# Kubernetes Lifecycle Hooks: `postStart` and `preStop`
## Overview
In Kubernetes, **lifecycle hooks** allow you to run specific code when a container starts or stops. These hooks are part of a containers lifecycle and are useful for performing setup and cleanup tasks.
The two main lifecycle hooks are:
* **`postStart`** Executed immediately after the container starts.
* **`preStop`** Executed just before the container stops.
These hooks can be defined inside the container specification in a Pod manifest.
---
## 1. `postStart` Hook
### Description
The `postStart` hook runs **immediately after a container is created**, but before it is marked as *Running*. It can be used to perform initialization tasks that need to occur right after startup.
The `postStart` hook supports two types of actions:
* `exec` Run a command inside the container.
* `httpGet` Send an HTTP request to a specified endpoint inside the container.
### Notes
* The `postStart` hook and the containers main process run **concurrently**.
* If the hook fails, the container is considered to have failed and will be restarted according to its restart policy.
### Example
```yaml
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "echo Container started at $(date) >> /var/log/startup.log"]
```
Using an HTTP GET action:
```yaml
lifecycle:
postStart:
httpGet:
path: /startup
port: 8080
```
### Common Use Cases
* Initializing configuration files or environment data.
* Sending startup notifications to monitoring systems.
* Preparing application dependencies.
---
## 2. `preStop` Hook
### Description
The `preStop` hook runs **just before a container is terminated**. Kubernetes will execute the hook and wait for it to complete before sending the `SIGTERM` signal to the containers main process.
This hook is typically used to ensure a **graceful shutdown** of the application.
Like `postStart`, it supports:
* `exec`
* `httpGet`
### Notes
* The hook must complete within the time defined by `terminationGracePeriodSeconds`.
* If the hook does not finish within that time, the container will be forcibly terminated.
### Example
```yaml
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "echo Shutting down... >> /var/log/shutdown.log && sleep 5"]
```
### Common Use Cases
* Closing active connections.
* Flushing logs or metrics.
* Deregistering the service from a load balancer or discovery system.
* Notifying external systems about the shutdown event.
---
## 3. Full Example
```yaml
apiVersion: v1
kind: Pod
metadata:
name: lifecycle-demo
spec:
containers:
- name: demo-container
image: nginx
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "echo 'Container started!' > /usr/share/nginx/html/index.html"]
preStop:
exec:
command: ["/bin/sh", "-c", "echo 'Container stopping...' >> /usr/share/nginx/html/index.html && sleep 10"]
terminationGracePeriodSeconds: 15
```
---
## 4. Best Practices for DevOps Engineers
1. **Handle Signals in Your Application**
Ensure your application properly handles `SIGTERM` and `SIGKILL` for clean shutdowns.
2. **Combine Hooks with Grace Periods**
Use `preStop` together with `terminationGracePeriodSeconds` to allow sufficient cleanup time.
3. **Monitor Hook Execution**
Log hook outputs for debugging and verification.
4. **Avoid Long-Running or Blocking Hooks**
Hooks should be lightweight to avoid delaying container lifecycle events.
---
## 5. Summary
| Hook Type | Trigger Time | Purpose | Common Actions |
| ----------- | ---------------------------------- | ----------------- | ------------------------------------------------- |
| `postStart` | Immediately after container starts | Initialization | Load configs, warm cache, notify service |
| `preStop` | Before container termination | Graceful shutdown | Flush data, close connections, deregister service |

View File

@@ -0,0 +1,104 @@
## LimitRange in Kubernetes
### Overview
A **LimitRange** in Kubernetes is a namespace-level policy object that defines constraints on the compute resources that individual **Pods** and **Containers** can request and use. It helps ensure that workloads run efficiently and fairly within a shared cluster.
A LimitRange can set:
* Minimum and maximum resource requests and limits
* Default requests and limits if none are specified by the user
While a **ResourceQuota** enforces limits at the **namespace** level (total resource usage), a **LimitRange** enforces rules at the **Pod or Container** level.
---
### Why Use a LimitRange
In a shared cluster, users might:
* Deploy Pods without specifying any resource requests or limits.
* Request excessive resources, leading to inefficient utilization.
A LimitRange prevents these issues by:
* Automatically applying default resource values when unspecified.
* Enforcing minimum and maximum resource thresholds.
* Ensuring fair distribution of resources among applications.
---
### How It Works
When a Pod or Container is created in a namespace with a LimitRange:
1. The Kubernetes API server checks if resource requests and limits are defined.
2. If they are not provided, the LimitRange applies the configured default values.
3. If provided values fall outside the configured minimum or maximum bounds, the API server rejects the creation request.
---
### Example: LimitRange YAML
```yaml
apiVersion: v1
kind: LimitRange
metadata:
name: mem-cpu-limits
namespace: dev-team
spec:
limits:
- type: Container
max:
cpu: "2" # Maximum 2 cores per container
memory: "2Gi" # Maximum 2Gi memory per container
min:
cpu: "200m" # Minimum 0.2 cores per container
memory: "256Mi" # Minimum 256Mi memory per container
default:
cpu: "500m" # Default limit if not specified
memory: "512Mi"
defaultRequest:
cpu: "250m" # Default request if not specified
memory: "256Mi"
```
---
### Example Behavior
| Scenario | Request/Limit Defined? | Result |
| -------- | ---------------------- | --------------------------------------------- |
| None | No | Defaults applied (`250m` CPU, `256Mi` Memory) |
| Too High | Yes (e.g., 3 CPU) | Rejected — exceeds max of 2 |
| Too Low | Yes (e.g., 100m CPU) | Rejected — below min of 200m |
---
### Viewing a LimitRange
You can inspect LimitRanges in a namespace using:
```bash
kubectl get limitrange -n dev-team
kubectl describe limitrange mem-cpu-limits -n dev-team
```
---
### LimitRange vs ResourceQuota
| Feature | LimitRange | ResourceQuota |
| --------------- | -------------------------------- | ------------------------------ |
| Scope | Per Container/Pod | Per Namespace |
| Controls | Min/Max/Default resource values | Total resource usage |
| Purpose | Enforce sane defaults and bounds | Prevent namespace-wide overuse |
| Works best with | ResourceQuota | LimitRange |
---
### Summary
A **LimitRange** ensures that every Pod or Container in a namespace has appropriate resource requests and limits, preventing resource misuse and ensuring cluster stability. It complements **ResourceQuota** to provide complete resource management across both individual workloads and namespaces.

View File

@@ -0,0 +1,20 @@
apiVersion: batch/v1
kind: CronJob
metadata:
name: cronjob1
namespace: ns-test
spec:
schedule: "* * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: mycronjob
image: debian
command:
- /bin/bash
- -c
- "echo 'Hello, CronJob!'"
restartPolicy: Never

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"

View File

@@ -0,0 +1,28 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-deployment
namespace: ns-test
labels:
name: deployment-test
spec:
replicas: 2
selector:
matchLabels:
name: app1
template:
metadata:
labels:
name: app1
spec:
containers:
- name: nginx-deployment
image: nginx:1.26
resources:
limits:
cpu: "400m"
memory: "512Mi"
requests:
cpu: "200m"
memory: "128Mi"

View File

@@ -0,0 +1,19 @@
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: daemonset-test
namespace: ns-test
spec:
selector:
matchLabels:
name: node-exporter
template:
metadata:
labels:
name: node-exporter
spec:
containers:
- name: node-exporter
image: prom/node-exporter

View File

@@ -0,0 +1,15 @@
apiVersion: batch/v1
kind: Job
metadata:
name: job1
namespace: ns-test
spec:
template:
spec:
containers:
- name: job-container
image: debian
command:
- echo
- "hello world"
restartPolicy: Never

View File

@@ -0,0 +1,16 @@
apiVersion: v1
kind: Pod
metadata:
name: lifecycle-demo
spec:
containers:
- name: demo-container
image: nginx
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "echo 'Container started!' > /usr/share/nginx/html/index.html"]
preStop:
exec:
command: ["/bin/sh", "-c", "echo 'Container stopping...' >> /usr/share/nginx/html/index.html && sleep 10"]
terminationGracePeriodSeconds: 15

View File

@@ -0,0 +1,5 @@
apiVersion: v1
kind: Namespace
metadata:
name: ns-test

View File

@@ -0,0 +1,23 @@
apiVersion: v1
kind: Pod
metadata:
namespace: ns-test
name: pod-tests
labels:
var1: var1_value
var2: var2_value
app.kubernetes.io/var3: var3_value
app.kubernetes.io/var4: var4_value
spec:
containers:
- name: nginx
image: nginx
resources:
limits:
memory: "150Mi"
cpu: "500m"
requests:
memory: "100Mi"
cpu: "200m"
nodeSelector:
kubernetes.io/hostname: kuber-2

View File

@@ -0,0 +1,18 @@
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: app1
namespace: ns-test
spec:
replicas: 3
selector:
matchLabels:
app.kubernetes.io/name: app1
template:
metadata:
labels:
app.kubernetes.io/name: app1
spec:
containers:
- name: nginx
image: nginx

View File

@@ -0,0 +1,15 @@
apiVersion: v1
kind: Service
metadata:
name: nginx
namespace: ns-test
labels:
app: nginx
spec:
type: NodePort # ClusterIP Or LoadBalancer
selector:
app: nginx
ports:
- name: http
port: 80
targetPort: 80

View File

@@ -0,0 +1,49 @@
---
apiVersion: v1
kind: Service
metadata:
labels:
app: nginx
name: nginx
spec:
clusterIP: None
ports:
- name: web
port: 80
selector:
app: nginx
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: simple-stateful-set
spec:
replicas: 3 # the default is 1
selector:
matchLabels:
app: nginx # has to match .spec.template.metadata.labels
serviceName: "nginx"
template:
metadata:
labels:
app: nginx # has to match .spec.selector.matchLabels
spec:
terminationGracePeriodSeconds: 10
containers:
- image: nginx
name: nginx
ports:
- containerPort: 80
name: web
volumeMounts:
- mountPath: /usr/share/nginx/html
name: www
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
storageClassName: "longhorn "

View File

@@ -0,0 +1,90 @@
# **Dozzle Real-Time Docker Log Viewer**
## **Overview**
**Dozzle** is an open-source, lightweight, web-based log viewer designed to simplify monitoring and debugging Docker containers. Sponsored by **Docker OSS** and actively maintained by **Amir Raminfar**, Dozzle provides real-time log streaming with an intuitive and efficient UI.
Optimized for developers, DevOps engineers, and system administrators, Dozzle offers:
* **Live log streaming** directly from containers
* **Search and filtering capabilities**
* **JSON log support** with intelligent color coding
* **A minimal footprint**, making it ideal for any environment
Dozzle is distributed under the **MIT license**, ensuring free and open use across development and production workflows.
---
## **Key Features**
### **🔹 Real-Time Log Streaming**
Instantly view logs as they are generated, enabling faster debugging and container monitoring.
### **🔹 Web-Based Interface**
No need for additional CLI commands—open your browser and start exploring logs immediately.
### **🔹 Lightweight & Fast**
Runs with minimal resource usage, suitable for both development setups and production Docker hosts.
### **🔹 Simple Installation**
Deployable with a single Docker command or via Docker Compose. No complex setup required.
### **🔹 Secure Local Access**
Works by reading the Docker daemon socket (`/var/run/docker.sock`), ensuring direct and secure interaction with local containers.
---
## **Installation & Setup**
### **Using Docker CLI (Recommended)**
The simplest way to run Dozzle is by mounting the Docker socket file:
* The Docker socket is typically located at:
**`/var/run/docker.sock`**
* Dozzle listens on **port 8080** by default, but you can remap it using `-p` if needed.
```bash
docker run -d \
--name dozzle \
-p 8080:8080 \
-v /var/run/docker.sock:/var/run/docker.sock \
amir20/dozzle:latest
```
Once running, access Dozzle at:
➡️ **[http://localhost:8080](http://localhost:8080)**
---
## **Using Docker Compose**
For environments managed with Compose, use the following configuration:
```yaml
services:
dozzle:
image: amir20/dozzle:latest
volumes:
- /var/run/docker.sock:/var/run/docker.sock
ports:
- 8080:8080
```
Start the service:
```bash
docker compose up -d
```
---
## **Swarm Deployment**
Dozzle can also be deployed as a Swarm service for distributed environments.

View File

@@ -0,0 +1,153 @@
# **Dozzle Deployment Modes**
Dozzle offers multiple deployment modes to support a variety of architectures—from single-host setups to distributed multi-node clusters. Depending on your environment, you can run Dozzle in one of the following modes:
* **Standard Mode (default)** Local logs from the Docker engine
* **Agent Mode** Remote hosts exposed securely via TLS
* **Swarm Mode** Distributed mesh network for Docker Swarm clusters
* **Hybrid (Swarm + Standalone Agents)** Combine both for maximum flexibility
This section explains how each mode works and provides production-ready deployment examples.
---
# **1. Agent Mode**
Agent mode allows a Dozzle instance to expose its hosts container logs to other Dozzle servers over a secure **TLS-encrypted channel**. This is ideal for:
* Managing multiple remote Docker hosts
* Viewing logs from distributed machines in a single Dozzle UI
* Secure cross-host communication without VPNs
In agent mode, Dozzle runs with the `agent` subcommand and listens for remote connections.
---
## **Deploying a Dozzle Agent**
```yaml
services:
dozzle-agent:
image: amir20/dozzle:latest
command: agent
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
ports:
- 7007:7007
```
### **Customizing Agent Identity**
Agents can be assigned human-readable names using the `DOZZLE_HOSTNAME` variable:
```yaml
environment:
- DOZZLE_HOSTNAME=my-special-name
```
---
## **Connecting a Dozzle Instance to One or More Agents**
Define the remote agents in the `DOZZLE_REMOTE_AGENT` variable. Multiple agents should be comma-separated.
```yaml
services:
dozzle:
image: amir20/dozzle:latest
environment:
- DOZZLE_REMOTE_AGENT=agent1:7007,agent2:7007
ports:
- 8080:8080
```
Once launched, the UI will display the remote agent hosts alongside local containers.
---
# **2. Swarm Mode**
Dozzle supports a special **Swarm Mode** designed for distributed Docker Swarm environments. When enabled, Dozzle automatically forms a **secure, fully encrypted mTLS mesh network** between all Dozzle nodes in the cluster.
### **Key features of Swarm Mode**
* Automatic discovery of all Dozzle instances
* Encrypted communication using mTLS
* Support for grouping logs by:
* Docker stacks (`com.docker.stack.namespace`)
* Docker Compose projects (`com.docker.compose.project`)
* Swarm services (`com.docker.swarm.service.name`)
Swarm Mode is the recommended deployment method for multi-node clusters.
---
## **Deploying Dozzle in Swarm Mode**
Use `mode: global` to deploy Dozzle on every node:
```yaml
services:
dozzle:
image: amir20/dozzle:latest
environment:
- DOZZLE_MODE=swarm
volumes:
- /var/run/docker.sock:/var/run/docker.sock
ports:
- 8080:8080
networks:
- dozzle
deploy:
mode: global
networks:
dozzle:
driver: overlay
```
### **Important:**
**Swarm mode cannot use Docker socket-proxy.**
This is a Docker limitation—Swarm services cannot directly access individual proxy instances, and Dozzle requires that direct access.
---
# **3. Adding Standalone Agents to Swarm Mode (v8.8.x+)**
Starting with **v8.8.x**, Dozzle allows you to mix **standalone agents** with a **Swarm-mode deployment**. Remote agents will appear as additional nodes in the Dozzle UI.
Example configuration:
```yaml
services:
dozzle:
image: amir20/dozzle:latest
environment:
- DOZZLE_MODE=swarm
- DOZZLE_REMOTE_AGENT=agent:7007
volumes:
- /var/run/docker.sock:/var/run/docker.sock
ports:
- 8080:8080
networks:
- dozzle
deploy:
mode: global
networks:
dozzle:
driver: overlay
```
This hybrid approach is ideal when part of your infrastructure runs in Swarm and other nodes run standalone Docker.
---
# **Summary**
| Mode | Best For | Key Features |
| --------------------------- | -------------------------------- | ------------------------------------ |
| **Standard** | Single-host setups | Local logs, simplest deployment |
| **Agent Mode** | Remote nodes, non-Swarm clusters | TLS-secured remote access |
| **Swarm Mode** | Multi-node Swarm clusters | mTLS mesh networking, auto-discovery |
| **Hybrid (Swarm + Agents)** | Mixed environments | Combine Swarm nodes + remote agents |

View File

@@ -0,0 +1,153 @@
# 📘 MariaDB Replication Setup Guide
This guide walks you through setting up **Master-Slave Replication** using MariaDB.
---
## 🛠️ Step 1: Install MariaDB
Install MariaDB on both the **master** and **slave** servers.
```bash
sudo apt update
sudo apt install mariadb-server
```
---
## ⚙️ Step 2: Configure the Master Server
Edit the MariaDB configuration file:
```bash
sudo vim /etc/mysql/mariadb.conf.d/50-server.cnf
```
Add or modify the following under the `[mariadb]` section:
```cnf
[mariadb]
log-bin
server_id=1
log-basename=master1
binlog-format=mixed
```
🔁 **Also**, change the `bind-address` to allow external connections:
```cnf
bind-address = 0.0.0.0
```
---
## 🔐 Step 3: Create Replication User
Access the MariaDB shell:
```bash
sudo mysql
```
Then run:
```sql
CREATE USER 'radin'@'%' IDENTIFIED BY '123';
GRANT REPLICATION SLAVE ON *.* TO 'radin'@'%';
FLUSH PRIVILEGES;
```
---
## 📈 Step 4: Check Master Status
Still inside the MariaDB shell, run:
```sql
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;
```
Take note of:
* `File`: The binary log file name (e.g., `db-master1-bin.000003`)
* `Position`: The log position (e.g., `347`)
Then, in a separate terminal, unlock tables:
```sql
UNLOCK TABLES;
```
---
## 🛠️ Step 5: Configure the Slave Server
Edit the config file on the slave:
```bash
sudo vim /etc/mysql/mariadb.conf.d/50-server.cnf
```
Set the following:
```cnf
[mariadb]
log-bin
server_id=2
log-basename=slave1
binlog-format=mixed
```
---
## 🔄 Step 6: Set Up Slave Replication
Access the MariaDB shell on the slave server:
```bash
sudo mysql
```
Run the following (replace values as needed):
```sql
CHANGE MASTER TO
MASTER_HOST='192.168.6.160',
MASTER_USER='radin',
MASTER_PASSWORD='123',
MASTER_PORT=3306,
MASTER_LOG_FILE='db-master1-bin.000003',
MASTER_LOG_POS=347,
MASTER_CONNECT_RETRY=10;
```
Start the slave:
```sql
START SLAVE;
```
Check slave status:
```sql
SHOW SLAVE STATUS\G
```
Look for:
* `Slave_IO_Running: Yes`
* `Slave_SQL_Running: Yes`
---
## 🔁 Resetting the Slave
To reset the slave configuration:
```sql
STOP SLAVE;
RESET SLAVE ALL;
```

View File

@@ -0,0 +1,22 @@
import mysql.connector
# Connect to the database
conn = mysql.connector.connect(
host="localhost",
user="your_user",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
# Run a query
cursor.execute("SELECT * FROM your_table;")
# Fetch and print results
for row in cursor.fetchall():
print(row)
# Close connection
cursor.close()
conn.close()

View File

@@ -0,0 +1,60 @@
### 📌 Echo Basic Usage
```bash
echo Hello, world!
```
**Output:**
```
Hello, world!
```
---
### 💡 Common Use Cases
1. **Print plain text:**
```bash
echo This is a message
```
2. **Print environment variables (Linux/macOS):**
```bash
echo $HOME
```
3. **Print environment variables (Windows):**
```cmd
echo %USERNAME%
```
4. **Write to a file:**
```bash
echo "Log entry" >> logfile.txt
```
5. **Suppress newline (Unix/Linux):**
```bash
echo -n "No newline"
```
6. **Use with escape characters (Unix/Linux):**
```bash
echo -e "Line1\nLine2"
```
---
### ⚠️ Notes
* On **Unix-like systems**, `echo` is a shell builtin (e.g., in `bash`, `sh`).
* On **Windows**, its a command in `cmd.exe`.
* Behavior may vary slightly between environments. For complex text handling, consider using `printf` instead in Unix/Linux.

View File

@@ -0,0 +1,91 @@
# 🖥️ Bash Operators
A quick reference guide to essential bash command operators and their usage.
---
## `>` — **Write to File (Overwrite)**
This operator **creates a new file** or **overwrites** the contents of an existing file.
```bash
echo "Hi" > file1
```
📄 *Creates* `file1` and writes `"Hi"` into it. If `file1` already exists, its content is replaced.
---
## `>>` — **Append to File**
Adds content to the **end of an existing file** without deleting what's already there.
```bash
echo "Hi" >> file1
```
📝 *Appends* `"Hi"` to the end of `file1`.
---
## `&&` — **AND Operator**
Runs the **second command only if the first succeeds**.
```bash
apt update && apt upgrade
```
🔗 `apt upgrade` runs only if `apt update` completes successfully.
---
## `;` — **Run Multiple Commands**
Executes **commands sequentially**, regardless of success or failure.
```bash
echo "Hi" > file1 ; cat file1
```
🔄 Both commands are executed one after the other.
---
## `|` — **Pipe Operator**
Takes the **output of the command on the left** and **uses it as input for the command on the right**.
```bash
ls -l | grep "txt"
```
🔗 Passes the output of `ls -l` to `grep "txt"` to filter and display only files containing "txt".
---
## `*` — **Wildcard (All Matching Files)**
Matches **all files** that meet the pattern.
```bash
cat file*
```
🌐 Displays the contents of all files starting with `file`.
---
## `[ ... ]` — **Specific Character Matching**
Reads files that match specific characters at the position defined in brackets.
```bash
cat file[1,2,3]
```
📚 Reads `file1`, `file2`, and `file3` (if they exist). Equivalent to:
```bash
cat file1 file2 file3
```

View File

@@ -0,0 +1,95 @@
# 🧾 Linux Exit Codes Cheat Sheet
Every command in Linux returns an **exit status code** upon completion. You can check this code using:
```bash
command
echo $?
```
These codes are helpful for debugging scripts or understanding command behavior.
---
## ✅ Common Exit Codes & Their Meanings
| Exit Code | Meaning |
| --------- | ----------------------------------------------- |
| `0` | ✅ Success |
| `1` | ❌ General Error |
| `2` | ⚠️ Misuse of Shell Built-in (bad options, etc.) |
| `126` | 🚫 Command Found but Cannot Execute |
| `127` | ❓ Command Not Found |
| `130` | ⌨️ Terminated by `Ctrl+C` |
| `137` | 💀 Killed (e.g., `kill -9`) |
---
## 🔍 Exit Code Examples
### `0` — Success
```bash
echo "Hello"
echo $? # ➜ 0
```
---
### `1` — General Error
```bash
grep "text" non_existing_file.txt
echo $? # ➜ 1
```
---
### `2` — Misuse of Shell Built-in
```bash
ls --wrongoption
echo $? # ➜ 2
```
---
### `126` — Command Found but Not Executable
```bash
touch myscript.sh
chmod -x myscript.sh
./myscript.sh
echo $? # ➜ 126
```
---
### `127` — Command Not Found
```bash
nonexistentcommand
echo $? # ➜ 127
```
---
### `130` — Script Terminated by `Ctrl+C`
```bash
sleep 10
# Press Ctrl+C while it sleeps
echo $? # ➜ 130
```
---
### `137` — Killed by `kill -9`
```bash
sleep 100 &
kill -9 $!
wait
echo $? # ➜ 137
```

View File

@@ -0,0 +1,80 @@
# 🌟 Understanding the **Shebang** (`#!`)
A **shebang** (also known as a **hashbang**) is the character sequence:
```
#!<interpreter_path>
```
It appears **at the very top** of a script file and tells the operating system **which interpreter** should execute the file.
---
## 📌 What It Looks Like
```bash
#!/usr/bin/python3
print("Hello, world!")
```
### Breakdown:
* `#!` — This is the **shebang**.
* `/usr/bin/python3` — This tells the OS to use **Python 3** to run the script.
---
## 🧠 Why It Matters
When you make a script **executable**:
```bash
chmod +x script.py
```
And run it directly:
```bash
./script.py
```
The OS reads the **shebang line** and uses the specified interpreter to execute the file. This works for any script type, like:
```bash
./script.sh # for a Bash script
./script.py # for a Python script
```
---
## 💡 Common Shebang Examples
| Language | Shebang |
| -------- | --------------------- |
| Bash | `#!/bin/bash` |
| Python | `#!/usr/bin/python3` |
| Node.js | `#!/usr/bin/env node` |
| Perl | `#!/usr/bin/perl` |
---
## 🚀 Pro Tip: Use `env` for Portability
Instead of hardcoding the interpreter path, use:
```bash
#!/usr/bin/env python3
```
This makes your script more **portable**, as it locates `python3` using the user's `PATH` environment.
---
## ✅ Summary
* The **shebang** defines the script interpreter.
* Place it on **the first line** of your script.
* Make the script executable with `chmod +x`.
* Use `/usr/bin/env` for better portability across systems.

View File

@@ -0,0 +1,77 @@
# 🧮 Bash Variables
In **Bash scripting**, **variables** are used to store values like text or numbers. They allow scripts to be dynamic and reusable.
---
## ✍️ Defining Variables
Variables are created **without spaces** around the `=` sign:
```bash
user="ali"
age=21
```
* `user` is assigned the value `"ali"`.
* `age` is assigned the value `21`.
> ✅ Tip: No `let` or `var` is needed like in other programming languages.
---
## 📢 Using Variables
You can **access variables** by prefixing them with `$`:
```bash
user="radin"
echo "Welcome, $user"
```
**Output:**
```
Welcome, radin
```
---
## 🧪 Full Script Example
Here's a complete Bash script using variables:
```bash
#!/bin/bash
user="mmd"
age=25
echo "$user is $age years old."
```
**Output:**
```
mmd is 25 years old.
```
---
## 📌 Notes
* Variable names are **case-sensitive** (`User` and `user` are different).
* Avoid spaces around `=` when assigning.
* Enclose variable values in quotes if they contain spaces.
---
## ✅ Summary
| Task | Syntax |
| --------------- | ---------------------------- |
| Define variable | `name="value"` |
| Use variable | `$name` |
| Print value | `echo "$name"` |
| With script | Use `#!/bin/bash` at the top |

View File

@@ -0,0 +1,77 @@
# 📝 Bash `read` Command
The `read` command in **Bash** is used to **take user input** from the terminal. It stores the input into one or more **variables**.
---
## 🔤 Basic Syntax
```bash
read [options] variable
```
---
## 📘 Simple Example
```bash
echo "What is your name?"
read name
echo "Hello, $name!"
```
* `read name` takes input from the user and stores it in the variable `name`.
* The script then greets the user with the stored input.
---
## 🎯 Prompt Inline with `-p`
```bash
read -p "What is your name? " name
echo "Hello, $name!"
```
* `-p` allows you to show the prompt **on the same line** as the user input.
---
## 🔒 Silent Input with `-s` (e.g., Passwords)
```bash
read -sp "Enter your password: " password
echo $password >> pass.txt
```
* `-s` hides the users input while typing (useful for passwords).
* `>> pass.txt` appends the password to a file (⚠️ For demonstration only—**avoid storing passwords in plain text**!).
---
## ⏳ Set a Timeout with `-t`
```bash
read -t 5 -p "Enter something in 5 seconds: " data
```
* `-t 5` gives the user **5 seconds** to input something.
* If no input is given in time, the script moves on.
---
## 🧠 Summary Table
| Option | Description | Example |
| ------ | --------------------- | ---------------------------- |
| `-p` | Show prompt inline | `read -p "Name: " name` |
| `-s` | Silent (hidden input) | `read -sp "Password: " pass` |
| `-t` | Timeout (in seconds) | `read -t 10 var` |
---
## ✅ Quick Recap
* Use `read` to get **interactive input** in your Bash scripts.
* Combine options (`-sp`, `-tp`, etc.) for powerful input control.
* Avoid exposing sensitive data—use secure handling practices.

175
Linux/Bash Script/07-If.md Normal file
View File

@@ -0,0 +1,175 @@
# 🐚 Bash `if` Statement Guide
Conditional statements in Bash allow you to execute code based on specific conditions. Below is a comprehensive guide to `if` statements, their syntax, comparison operators, and examples.
---
## 🔹 Basic Syntax
```bash
if [[ condition ]]; then
# commands if condition is true
fi
```
### With `else`
```bash
if [[ condition ]]; then
# true
else
# false
fi
```
### With `elif`
```bash
if [[ condition1 ]]; then
# condition1 is true
elif [[ condition2 ]]; then
# condition2 is true
else
# none matched
fi
```
---
## ⚙️ Operators
### 🔢 Numeric Comparison
| Operator | Meaning |
| -------- | ---------------- |
| `-eq` | Equal to |
| `-ne` | Not equal |
| `-lt` | Less than |
| `-le` | Less or equal |
| `-gt` | Greater than |
| `-ge` | Greater or equal |
### 🔤 String Comparison
| Operator | Meaning |
| -------- | ---------------- |
| `==` | Equal to |
| `!=` | Not equal |
| `-z` | Empty string |
| `-n` | Not empty string |
### 📁 File Tests
| Operator | Meaning |
| -------- | ------------------ |
| `-e` | File exists |
| `-d` | Directory exists |
| `-r` | File is readable |
| `-w` | File is writable |
| `-x` | File is executable |
---
## 🧪 Practical Examples
### Example 1: Number Check
```bash
read -p "Enter Your Number: " number
if [[ $number -eq 0 ]]; then
echo "Zero"
elif [[ $number -ge 1 ]]; then
echo "Positive"
else
echo "Negative"
fi
```
---
### Example 2: Number Range with Error Handling
```bash
read -p "Enter Your Number: " number
if [[ $number -eq 0 ]]; then
echo "Zero"
elif [[ $number -ge 1 ]]; then
echo "Positive"
elif [[ $number -le -1 ]]; then
echo "Negative"
else
echo "Error: Invalid input"
exit 1
fi
```
---
### Example 3: String Check
```bash
read -p "Enter Your String: " str
if [[ -n $str ]]; then
if [[ $str == "hello" ]]; then
echo "Hi"
elif [[ $str != "hello" ]]; then
echo "Ok"
fi
else
echo "Nothing to read"
exit 1
fi
```
---
### Example 4: File Existence
```bash
file="script.sh"
if [[ -e $file ]]; then
echo "File exists"
else
touch "$file"
echo "File created"
fi
```
---
### Example 5: File Permission Check
```bash
file="script50.sh"
if [[ -e $file ]]; then
echo "File exists"
if [[ ! -x $file ]]; then
chmod +x "$file"
echo "Executable permission added"
fi
if [[ ! -r $file ]]; then
chmod +r "$file"
echo "Read permission added"
fi
else
touch "$file"
echo "File created"
fi
```
---
## ✅ Tips
* Always quote variables: `"$var"` to prevent word splitting.
* Use `[[ ... ]]` for conditional tests (preferred over `[ ... ]`).
* Prefer `read -r` to avoid backslash escapes.

View File

@@ -0,0 +1,90 @@
# 🐚 Bash Function Syntax & Examples
Bash functions allow you to group reusable logic in shell scripts. Below are clear examples and explanations to help you understand how to define and use them effectively.
---
## 🔧 Defining a Function
You can define a Bash function in two main ways:
### Option 1: Classic Syntax
```bash
function_name () {
# commands
}
```
### Option 2: With the `function` Keyword
```bash
function function_name () {
# commands
}
```
> 💡 Both syntaxes are valid. The use of the `function` keyword is optional and mostly stylistic.
---
## 📥 Passing Arguments
Bash functions accept arguments just like scripts. These are accessed via `$1`, `$2`, etc.
### Example: Single Argument
```bash
func1() {
echo "Arg: $1"
}
func1 "Test"
```
**Output:**
```
Arg: Test
```
---
## Multiple Arguments & Calculation
You can perform operations using passed arguments, like arithmetic:
```bash
summery() {
local sum=$(( $1 + $2 ))
echo $sum
}
summery 5 7
```
**Output:**
```
12
```
> 📌 `local` ensures `sum` is scoped within the function.
---
## ✅ Best Practices
* Use `local` to avoid polluting the global scope.
* Quote variables when dealing with strings.
* Use descriptive names for clarity.
---
## 🧪 Try It Yourself
Add these examples to a `.sh` file and run it with:
```bash
bash script.sh
```

126
Linux/Bash Script/09-For.md Normal file
View File

@@ -0,0 +1,126 @@
# Bash `for` Loop Cheat Sheet
A clear and concise reference for using `for` loops in Bash, with syntax variations, examples, and best practices.
---
## 1. Basic `for` Loop (List Iteration)
Iterates over a fixed list of items.
**Syntax:**
```bash
for VARIABLE in ITEM1 ITEM2 ITEM3 ...
do
commands
DONE
done
```
**Example:**
```bash
for color in red green blue
do
echo "Color: $color"
done
```
*Output:*
```
Color: red
Color: green
Color: blue
```
---
## 2. Numeric Iteration Using a List
When you explicitly list out numbers.
**Example:**
```bash
for i in 1 2 3 4 5
do
echo "Number: $i"
done
```
*Output:*
```
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
```
---
## 3. C-style `for` Loop (Arithmetic)
Similar to loops in C-style languages: initialize, condition, increment.
**Syntax:**
```bash
for (( init; condition; increment ))
do
commands
ndone
```
**Example:**
```bash
for (( i=0; i<5; i++ ))
do
echo "Index: $i"
done
```
*Output:*
```
Index: 0
Index: 1
Index: 2
Index: 3
Index: 4
```
---
## 4. Looping Over Files (Globbing)
Use shell glob patterns to iterate over matching filenames.
**Example:**
```bash
for file in *.txt
do
echo "Found text file: $file"
done
```
```
# If the directory contains a.txt and notes.txt, output might be:
Found text file: a.txt
Found text file: notes.txt
```
---
## Summary
| Style | Purpose | Notes |
| ----------------- | ------------------------------------------ | ------------------------------------- |
| `for var in list` | Iterate over a static list or glob results | Most common in shell scripting |
| `for (( ... ))` | Numeric / arithmetic loops | C-style syntax, powerful for counters |

View File

@@ -0,0 +1,138 @@
# Bash `while` Loop Guide
A clear, concise, and visually pleasant reference for using `while` loops in Bash.
---
## 1. Overview
The `while` loop in Bash repeatedly executes a block of commands **as long as a condition evaluates to true**. It is a fundamental control structure for iteration when the number of repetitions is not known in advance.
### General form
```bash
while [ condition ]
do
command1
command2
...
done
```
* The condition is evaluated before each iteration. If it returns a zero (truthy) exit status, the loop body runs. Otherwise, the loop exits.
* Square brackets (`[ ... ]`) are a synonym for the `test` command; spacing matters.
---
## 2. Examples
### 2.1 Simple counter
Counts from 1 to 5 and prints the current value.
```bash
counter=1
while [ $counter -le 5 ]
do
echo "Counter: $counter"
((counter++))
done
```
**What it does:**
* Initializes `counter` to 1.
* The loop continues while `counter` is less than or equal to 5.
* Prints and increments the counter each iteration.
### 2.2 Waiting for a file to appear
Polls for the existence of `/tmp/myfile.txt` once per second.
```bash
while [ ! -f /tmp/myfile.txt ]
do
echo "Waiting for file..."
sleep 1
done
echo "File exists!"
```
**What it does:**
* Checks if the file does **not** exist (`! -f`).
* Sleeps for one second between checks to avoid busy-waiting.
* When the file appears, exits the loop and prints confirmation.
### 2.3 Interactive prompt with exit condition
Keeps prompting the user until they type `q`.
```bash
while true
do
read -p "Type 'q' to quit: " input
if [ "$input" = "q" ]; then
break
fi
done
```
**What it does:**
* Uses an infinite loop (`while true`).
* Prompts the user each time.
* Exits the loop when the input equals `q` using `break`.
---
## 3. Tips & Best Practices
* **Quote variables** to avoid word splitting and issues when they are empty: `[ "$foo" = "bar" ]`.
* **Use arithmetic expressions** with `(( ... ))` when dealing with numbers (`((counter++))` is more concise than `counter=$((counter + 1))`).
* **Avoid busy loops:** if waiting on external state, insert a `sleep` to reduce CPU usage.
* **Use `set -u` and `set -e`** in scripts to catch undefined variables and stop on errors, but be careful when using them with conditional tests.
* **Test conditions explicitly:** e.g., use `-f`, `-d`, `-r`, `-s`, etc., for file-related checks.
---
## 4. Common Pitfalls
* Missing spaces inside `[ ]``while [$counter -le 5]` is invalid; it must be `[ $counter -le 5 ]`.
* Forgetting to initialize loop variables, leading to unexpected behavior when using them in tests.
* Using `read` without handling empty input; consider providing a default or validating.
* Infinite loops without an exit strategy (e.g., missing `break` or condition never false).
---
## 5. Variations
* **Until loop:** opposite of `while` — runs until a condition becomes true.
```bash
until [ -f /tmp/myfile.txt ]
do
echo "Waiting..."
sleep 1
```
done
- **Command-based condition:** you can use any command whose exit status matters.
```bash
while ping -c1 example.com >/dev/null 2>&1
do
echo "Host is reachable"
sleep 5
done
````
---
## 6. Summary
Use `while` loops when the number of iterations depends on dynamic conditions (user input, file existence, external services). Combine with proper quoting, sleeping, and exit strategies to write robust and readable scripts.

View File

@@ -0,0 +1,84 @@
# 🐧 Linux Runlevels Guide
This guide provides a concise overview of traditional **runlevels** in Linux systems, particularly for **Red Hat** and **Debian**-based distributions. Runlevels define specific states of system operation, historically managed by the `init` system.
---
## 🔄 System Boot Sequence
```plaintext
BIOS → Bootloader → Kernel → init
```
* **BIOS**: Performs hardware checks via **POST** (Power-On Self Test).
* **Bootloader**: Loads the kernel.
* **Kernel**: Initializes system and mounts the root filesystem.
* **init**: Launches system processes based on the selected runlevel.
---
## 📊 Runlevels Comparison
| Runlevel | Description | Red Hat | Debian |
| -------- | ----------------------------------- | ---------------- | --------------- |
| 0 | Halt / Shutdown | ✅ Supported | ✅ Supported |
| 1 | Single-User Mode | ✅ Supported | ✅ Supported |
| 2 | Multi-User (No Network) | ❌ (Includes Net) | ✅ Supported |
| 3 | Multi-User (Network, No GUI) | ✅ Supported | ✅ Supported |
| 4 | User-Defined / Custom | ✅ Supported | ✅ Supported |
| 5 | GUI Mode / *(Halt on some systems)* | ✅ GUI Mode | ⚠️ Custom/Halt? |
| 6 | Reboot | ✅ Supported | ✅ Supported |
> 💡 **Notes**:
> • **Runlevel 5** on Red Hat typically launches a full graphical environment (GUI).
> • On Debian, runlevels 25 are often configured identically and can be customized.
> • Runlevel behavior is configurable via `/etc/inittab` (SysVinit systems).
---
## 🔧 Useful Commands
### ✅ Check Current Runlevel
```bash
runlevel
```
### 🔁 Change Runlevel
```bash
telinit <runlevel>
```
or
```bash
init <runlevel>
```
> ⚠️ **Caution**: Switching runlevels may stop services or terminate user sessions. Use carefully on production systems.
---
## 🚀 Modern Systems: systemd Targets
Most modern Linux distributions use **systemd**, which replaces runlevels with **targets**.
| Runlevel | systemd Target |
| -------- | ------------------- |
| 0 | `poweroff.target` |
| 1 | `rescue.target` |
| 3 | `multi-user.target` |
| 5 | `graphical.target` |
| 6 | `reboot.target` |
### 📌 Common systemd Commands
```bash
# Show default target
systemctl get-default
# Change to graphical mode
systemctl isolate graphical.target
```

View File

@@ -0,0 +1,59 @@
# 📁 Linux Directory Structure & Basic Commands
This document provides an overview of important Linux directories, their types, and essential file management commands.
---
## 📂 Directory Types
| Type | Description |
| ----------- | ----------------------------------------------------------------------------------- |
| **Virtual** | Do not reside on disk; dynamically generated by the system (e.g., `/proc`, `/sys`). |
| **Normal** | Standard directories that store files and data on disk. |
---
## 🗂️ Common Linux Directories
| Directory | Type | Description |
| --------- | ------- | ----------------------------------------------------------- |
| `/etc` | Normal | System configuration files |
| `/opt` | Normal | Optional or third-party software packages |
| `/bin` | Normal | Essential binary executables for all users |
| `/sbin` | Normal | System binaries, typically for administrative tasks |
| `/lib` | Normal | Shared libraries and kernel modules |
| `/home` | Normal | User home directories |
| `/proc` | Virtual | Kernel and process information (virtual files) |
| `/srv` | Normal | Data for services provided by the system (e.g., web, FTP) |
| `/sys` | Virtual | Kernel devices and system information |
| `/usr` | Normal | Secondary hierarchy: programs, libraries, and documentation |
| `/var` | Normal | Variable data: logs, mail, print spool, temporary files |
| `/dev` | Virtual | Device files (e.g., disk, USB, terminals) |
| `/mnt` | Normal | Mount point for temporary filesystems |
| `/boot` | Normal | Boot loader files, kernel images |
---
## 🛠️ Basic File & Directory Commands
| Command | Description |
| ------- | ---------------------------------------- |
| `cd` | Change directory |
| `ls` | List directory contents |
| `rm` | Remove files or directories |
| `mkdir` | Create a new directory |
| `touch` | Create an empty file or update timestamp |
| `cp` | Copy files or directories |
| `mv` | Move or rename files or directories |
### 📘 Examples
```bash
cd /etc # Navigate to /etc directory
ls -l # List files in long format
rm file.txt # Delete file.txt
mkdir new_folder # Create a directory named 'new_folder'
touch file.txt # Create a new empty file
cp file1.txt file2.txt # Copy file1.txt to file2.txt
mv file.txt /home/user/ # Move file.txt to another directory
```

View File

@@ -0,0 +1,49 @@
# 📦 Linux Libraries & Package Management
This guide provides a quick overview of **library types**, **package sources**, and **Debian-based package management** commands using `apt`.
---
## 📚 Library Types
Linux supports two main types of libraries:
1. **Static Libraries (`.a`)**
- Linked at **compile-time**
- Included in the final binary
- Larger file size, faster execution
2. **Shared Libraries (`.so`)**
- Linked at **run-time**
- Saved separately from the binary
- Saves space and allows updates without recompiling
---
## 📦 Package Sources
### ✅ Official Packages
Provided and maintained by the distribution (e.g., Debian, Ubuntu, Red Hat).
### 🌐 Third-Party Packages
Created by external developers or organizations. Use with caution and verify trustworthiness.
---
## 🏬 Linux Package Managers
### 📦 Debian-based Systems
- **Package Manager**: `apt`
- **Low-level Tool**: `dpkg`
- **Package Format**: `.deb`
### 📦 Red Hat-based Systems
- **Package Manager**: `yum` or `dnf` (newer)
- **Low-level Tool**: `rpm`
- **Package Format**: `.rpm`
---
## 🌍 Package Mirrors
Mirrors are alternative download sources for package repositories, often closer geographically for faster updates.

View File

@@ -0,0 +1,94 @@
# 📦 `dpkg` Debian Package Manager
`dpkg` is the package manager for Debian-based Linux distributions. It is used to install, remove, and manage `.deb` packages directly.
### 📘 Basic Syntax
```bash
dpkg [<option>...] <command>
```
---
## 🌐 Finding Packages
You can browse and search for Debian packages at [pkgs.org](https://pkgs.org).
---
## 📋 Listing Installed Packages
```bash
dpkg -l
dpkg --list
```
---
## 📥 Installing a Package
```bash
dpkg -i <package.deb>
dpkg --install <package.deb>
```
> ⚠️ If there are missing dependencies, run:
```bash
apt install -f
```
---
## 📂 Viewing Package Contents
```bash
dpkg -c <package.deb>
dpkg --contents <package.deb>
```
---
## Getting Package Info
```bash
dpkg -I <package.deb>
dpkg --info <package.deb>
```
---
## 📁 Listing Installed Files
```bash
dpkg -L <package-name>
dpkg --listfiles <package-name>
```
---
## 🧹 Removing a Package (and its config files)
```bash
dpkg -p <package-name>
dpkg --purge <package-name>
```
---
## 📝 Checking Package Status
```bash
dpkg -s <package-name>
dpkg --status <package-name>
```
---
## 🔧 Reconfiguring a Package
```bash
dpkg-reconfigure <package-name>
```

View File

@@ -0,0 +1,148 @@
# 📦 Managing Packages with `apt` on Debian/Ubuntu
The `apt` (Advanced Package Tool) command-line utility allows you to manage software on Debian-based Linux systems. Below are essential `apt` commands grouped by purpose, with clear explanations for each.
---
## 🔄 1. Updating and Upgrading the System
### `sudo apt update`
Fetches the latest package lists from repositories. This ensures your system is aware of the newest available versions of packages.
```bash
sudo apt update
```
---
### `apt upgrade`
Installs the newest versions of all installed packages based on the updated package lists. It does **not** remove or install any other packages.
```bash
apt upgrade
```
---
## 🔍 2. Searching and Viewing Packages
### `apt show <package>`
Displays detailed information about a specific package, including version, dependencies, description, and more.
```bash
apt show <package>
```
---
### `apt list`
Lists packages based on various filters (e.g., installed, upgradable, available). Running it without arguments shows all packages.
```bash
apt list
```
---
### `apt-cache search <pkg name>`
Searches the package cache for packages matching the given name or description. Useful for discovering packages related to a topic or function.
```bash
apt-cache search <pkg name>
```
---
## 📥 3. Installing and Reinstalling Packages
### `apt install <pkg name>`
Installs a package and its dependencies from the repositories.
```bash
apt install <pkg name>
```
---
### `apt reinstall <package>`
Reinstalls the specified package. This is useful if files from a package are accidentally deleted or corrupted.
```bash
apt reinstall <package>
```
---
## ❌ 4. Removing Packages
### `apt remove <package>`
Removes the specified package but **retains configuration files**. Useful when planning to reinstall later without losing settings.
```bash
apt remove <package>
```
---
### `apt purge <package>`
Completely removes the package **along with its configuration files**. Use when you want a clean uninstallation.
```bash
apt purge <package>
```
---
### `apt autoremove`
Automatically removes packages that were installed as dependencies but are no longer needed.
```bash
apt autoremove
```
---
## 🛠️ 5. Advanced Package Handling
### `apt install -f`
Attempts to **fix broken dependencies** by installing missing packages. Often used after a failed install.
```bash
apt install -f
```
---
### `apt install --download-only <package>`
Downloads a package without installing it. The downloaded `.deb` files are saved in:
```bash
/var/cache/apt/archives/
```
Example:
```bash
apt install --download-only <package>
```
---
## ✅ Final Notes
* Always start with `sudo apt update` before any install or upgrade.
* Use `apt-cache search` when unsure of a packages exact name.
* Be cautious with `purge` as it deletes config files too.

View File

@@ -0,0 +1,156 @@
# 🍽️ Managing Packages with `yum` on RHEL/CentOS
`yum` (Yellowdog Updater, Modified) is the traditional package manager for RPM-based Linux distributions such as **Red Hat Enterprise Linux (RHEL)** and **CentOS**. Below is a breakdown of commonly used `yum` commands, categorized and explained in detail.
---
## 🔄 1. Updating the System
### `yum update`
Fetches the latest package metadata and installs available updates for all packages currently installed on the system.
```bash
yum update
```
---
### `yum upgrade`
Performs the same function as `yum update`. In older versions of `yum`, `upgrade` was used for more aggressive upgrades, but in recent versions, they are functionally equivalent.
```bash
yum upgrade
```
---
## 📥 2. Installing and Reinstalling Packages
### `yum install <pkg-name>`
Installs a new package along with any required dependencies.
```bash
yum install <pkg-name>
```
---
### `yum reinstall <pkg-name>`
Reinstalls an already installed package, which is useful if system files have been corrupted or modified.
```bash
yum reinstall <pkg-name>
```
---
### `yum localinstall <file-dir>`
Installs a `.rpm` package from a local file path while resolving dependencies using remote repositories.
```bash
yum localinstall <file-dir>
```
---
## ❌ 3. Removing Packages
### `yum remove <pkg-name>`
Uninstalls the specified package from the system, including any dependencies no longer required.
```bash
yum remove <pkg-name>
```
---
## 🔍 4. Querying and Searching
### `yum list`
Lists all available, installed, and updatable packages.
```bash
yum list
```
---
### `yum info <pkg>`
Displays detailed information about the specified package, including version, repository, summary, and description.
```bash
yum info <pkg>
```
---
### `yum search`
Searches for a keyword in package names and descriptions. Add the search term to complete the command.
```bash
yum search <keyword>
```
Example:
```bash
yum search python
```
---
### `yum deplist <pkg>`
Shows the list of dependencies for a given package.
```bash
yum deplist <pkg>
```
---
## 🕓 5. Package History and Transactions
### `yum history`
Displays a history of all yum transactions (installs, updates, removals), which can be reviewed or undone if needed.
```bash
yum history
```
---
## 💾 6. Downloading Packages (Without Installing)
### `yum download <pkg>`
Downloads an RPM package file without installing it. Useful for transferring or offline installations. Requires the `yum-utils` package.
```bash
yum download <pkg>
```
> 💡 **Note:** If you get an error, try installing `yum-utils`:
>
> ```bash
> yum install yum-utils
> ```
---
## ✅ Final Notes
* `yum` has been replaced by `dnf` in newer distributions (e.g., RHEL 8+), but still widely used in older systems.
* Always run `yum update` before installing new packages.
* Combine with `yum history` to review or undo changes when troubleshooting.

View File

@@ -0,0 +1,172 @@
# 📦 Managing Packages with `rpm` on RHEL/CentOS
The `rpm` command (RPM Package Manager) is the **low-level package management tool** used on **Red Hat-based** systems such as RHEL, CentOS, Fedora, and others. Unlike `yum`, `rpm` does not resolve dependencies automatically and is best used for advanced or manual package management.
Below are the core `rpm` commands categorized and explained.
---
## 📥 1. Installing Packages
### `rpm -i <file.rpm>`
### `rpm --install <file.rpm>`
Installs a new `.rpm` package file. This command will **fail if the package's dependencies are not already installed**.
```bash
rpm -i <file.rpm>
```
or
```bash
rpm --install <file.rpm>
```
> 💡 Tip: Use `yum localinstall` or `dnf install` instead for dependency resolution.
---
## 🔄 2. Upgrading Packages
### `rpm -U <file.rpm>`
### `rpm --upgrade <file.rpm>`
Upgrades an existing package if it is already installed. If the package is not already present, this command will install it.
```bash
rpm -U <file.rpm>
```
or
```bash
rpm --upgrade <file.rpm>
```
---
## ❌ 3. Removing Packages
### `rpm -e <package>`
### `rpm --erase <package>`
Removes a package from the system by name (not the filename). Note that this command also does **not resolve dependencies**, so it may break things if you're not careful.
```bash
rpm -e <package>
```
or
```bash
rpm --erase <package>
```
> ⚠️ Caution: Always check what depends on a package before removing it.
---
## 🔍 4. Querying Packages
### `rpm -q <package>`
Query whether a package is installed, and show its version.
```bash
rpm -q <package>
```
---
### `rpm -qa`
List **all installed packages**.
```bash
rpm -qa
```
---
### `rpm -qi <package>`
Displays detailed **information** about a specific installed package.
```bash
rpm -qi <package>
```
---
### `rpm -ql <package>`
Lists all files installed by a package.
```bash
rpm -ql <package>
```
---
### `rpm -qf <file>`
Finds out **which package** owns a specific file.
```bash
rpm -qf /usr/bin/wget
```
---
### `rpm -qp <file.rpm>`
Query a package file (without installing it) to see its metadata.
```bash
rpm -qp <file.rpm>
```
---
### `rpm -K <file.rpm>`
Verifies the **signature and integrity** of an RPM package file.
```bash
rpm -K <file.rpm>
```
---
## 🛠️ 5. Verifying and Checking
### `rpm -V <package>`
Verifies installed package files against their original metadata (modifications, corruption, etc.).
```bash
rpm -V <package>
```
---
### `rpm --test -i <file.rpm>`
Simulates an install without actually installing the package — useful for testing.
```bash
rpm --test -i <file.rpm>
```
---
## ✅ Final Notes
* `rpm` is a **powerful low-level tool**, but not recommended for resolving dependencies.
* For **automated dependency handling**, prefer using `yum` or `dnf`.
* Use `rpm` when you need precise control over the package management process or are working with standalone `.rpm` files.

View File

@@ -0,0 +1,114 @@
# 🔐 Secure Shell (SSH) Remote Access & Management
**SSH (Secure Shell)** is a cryptographic network protocol that allows users to **securely access and control remote machines** over a network. It's a foundational tool for system administrators, developers, and anyone managing remote systems.
---
## 🧠 What SSH Does
* **🔒 Encrypts Communication**
All data transmitted between the client and the remote server is encrypted, protecting it from eavesdropping and man-in-the-middle attacks.
* **🧑‍💻 Authenticates Users**
Supports both password-based and public key-based authentication to ensure that only authorized users gain access.
* **💻 Enables Remote Command Execution**
Run commands on a remote machine as if you're using its terminal directly.
* **📁 Supports Secure File Transfers**
Tools like `scp` (Secure Copy) and `sftp` (SSH File Transfer Protocol) allow encrypted file transfers between machines.
---
## 🚀 Installing the SSH Server
To accept SSH connections on a machine, you must install and start the **OpenSSH server**.
### On Debian/Ubuntu systems
```bash
sudo apt install openssh-server
```
* This installs the OpenSSH daemon (`sshd`), which listens for incoming SSH connections.
* To enable and start the service:
```bash
sudo systemctl enable ssh
sudo systemctl start ssh
```
---
### On RHEL/CentOS systems
```bash
sudo yum install openssh-server
```
* Start and enable the SSH service:
```bash
sudo systemctl enable sshd
sudo systemctl start sshd
```
---
## 🛠️ Common SSH Usage Examples
### 🔗 Connect to a Remote Server
```bash
ssh username@remote_host
```
### 📁 Copy a File to a Remote Server Using `scp`
```bash
scp file.txt user@remote_host:/path/to/destination/
```
### 📥 Copy a File from a Remote Server
```bash
scp user@remote_host:/path/to/file.txt .
```
### 🗂️ Use Interactive File Transfer with `sftp`
```bash
sftp user@remote_host
```
---
## 🔐 Key-Based Authentication (Optional but Recommended)
To use SSH without typing a password every time, you can set up key-based authentication:
1. **Generate SSH key pair on your local machine:**
```bash
ssh-keygen
```
2. **Copy the public key to the remote server:**
```bash
ssh-copy-id user@remote_host
```
3. Now you can SSH without a password prompt:
```bash
ssh user@remote_host
```
---
## ✅ Final Notes
* SSH is a vital tool for managing servers securely.
* Always **disable root login** and **use key authentication** for better security.
* You can configure SSH behavior in `/etc/ssh/sshd_config`.

View File

@@ -0,0 +1,119 @@
# Getting Started with Vim 📝
## 1. Installing Vim
To install Vim on a Debianbased system (like Ubuntu), run:
```bash
sudo apt update
sudo apt install vim
```
---
## 2. Opening Files or Directories
* **Open a file**
```bash
vim <filename>
```
* **Open a directory**
```bash
vim <directory_name>
```
(This opens Vims file browser—helpful for navigating and editing multiple files.)
---
## 3. Vim Modes
Vim works in multiple modes—here are the core ones:
1. **Normal mode** The default mode; used for navigation and commands.
2. **Insert mode** For editing text; enter it by pressing `i`, `a`, or `o`.
3. **Visual mode** For selecting text; enter it with `v`, `V`, or `Ctrl+v`.
---
## 4. Essential Commands
(Type these in **Normal mode** and then press Enter when needed)
| Command | Description |
| ----------- | ----------------------------------------- |
| `:w` | Save (write changes to the current file) |
| `:w <name>` | Save changes to a specified file `<name>` |
| `:wq` | Save and quit Vim |
| `:q` | Quit (only if no unsaved changes exist) |
| `:q!` | Quit without saving (discard all changes) |
---
## 5. Handy Shortcuts
These are core shortcuts used in **Normal mode**:
| Shortcut | Action |
| -------- | -------------------------------- |
| `dd` | Delete (cut) the current line |
| `yy` | Yank (copy) the current line |
| `p` | Paste after the cursor |
| `u` | Undo the last change |
| `gg` | Go to the first line of the file |
---
## 6. Quick Usage Flow
1. **Start Vim**:
```bash
vim example.txt
```
2. **Insert text**:
Press `i` → type your content → press `Esc` to return to **Normal mode**.
3. **Save your work**:
Type `:w` in Normal mode and press Enter.
4. **Make edits**:
* Use `dd` to delete a line
* Use `yy` to copy (yank) a line
* Move the cursor to a new location, then hit `p` to paste
* Press `u` to undo any mistake
5. **Navigate quickly**:
* `gg` to jump to the beginning
* Use arrow keys or `h`, `j`, `k`, `l` for navigation
6. **Finish editing**:
* `:wq` to save and exit
* `:q!` to exit without saving
---
## 7. Tips & Tricks
* **Visual mode**:
Press `v` to start selecting character by character, `V` for line selection, or `Ctrl+v` for block-wise selection.
* **Other navigation**:
* Use `G` to go to the end of the file
* Use a number before a command, e.g., `5dd` deletes 5 lines
---
### Summary
Vim may feel different at first, but once you get comfortable switching between **Insert**, **Normal**, and **Visual** modes, you'll find its a powerful and efficient editor.
Happy Vimming! 😊

View File

@@ -0,0 +1,70 @@
# 🗜️ ZIP Compression Cheatsheet
The `zip` command is a widely used tool for compressing files and folders into a `.zip` archive. It is cross-platform and supports features like encryption and customizable compression levels.
---
## 📦 Basic Syntax
```bash
zip [options] archive.zip files
```
---
## 🔧 Create a ZIP Archive
```bash
zip archive.zip file1 file2
```
* Compresses `file1` and `file2` into `archive.zip`
---
## 📈 Maximum Compression
```bash
zip -9 archive.zip file1 file2
```
* `-9`: Use maximum compression (slower, but smaller file size)
---
## 🔐 Create a Password-Protected ZIP
```bash
zip -e archive.zip file1 file2
```
* `-e`: Prompts for password encryption on the archive
---
## 📋 List Files in a ZIP Archive
```bash
unzip -l archive.zip
```
* `-l`: Lists contents of the ZIP without extracting
---
## 📂 Extract ZIP Archive
```bash
unzip archive.zip
```
* Extracts contents into the current directory
### 📁 Extract to Custom Directory
```bash
unzip archive.zip -d <custom-dir>
```
* `-d <custom-dir>`: Extracts files into the specified folder

View File

@@ -0,0 +1,155 @@
# Linux Compression & Archiving Cheatsheet
## Tar Command Basics
The `tar` command is used to create, extract, and manage archive files.
**Syntax:**
```bash
tar [options] [archive_name.tar] [file(s)/directory]
```
---
### Create a `.tar` Archive
```bash
tar -cf archive_file.tar file1 file2 dir1
```
**Options:**
* `-c`: Create a new archive
* `-f`: Specify the archive file name
### Create with Verbose Output
```bash
tar -cvf archive_file.tar file1 file2 dir1
```
* `-v`: Verbose mode (shows progress)
### Extract a `.tar` Archive
```bash
tar -xf archive_file.tar
```
or
```bash
tar -xvf archive_file.tar
```
* `-x`: Extract files
---
## Gzip Compression
**Gzip** (GNU zip) is a fast and widely used compression tool.
### Create a `.tar.gz` Archive
```bash
tar -czf archive_file.tar.gz file1 file2 dir1
```
* `-z`: Compress using gzip
### Verbose Creation
```bash
tar -czvf archive_file.tar.gz file1 file2 dir1
```
### Extract `.tar.gz`
```bash
tar -xzf archive_file.tar.gz
```
or
```bash
tar -xzvf archive_file.tar.gz
```
---
## Bzip2 Compression
**Bzip2** provides better compression than gzip but at the cost of speed.
### Create a `.tar.bz2` Archive
```bash
tar -cjf archive_file.tar.bz2 file1 file2 dir1
```
* `-j`: Compress using bzip2
### Verbose Creation
```bash
tar -cjvf archive_file.tar.bz2 file1 file2 dir1
```
### Extract `.tar.bz2`
```bash
tar -xjf archive_file.tar.bz2
```
or
```bash
tar -xjvf archive_file.tar.bz2
```
---
## XZ Compression
**XZ** offers the best compression ratio but is the slowest option.
### Create a `.tar.xz` Archive
```bash
tar -cJf archive_file.tar.xz file1 file2 dir1
```
* `-J`: Compress using xz
### Verbose Creation
```bash
tar -cJvf archive_file.tar.xz file1 file2 dir1
```
### Extract `.tar.xz`
```bash
tar -xJf archive_file.tar.xz
```
or
```bash
tar -xJvf archive_file.tar.xz
```
---
## Compression Format Comparison
| Feature | gzip | bzip2 | xz |
| ------------------- | ----------- | ---------- | --------- |
| Compression Speed | Fast | Slow | Slowest |
| Decompression Speed | Fast | Slower | Moderate |
| Compression Ratio | Good | Better | Best |
| File Extension | `.tar.gz` | `.tar.bz2` | `.tar.xz` |
| Common Use | General/Web | Backups | Archival |

View File

@@ -0,0 +1,85 @@
# 📘 **Using `grep` in Linux/Unix**
`grep` (Global Regular Expression Print) is a powerful command-line utility used to search for text patterns in files. Below are common variations of the `grep` command with examples and explanations.
---
## 🔍 Basic Search
```bash
grep "hello" file1
```
**Description**:
Searches for lines containing the word `hello` in `file1`. The search is **case-sensitive**.
---
## 🔍 Case-Insensitive Search
```bash
grep -i "hello" file1
```
**Description**:
Performs a **case-insensitive** search for `hello` in `file1`. Matches `hello`, `Hello`, `HELLO`, etc.
---
## 🔢 Show Line Numbers
```bash
grep -n "hello" file1
```
**Description**:
Displays matching lines **with their line numbers**.
---
## 🔢 Case-Insensitive with Line Numbers
```bash
grep -in "hello" file1
```
**Description**:
Combines `-i` and `-n` to show line numbers and ignore case.
---
## 🚫 Invert Match
```bash
grep -v "hello" file1
```
**Description**:
Shows lines that **do NOT** contain the word `hello`.
---
## 🚫 Invert, Ignore Case, and Show Line Numbers
```bash
grep -ivn "hello" file1
```
**Description**:
Combines all the above:
* `-i`: Ignore case
* `-v`: Invert match
* `-n`: Show line numbers
Shows all lines that **dont contain** `hello`, regardless of case, and includes line numbers.
---
## ✅ Summary of Flags
| Flag | Description |
| ---- | -------------------------- |
| `-i` | Ignore case |
| `-n` | Show line numbers |
| `-v` | Invert the match (exclude) |

View File

@@ -0,0 +1,45 @@
# 📘 **Using `less` in Linux/Unix**
`less` is a terminal pager program used to view the content of files one screen at a time. It's especially useful for viewing large files or logs.
---
## 📂 Basic Usage
```bash
less file
```
**Description**:
Opens `file` for viewing.
```bash
less /var/log/syslog
```
**Description**:
Opens the system log file for reading. Useful for examining system logs line by line.
---
## ⌨️ Common Keyboard Shortcuts
Here are the most frequently used keyboard shortcuts when using `less`:
| Key/Command | Action |
| ----------- | ------------------------------------ |
| `space` | Scroll **down** one screen |
| `b` | Scroll **up** one screen |
| `q` | **Quit** `less` |
| `/pattern` | **Search** forward for `pattern` |
| `n` | Go to the **next** match of pattern |
| `N` | Go to the **previous** match |
| `g` | Go to the **first line** of the file |
| `G` | Go to the **last line** of the file |
---
## ✅ Summary
`less` is a vital tool for system administrators, developers, and anyone dealing with large text files. With simple navigation and powerful search capabilities, it makes file reading efficient and user-friendly.

View File

@@ -0,0 +1,77 @@
# 📘 **Using `head` and `tail` Commands in Linux/Unix**
Both `head` and `tail` are essential commands for viewing specific portions of a file quickly, without opening the entire file.
---
## 🔝 `head` — Show the Top of a File
The `head` command displays the beginning part of a file.
### Syntax
```bash
head [options] file
```
### Examples
```bash
head file1
```
**Description**:
Displays the first 10 lines of `file1` (default behavior).
```bash
head -n 5 file1
```
**Description**:
Shows the first 5 lines of `file1`.
---
## 🔚 `tail` — Show the Bottom of a File
The `tail` command displays the end part of a file.
### Syntax
```bash
tail [options] file
```
### Examples
```bash
tail file1
```
**Description**:
Displays the last 10 lines of `file1` (default behavior).
```bash
tail -n 20 file1
```
**Description**:
Shows the last 20 lines of `file1`.
```bash
tail -f file1
```
**Description**:
Follows the file as it grows — useful for watching logs in real-time.
---
## ✅ Summary of Options
| Command | Option | Description |
| ------- | ------------- | ------------------------------------------- |
| `head` | `-n <number>` | Show the first `<number>` lines |
| `tail` | `-n <number>` | Show the last `<number>` lines |
| `tail` | `-f` | Follow the file in real-time (live updates) |

View File

@@ -0,0 +1,52 @@
# 📘 **Using the `wc` Command in Linux/Unix**
`wc` (word count) is a utility that counts lines, words, and bytes or characters in files. Its useful for quickly getting file size details in text terms.
---
## ⚙️ Syntax
```bash
wc [option] file
```
---
## 🔎 Basic Usage
```bash
wc file
```
**Example output:**
```
5 6 43 file1
```
This output means:
| Number | Meaning |
| ------ | ------------------- |
| `5` | Number of **lines** |
| `6` | Number of **words** |
| `43` | Number of **bytes** |
---
## 📋 Common Options
| Option | Description | Example |
| ------ | ------------------------- | ------------ |
| `-l` | Count **lines** only | `wc -l file` |
| `-w` | Count **words** only | `wc -w file` |
| `-c` | Count **bytes** only | `wc -c file` |
| `-m` | Count **characters** only | `wc -m file` |
---
## 📌 Notes
* `bytes (-c)` counts raw bytes, which might differ from characters (`-m`) in multibyte encodings like UTF-8.
* Without options, `wc` outputs lines, words, and bytes by default.

View File

@@ -0,0 +1,79 @@
# ⚙️ PS Command
The `ps` (process status) command is used to **view running processes** on a Linux system. Its useful for monitoring and troubleshooting tasks.
---
## 🧾 Basic Usage
### 🔍 Show tasks in the current shell
```bash
ps
```
### 🔍 Show tasks in the current shell with **full info**
```bash
ps -f
```
---
## 🌍 View System-Wide Processes
### 📋 Show **all** processes
```bash
ps -A
# or
ps -e
```
---
### 👤 Show tasks by **specific user**
```bash
ps -u <username>
```
📌 Replace `<username>` with the actual user name.
---
### 📊 Show **detailed info for all** tasks
```bash
ps aux
```
---
## 📘 Output Fields Explained
| Column | Description |
| --------- | -------------------------------------------------- |
| `USER` | Owner of the process (often `root` or your user) |
| `PID` | Process ID |
| `%CPU` | CPU usage percentage |
| `%MEM` | Memory usage percentage |
| `STAT` | Process state: `R` (running), `S` (sleeping), etc. |
| `START` | Time when the process started |
| `TIME` | Total CPU time used |
| `COMMAND` | Command that started the process |
### 📑 Show List Jobs
```bash
jobs
```
### 🔄Move Process From Background To Forground
```bash
fg
```

View File

@@ -0,0 +1,74 @@
# 🗡️ Kill Command
The `kill` command is used to **send signals to processes**, typically to terminate or control them.
```bash
kill [options] <PID>
```
📌 Replace `<PID>` with the Process ID of the target process.
---
## 🚦 Common `kill` Usage Examples
### 💤 Graceful Termination — `SIGTERM` (Signal 15)
```bash
kill 123
```
✅ Politely asks the process to terminate.
*Allows the process to clean up before exiting.*
---
### 🪓 Force Kill — `SIGKILL` (Signal 9)
```bash
kill -9 123
```
💥 **Immediate termination**.
*Doesnt allow cleanup — use only when necessary.*
🗡️ *Think of it as the "katana" of kill commands.*
### 📑 Multi Process Kill
```bash
pidof <ps-name> | xargs kill -9
```
---
### ⌨️ Interrupt — `SIGINT` (Signal 2)
```bash
kill -2 123
```
🛑 Mimics pressing `Ctrl + C`.
*Often used to stop processes gracefully from the terminal.*
---
### 🔄 Hangup — `SIGHUP` (Signal 1)
```bash
kill -1 123
```
♻️ Requests the process to **reload or restart**.
*Commonly used for daemons or services to reload configs.*
---
## 📋 Summary of Signals
| Signal | Name | Description |
| ------ | --------- | ------------------------------ |
| `1` | `SIGHUP` | Reload configuration / restart |
| `2` | `SIGINT` | Interrupt (like Ctrl + C) |
| `9` | `SIGKILL` | Force kill (cannot be ignored) |
| `15` | `SIGTERM` | Graceful termination (default) |

View File

@@ -0,0 +1,111 @@
# 🧑‍💻 Linux User & Group Management Cheat Sheet
---
## 🔍 Viewing User Info from `/etc/shadow`
```bash
cat /etc/shadow
```
Example entry:
```bash
radin:$y$j9T$gxn.Bgl/nVnzPEeWn0Hrz.$CEeQGtg1TlZ/jwu9Zsz2kkIq3dBtbhJ/bzhVT7cJ1.9:20270:0:99999:7:::
```
| Field | Description | Example |
| ----------------- | -------------------------------------------- | ----------------------------------------------- |
| 👤 Username | Users login name | `radin` |
| 🔒 Password Hash | Encrypted password | `$y$j9T$gxn.Bgl/nVnzPEeWn0Hrz.$CEeQGtg1TlZ/...` |
| 🗓️ Last Changed | Days since Jan 1, 1970 when password changed | `20270` (which is 20270 + 1970 = year) |
| ⏳ Min Age | Minimum days between password changes | `0` |
| ⏰ Max Age | Maximum days before password must be changed | `99999` |
| ⚠️ Warning Period | Days before expiration user is warned | `7` |
---
## 🛡️ Viewing Groups from `/etc/group`
```bash
cat /etc/group
```
Example:
```bash
radin:x:1000:
sudo:x:27:radin
```
| Field | Description | Example |
| ------------- | ------------------------------------ | --------------- |
| 👥 Group Name | Name of the group | `radin`, `sudo` |
| 🔑 Password | Password (usually `x` means none) | `x` |
| 🆔 GID | Group ID | `1000`, `27` |
| 👤 Users | Users in the group (comma-separated) | `radin` |
---
## 👥 Check Groups for a User
```bash
groups <username>
```
---
## 🆔 View User and Group IDs
```bash
id <username>
```
Example output:
```bash
uid=1000(radin) gid=1000(radin) groups=1000(radin),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),100(users),114(lpadmin)
```
---
## Adding Users
| Command | Description |
| -------------------------------------- | ----------------------------------------- |
| `useradd <username>` | Add user without home directory |
| `useradd -m <username>` | Add user **with** home directory |
| `useradd -s /bin/bash -m <username>` | Add user with bash shell & home directory |
| `useradd -G group1,root -m <username>` | Add user with home and extra groups |
---
## 🔑 Changing Password
```bash
passwd <username>
```
---
## ❌ Deleting Users
| Command | Description |
| ----------------------- | ------------------------------------ |
| `userdel <username>` | Delete user |
| `userdel -r <username>` | Delete user and their home directory |
| `userdel -f <username>` | Force delete user |
---
## 🔧 Modifying Users (`usermod`)
| Command | Description |
| ---------------------------------------- | ----------------------------------------- |
| `usermod [options] username` | Modify user with various options |
| `usermod -l <newusername> <oldusername>` | Rename user |
| `usermod -d <dir> -m <username>` | Change user home directory and move files |
| `usermod -G <groups> <username>` | Set new groups (replaces old groups) |
| `usermod -aG <group> <username>` | Add user to a supplementary group |
| `usermod -s <shell> <username>` | Change user login shell |

View File

@@ -0,0 +1,150 @@
# 📁 Linux File Permissions: A Quick & Clear Guide
---
## 🔍 Example: Output of `ls -lh`
Run this command in your terminal:
```bash
ls -lh
```
Example output:
```bash
drwxr-xr-x 3 root root 4.0K Jul 1 22:22 dir1
-rw-r--r-- 1 root root 2.0G Jul 1 21:59 test2.tar
```
---
## 🧠 Understanding the Output Columns
| Column | Description |
| -------------------- | --------------------------------------- |
| `d` / `-` | File type (`d` = directory, `-` = file) |
| `rwxr-xr-x` | Permissions (user, group, others) |
| `3` | Number of hard links |
| `root` | Owner (user) |
| `root` | Group |
| `4.0K` / `2.0G` | File size |
| `Jul 1 22:22` | Last modification date |
| `dir1` / `test2.tar` | File or directory name |
---
## 🔤 First Character: File Type Indicator
* `d` → Directory 📂
* `-` → Regular file 📄
---
## 🔠 File Permissions Breakdown
```
drwxr-xr-x
│││ │ │ │
│││ │ │ └─ Permissions for Others (o)
│││ │ └── Permissions for Group (g)
│││ └──── Permissions for User (u)
│└──────── File type (d = directory, - = file)
└───────── Read (r), Write (w), Execute (x)
```
---
## 🔐 Permission Symbols Explained
| Symbol | Meaning |
| ------ | ------- |
| `r` | Read |
| `w` | Write |
| `x` | Execute |
---
## 👥 Permission Entities
| Symbol | Meaning |
| ------ | ------------ |
| `u` | User (owner) |
| `g` | Group |
| `o` | Others |
| `a` | All |
---
## 🔢 Numeric Permission Values (Octal)
| Value | Binary | Permissions | Meaning |
| ----- | ------ | ----------- | ---------------------- |
| 0 | 000 | --- | No permissions |
| 1 | 001 | --x | Execute only |
| 2 | 010 | -w- | Write only |
| 3 | 011 | -wx | Write + Execute |
| 4 | 100 | r-- | Read only |
| 5 | 101 | r-x | Read + Execute |
| 6 | 110 | rw- | Read + Write |
| 7 | 111 | rwx | Read + Write + Execute |
---
## 🛠️ Changing Permissions with `chmod`
### Syntax:
```bash
chmod [permissions] [filename]
```
### Example (numeric):
```bash
chmod 755 myscript.sh
```
### What does `755` mean?
| Entity | Value | Permission |
| ------ | ----- | -------------------------- |
| User | 7 | rwx (read, write, execute) |
| Group | 5 | r-x (read, execute) |
| Others | 5 | r-x (read, execute) |
### Recursive permission change:
```bash
chmod -R <permission> <directory>
```
---
## 👑 Changing Ownership with `chown`
### Syntax:
```bash
chown [options] owner[:group] file
```
### Examples:
Change owner only:
```bash
sudo chown radin file.txt
```
Change owner and group:
```bash
sudo chown radin:dev file.txt
```
Change owner and group recursively (for directories):
```bash
sudo chown -R radin:dev files/
```

View File

@@ -0,0 +1,148 @@
# 🌐 IP Command Cheat Sheet
The `ip` command is a powerful tool for network configuration and management in Linux. It replaces many of the older `ifconfig` functionalities.
---
## 📌 General Syntax
```bash
ip [ OPTIONS ] OBJECT { COMMAND | help }
```
**Common OBJECTS:**
* `addr` IP addresses
* `link` Network interfaces
* `route` Routing tables
* `neigh` ARP table
* `rule`, `netns`, etc.
---
## 🔍 View Network Information
### Show All IP Addresses
```bash
ip addr show
# or shorthand:
ip a
```
### Show IP for Specific Interface
```bash
ip addr show dev eth0
```
### Show Link Layer Information
```bash
ip link show
```
---
## 🔧 Interface Management
### Bring Interface Down
```bash
ip link set eth0 down
```
### Bring Interface Up
```bash
ip link set eth0 up
```
---
## 🌐 IP Address Configuration
### Add an IP Address
```bash
ip addr add 192.168.1.10/24 dev eth0
```
### Delete an IP Address
```bash
ip addr del 192.168.1.10/24 dev eth0
```
---
## 🛣️ Routing
### Show Routing Table
```bash
ip route show
```
### Add a Default Gateway
```bash
ip route add default via 192.168.1.1
```
### Add a Specific Route
```bash
ip route add 192.168.10.0/24 via 192.168.5.2
```
### Delete a Specific Route
```bash
ip route del 192.168.10.0/24 via 192.168.5.2
```
---
## 🧱 Bridge Interface Management
### Create a Bridge
```bash
ip link add name br0 type bridge
```
### Delete a Bridge
```bash
ip link delete br0
```
### Bring Bridge Up
```bash
ip link set br0 up
```
---
## 🛠️ Example: Set a Static IP Address
```bash
ip link set ens33 up
ip addr add 10.10.40.12/24 dev ens33
ip route add default via 10.10.40.1
```
---
### ✅ Tip:
Always verify with:
```bash
ip a
ip r
```

View File

@@ -0,0 +1,74 @@
# 🛣️ `route` Command Documentation
The `route` command is used to view and manipulate the IP routing table in Linux systems. Below is a concise guide to listing, adding, and deleting routes using `route`.
---
## 📋 View Routing Table
```bash
route -n
```
* **Description**: Displays the kernel routing table.
* **`-n`**: Shows numerical addresses instead of resolving hostnames (faster and cleaner).
---
## Add Routes
### Add a Network Route
```bash
route add -net 10.10.10.0 netmask 255.255.255.0 gw 192.168.1.1
```
* **`-net 10.10.10.0`**: Specifies the network address.
* **`netmask 255.255.255.0`**: Defines the subnet mask for the network.
* **`gw 192.168.1.1`**: Sets the gateway through which packets will be routed.
### Add a Default Gateway
```bash
route add default gw 192.168.1.1
```
* **default**: Indicates this is the default route.
* **`gw 192.168.1.1`**: The default gateway IP address for all traffic not destined for a known network.
---
## ❌ Delete Routes
### Delete a Network Route
```bash
route del -net 10.10.10.0 netmask 255.255.255.0
```
* Removes the specified network route.
### Delete the Default Route
```bash
route del default
```
* Removes the current default gateway.
---
## 📎 Notes
* These commands typically require **superuser (root)** privileges. Use `sudo` if needed:
```bash
sudo route add ...
```
* Consider using `ip route` instead of `route`, as `route` is deprecated on some modern distributions:
```bash
ip route show
```

Some files were not shown because too many files have changed in this diff Show More