diff --git a/.github/instructions/md-formatting.instructions.md b/.github/instructions/md-formatting.instructions.md new file mode 100644 index 0000000000..9c3b677862 --- /dev/null +++ b/.github/instructions/md-formatting.instructions.md @@ -0,0 +1,18 @@ +--- +name: md-formatting +description: "Apply consistent Markdown formatting to all .md files in this repository, with commands formatted as code and emojis used for emphasis and clarity." +applyTo: "**/*.md" +--- + +Use this instruction for every Markdown file in the repository. + +- Format commands and CLI examples using inline backticks for commands (`git status`) and fenced code blocks for longer snippets. +- Use headings, lists, and bold text to structure content clearly. +- Add emojis for emphasis and readability, for example: + - βœ… for success or recommended actions + - ⚠️ for warnings and caveats + - πŸ’‘ for tips and notes + - πŸ”§ for technical steps +- Keep prose clear and concise, with proper sentence spacing. +- Avoid raw unformatted command text in paragraphs; commands should always be in Markdown code formatting. +- Ensure generated or updated Markdown follows the repo's consistent style across `README.md`, lesson notes, and other `.md` files. diff --git a/2026/day-14/OSI Models 2.jpg b/2026/day-14/OSI Models 2.jpg new file mode 100644 index 0000000000..fc99a5e202 Binary files /dev/null and b/2026/day-14/OSI Models 2.jpg differ diff --git a/2026/day-14/OSI Models.jpg b/2026/day-14/OSI Models.jpg new file mode 100644 index 0000000000..6887db313f Binary files /dev/null and b/2026/day-14/OSI Models.jpg differ diff --git a/2026/day-14/day-14-networking1.md b/2026/day-14/day-14-networking1.md new file mode 100644 index 0000000000..d0859b8170 --- /dev/null +++ b/2026/day-14/day-14-networking1.md @@ -0,0 +1,203 @@ +# Day 14 - Networking Basics and OSI Layer + +# 🌐 1. What a Network Actually Is + +A network is simply: + +> 🧠 A group of devices connected so they can talk to each other. + +## πŸ“Œ Examples: + +- Your laptop ↔ router +- Your phone ↔ Wi-Fi +- Servers ↔ other servers +- Your device ↔ Google + +## πŸ”— They can be connected using: + +- πŸ”Œ Cables (Ethernet) +- πŸ“Ά Wi-Fi (wireless signals) +- ☁️ Virtual links (cloud networks like AWS) + +--- + +## 2. The OSI Model (Open Systems Interconnection Model) + +**The OSI Model (Open Systems Interconnection Model) is a conceptual framework used to understand how data travels from one computer to another over a network** + +**It breaks the entire networking process into 7 separate layers, where each layer has a specific job.** + +- Application +- Presentation +- Session +- Transport +- Network +- Data Link +- Physical + +# 🌐 What Happens When You Open Google (OSI Model Real-World Example) + +This document explains what happens behind the scenes when you type `www.google.com` in your browser and press Enter, mapped to the **OSI Model (7 Layers)**. + +# 🧠 Scenario Overview + +When you open Google, your computer performs multiple networking steps in milliseconds to fetch and display the webpage. + +# 🌐 Step-by-Step OSI Model Breakdown + +--- + +## 7. Application Layer (Layer 7) + +You interact with the browser (Chrome, Edge, Firefox). + +- You type: `www.google.com` +- Browser understands user request +- Creates an HTTP/HTTPS request + +πŸ‘‰ Meaning: +You are requesting a webpage. + +--- + +## 6. Presentation Layer (Layer 6) + +Data is prepared for secure transmission. + +- Data formatting happens +- Encryption is applied using **HTTPS (TLS/SSL)** + +πŸ‘‰ Meaning: +Data is encrypted so no one can read it during transmission. + +--- + +## 5. Session Layer (Layer 5) + +A communication session is established. + +- Connection between your computer and server is created +- Session is maintained while browsing + +πŸ‘‰ Meaning: +Keeps communication active until you close the browser/tab. + +--- + +## 4. Transport Layer (Layer 4) + +Ensures reliable data delivery. + +- Data is broken into segments +- TCP protocol is used (reliable delivery) +- Lost packets are retransmitted + +πŸ‘‰ Meaning: +Ensures all data arrives correctly and in order. + +--- + +## 3. Network Layer (Layer 3) + +Handles routing and IP addressing. + +- DNS converts `google.com` β†’ IP address (e.g., 142.250.x.x) +- Routers decide best path for data packets + +πŸ‘‰ Meaning: +Finds the correct destination across the internet. + +--- + +## 2. Data Link Layer (Layer 2) + +Handles local network communication. + +- Data is framed +- MAC addresses are used +- Communication between device and router + +πŸ‘‰ Meaning: +Delivers data within your local network (Wi-Fi/Ethernet). + +--- + +## 1. Physical Layer (Layer 1) + +Actual transmission of data happens. + +- Data becomes electrical signals / radio waves / light signals +- Sent via cables, fiber optics, or Wi-Fi + +πŸ‘‰ Meaning: +Raw 0s and 1s travel through physical medium. + +--- + +# 🌍 Server Side (Google) + +The request reaches Google servers +(operated by :contentReference[oaicite:0]{index=0}) + +- Server processes your request +- Generates response (HTML, CSS, JS) +- Sends data back through the same layers in reverse + +--- + +# πŸ” Reverse Process (Receiving Data) + +When response comes back: + +1. Physical signals β†’ bits +2. Data Link β†’ frames processed +3. Network β†’ routing removed +4. Transport β†’ segments reassembled (TCP) +5. Session β†’ connection maintained +6. Presentation β†’ decrypted (HTTPS) +7. Application β†’ browser renders page + +--- + +# πŸ“¦ Final Output + +Your browser displays: + +πŸ‘‰ Google homepage + +--- + +# 🧩 Simple Summary + +Opening Google involves: + +- Request creation (Application Layer) +- Encryption (Presentation Layer) +- Session establishment (Session Layer) +- Reliable transfer via TCP (Transport Layer) +- Routing via IP (Network Layer) +- Local delivery via MAC/Wi-Fi (Data Link Layer) +- Physical transmission via signals (Physical Layer) + +--- + +# πŸ’‘ One-Line Understanding + +> Opening Google is your computer sending a structured, encrypted request through 7 networking layers, and receiving a response that is rebuilt into a webpage. + +--- + +# πŸš€ Key Takeaway + +The OSI model helps us understand: + +- How data travels across networks +- How different devices communicate +- How complex networking is broken into simple layers +--- + +# πŸ’‘ Key Insight + +> `curl https://www.google.com` is not β€œjust a command” β€” it is a full OSI stack in action, from Application layer down to Physical transmission and back up again. + +--- \ No newline at end of file diff --git a/2026/day-14/day-14-networking2-hands-on.md b/2026/day-14/day-14-networking2-hands-on.md new file mode 100644 index 0000000000..c694364f54 --- /dev/null +++ b/2026/day-14/day-14-networking2-hands-on.md @@ -0,0 +1,475 @@ +# Day 14 - Networking Basics πŸš€ Hands-on Checklist + +# 1. Identity + +**Command1** + +```bash +hostname -I +``` + +**Output** + +```text +ubuntu@Kartik:~/LinuxForDevOps/day14$ hostname -I +172.27.145.12 +``` + +**Observation** +- System IP address identified successfully. +- Used to verify local network configuration. + +**Command2** + +```bash +ip addr show + +``` +**Output** +```text + +ubuntu@Kartik:~/LinuxForDevOps/day14$ ip addr show +1: lo: mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 + link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 + inet 127.0.0.1/8 scope host lo + valid_lft forever preferred_lft forever + inet 10.255.255.254/32 brd 10.255.255.254 scope global lo + valid_lft forever preferred_lft forever + inet6 ::1/128 scope host + valid_lft forever preferred_lft forever +2: eth0: mtu 1500 qdisc mq state UP group default qlen 1000 + link/ether 00:15:5d:dc:64:25 brd ff:ff:ff:ff:ff:ff + inet 172.27.145.12/20 brd 172.27.159.255 scope global eth0 + valid_lft forever preferred_lft forever + inet6 fe80::215:5dff:fedc:6425/64 scope link + valid_lft forever preferred_lft forever +``` + +**Observation** + +- This command shows: **All network interfaces + their IP addresses on your machine** + +- Loopback Interface (lo) : ```1: lo: ``` +- Ethernet / Network Interface (eth0) : ```2: eth0: ``` This is your real network connection +- ```ip addr show``` reveals how your machine identifies itself locally and on the network β€” including loopback (self), private IP (network), and MAC address (hardware identity). + +# 2. Reachability + +**Command** + +```bash +ping -c 4 google.com +``` + +**Output** + +```text +ubuntu@Kartik:~/LinuxForDevOps/day14$ ping -c 4 google.com +PING google.com (142.251.30.139) 56(84) bytes of data. +64 bytes from sv-in-f139.1e100.net (142.251.30.139): icmp_seq=1 ttl=111 time=74.6 ms +64 bytes from sv-in-f139.1e100.net (142.251.30.139): icmp_seq=2 ttl=111 time=17.8 ms +64 bytes from sv-in-f139.1e100.net (142.251.30.139): icmp_seq=3 ttl=111 time=20.8 ms +64 bytes from sv-in-f139.1e100.net (142.251.30.139): icmp_seq=4 ttl=111 time=22.4 ms + +--- google.com ping statistics --- +4 packets transmitted, 4 received, 0% packet loss, time 3018ms +rtt min/avg/max/mdev = 17.764/33.900/74.587/23.550 ms +``` +**Observation** +- You sent 4 packets & You received all 4 back +- 0% packet loss +- Avg Latency : 33.900 +- Average round-trip time is ~34 ms +- So network is stable (no loss) + +# 3. Path Analysis + +**Command** + +```bash +traceroute google.com +``` +**Output** + +```text +ubuntu@Kartik:~/LinuxForDevOps/day14$ traceroute google.com +traceroute to google.com (142.250.151.101), 30 hops max, 60 byte packets + 1 Kartik.mshome.net (172.27.144.1) 0.727 ms 0.733 ms 0.724 ms + 2 192.168.0.1 (192.168.0.1) 3.416 ms 3.355 ms 3.312 ms + 3 * * * + 4 80.255.198.222 (80.255.198.222) 16.828 ms 17.035 ms 16.994 ms + 5 * * * + 6 80.255.204.85 (80.255.204.85) 27.721 ms 15.202 ms 22.795 ms + 7 host-213-104-85.174.not-set-yet.virginmedia.net (213.104.85.174) 18.128 ms 17.153 ms 25.102 ms + 8 * * * + 9 216.239.41.240 (216.239.41.240) 26.259 ms 108.170.234.220 (108.170.234.220) 25.727 ms 209.85.252.180 (209.85.252.180) 26.840 ms +10 172.253.73.196 (172.253.73.196) 19.778 ms 172.253.64.176 (172.253.64.176) 24.029 ms 172.253.74.128 (172.253.74.128) 16.429 ms +11 * * * +12 * * * +13 * * * +14 * * * +15 * * * +16 * * * +17 * * st-in-f101.1e100.net (142.250.151.101) 21.054 ms +``` +**Observation** + +- All the hops (routers) your packet passes through to reach Google. +- Each line = one router in the path. + +**🧭 Total hops observed** : **17** : ```From hop 1 β†’ hop 17``` --> where Google server responded + +**⚠️ Timeouts observed:** ```Hop 3, 5, 8, 11, 12, 13, 14, 15, 16``` + +**🧠 Meaning of these timeouts :** + +- Routers are not replying to ICMP traceroute packets +- NOT a failure +- Very common in ISP + Google backbone networks + +**🧠 Your Full Route** + +``` +[You] + ↓ +172.27.144.1 (VM/Host) -- Your Machine + ↓ +192.168.0.1 (Router) -- Your Network IP(Virgin media wifi ip) + ↓ +ISP Backbone (Virgin Media) + ↓ +Internet Routers (hidden hops) + ↓ +Google Backbone + ↓ +Google Server βœ… + +``` +**Why * * * happens** + +**Routers may ignore traceroute because:** + +- Firewall blocks ICMP replies +- Security hardening +- Rate limiting +- Cloud provider protection +πŸ‘‰ It does NOT mean failure + +**Key Takeaway** + +```traceroute``` shows the internet path, not just the destination β€” revealing how your request travels through routers, ISPs, and cloud backbone networks before reaching Google. + +# 4. Listening Ports + +**It shows what your machine is actually β€œlistening” to.** + +**Command** + +``ss -tulpn`` + +πŸ” What ```ss -tulpn``` means + +```ss = socket statistics``` + +**It shows:** +- Open ports +- Listening services +- TCP/UDP connections +- Which processes are using them + +```text + +ubuntu@Kartik:~/LinuxForDevOps/day14$ ss -tulpn +Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process +udp UNCONN 0 0 127.0.0.54:53 0.0.0.0:* +udp UNCONN 0 0 127.0.0.53%lo:53 0.0.0.0:* +udp UNCONN 0 0 10.255.255.254:53 0.0.0.0:* +udp UNCONN 0 0 127.0.0.1:323 0.0.0.0:* +udp UNCONN 0 0 [::1]:323 [::]:* +tcp LISTEN 0 4096 127.0.0.53%lo:53 0.0.0.0:* +tcp LISTEN 0 4096 127.0.0.54:53 0.0.0.0:* +tcp LISTEN 0 1000 10.255.255.254:53 0.0.0.0:* +tcp LISTEN 0 511 0.0.0.0:80 0.0.0.0:* +tcp LISTEN 0 511 [::]:80 [::]:* + +``` + +**🧠 Your system overview** + +**You currently have:** +- DNS services running (port 53) +- Local system resolver active +- Web server listening on port 80 +- Loopback + private network bindings + +# 5. Name Resolution + +```dig google.com``` + +**This is a perfect real-world DNS resolution trace** + +🌐 What ```dig google.com``` did + +**dig = DNS lookup tool** + +It asked: **What are the IP addresses for google.com?** + +**Output** + +```text +ubuntu@Kartik:~/LinuxForDevOps/day14$ dig google.com + +; <<>> DiG 9.18.39-0ubuntu0.24.04.5-Ubuntu <<>> google.com +;; global options: +cmd +;; Got answer: +;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 11112 +;; flags: qr rd ra; QUERY: 1, ANSWER: 6, AUTHORITY: 0, ADDITIONAL: 1 + +;; OPT PSEUDOSECTION: +; EDNS: version: 0, flags:; udp: 512 +;; QUESTION SECTION: +;google.com. IN A + +;; ANSWER SECTION: +google.com. 63 IN A 142.251.30.101 +google.com. 63 IN A 142.251.30.139 +google.com. 63 IN A 142.251.30.138 +google.com. 63 IN A 142.251.30.100 +google.com. 63 IN A 142.251.30.102 +google.com. 63 IN A 142.251.30.113 + +;; Query time: 31 msec +;; SERVER: 10.255.255.254#53(10.255.255.254) (UDP) +;; WHEN: Sun May 31 12:33:33 BST 2026 +;; MSG SIZE rcvd: 135 +``` +**🌐 Resolved IPs ^** + +``` +142.251.30.101 +142.251.30.139 +142.251.30.138 +142.251.30.100 +142.251.30.102 +142.251.30.113 +``` + +**🧠 Why multiple IPs?** + +Because Google uses: + +πŸ”₯ Load Balancing : Traffic distributed across servers + +🌍 Geo-routing : You connect to nearest data center + +⚑ High availability : If one server fails, others respond + +πŸ‘‰ This is why Google never goes down easily + +# 6. HTTP Check + +```curl -I https://google.com``` + +🌐 What this command does + +```curl -I = send HTTP HEAD request (headers only)``` + +**You are asking: Give me only metadata about google.com, HEADER DETAILS Only not the full page.** + +**Output** + +``` +ubuntu@Kartik:~/LinuxForDevOps/day14$ curl -I https://google.com +HTTP/2 301 +location: https://www.google.com/ +content-type: text/html; charset=UTF-8 +content-security-policy-report-only: object-src 'none';base-uri 'self';script-src 'nonce-KIi4ninNsWjFZ_OPAIpAIw' 'strict-dynamic' 'report-sample' 'unsafe-eval' 'unsafe-inline' https: http:;report-uri https://csp.withgoogle.com/csp/gws/other-hp +date: Sun, 31 May 2026 11:51:42 GMT +expires: Tue, 30 Jun 2026 11:51:42 GMT +cache-control: public, max-age=2592000 +server: gws +content-length: 220 +x-xss-protection: 0 +x-frame-options: SAMEORIGIN +alt-svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000 +``` + +**πŸ” 1. Protocol Used** + +```HTTP/2 301``` + +🧠 Meaning: + +- HTTP/2 β†’ modern, multiplexed web protocol +- 301 β†’ Permanent Redirect + +# 7. Connections Snapshot + +**Command** + +```netstat -an | head``` + +``` +netstat = network statistics +-a = all connections +-n = numeric (no DNS resolution) +``` + +**netstat shows your machine is running DNS resolver services on port 53 and a web server listening on port 80 across IPv4 and IPv6 interfaces.** + +**Output** + +**This output is basically a snapshot of all active network sockets on your machine** + +``` +ubuntu@Kartik:~/LinuxForDevOps/day14$ netstat -an | head +Active Internet connections (servers and established) +Proto Recv-Q Send-Q Local Address Foreign Address State +tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN +tcp 0 0 127.0.0.54:53 0.0.0.0:* LISTEN +tcp 0 0 10.255.255.254:53 0.0.0.0:* LISTEN +tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN +tcp 0 0 127.0.0.1:50638 127.0.0.1:80 ESTABLISHED +tcp 0 0 127.0.0.1:50650 127.0.0.1:80 ESTABLISHED +tcp 0 0 127.0.0.1:80 127.0.0.1:50638 ESTABLISHED +tcp 0 0 127.0.0.1:80 127.0.0.1:50650 ESTABLISHED + +``` +1. ESTABLISHED connections: 4 +2. LISTEN connections: 4 + +--- + +# 8. Mini Task: Port Probe & Interpret + +**Task 1 : Identify one listening port from ss -tulpn (e.g., SSH on 22 or a local web app).** + +``` +ubuntu@Kartik:~/LinuxForDevOps/day14$ ss -tulpn +Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process +udp UNCONN 0 0 127.0.0.54:53 0.0.0.0:* +udp UNCONN 0 0 127.0.0.53%lo:53 0.0.0.0:* +udp UNCONN 0 0 10.255.255.254:53 0.0.0.0:* +udp UNCONN 0 0 127.0.0.1:323 0.0.0.0:* +udp UNCONN 0 0 [::1]:323 [::]:* +tcp LISTEN 0 4096 127.0.0.53%lo:53 0.0.0.0:* +tcp LISTEN 0 4096 127.0.0.54:53 0.0.0.0:* +tcp LISTEN 0 1000 10.255.255.254:53 0.0.0.0:* +tcp LISTEN 0 511 0.0.0.0:80 0.0.0.0:* +tcp LISTEN 0 511 [::]:80 [::]:* +``` + +**Listening Service Identified** + +- Service: DNS Resolver (systemd-resolved) + Web Server + +- Ports: + +1. Port 53 β†’ DNS infrastructure (critical for internet access) +2. Port 80 β†’ Web traffic (HTTP server) + +**Task 2 : From the same machine, test it: ```nc -zv localhost``` (or curl -I http://localhost:).** + +**Command** + +```nc -zv localhost 80``` + +**Output** + +``` +ubuntu@Kartik:~/LinuxForDevOps/day14$ nc -zv localhost 80 +Connection to localhost (127.0.0.1) 80 port [tcp/http] succeeded! +``` + +**OR** + +**Command** + +```curl -I http://localhost:80``` + +**Output** + +```ubuntu@Kartik:~/LinuxForDevOps/day14$ curl -I http://localhost:80 +HTTP/1.1 200 OK +Server: nginx/1.24.0 (Ubuntu) +Date: Sun, 31 May 2026 12:17:18 GMT +Content-Type: text/html +Content-Length: 615 +Last-Modified: Thu, 21 May 2026 06:26:26 GMT +Connection: keep-alive +ETag: "6a0ea592-267" +Accept-Ranges: bytes +``` + +**Interpretation** + +Reachable: Yes / No +If not reachable, next checks: +Verify service status (systemctl status ) +Check firewall rules (ufw status, iptables -L) +Review application logs + + +# 🧠 Networking Reflection (DevOps Troubleshooting Guide) + +# ⚑ 1. Which command gives you the fastest signal when something is broken? + +## πŸ“‘ `ping` +- Quickly confirms basic network connectivity +- Detects packet loss and latency issues + +πŸ‘‰ Use when: +- You suspect network is down +- You want quick connectivity check + +## 🌐 `curl -I` +- Checks if a web service is responding +- Verifies HTTP/HTTPS status without downloading full content + +πŸ‘‰ Use when: +- Website is slow or not loading +- You want to check server availability + +--- + +# 🧩 2. What layer would you inspect if DNS fails? + +## 🌍 Primary Layer: +- **Application Layer (DNS Service)** + +## πŸ” Next checks: +- Transport Layer β†’ UDP/TCP port 53 +- Internet Layer β†’ IP connectivity + +πŸ‘‰ Meaning: +Start from DNS resolver, then move downward in OSI stack if needed. + +--- + +# 🚨 3. What layer would you inspect if HTTP 500 appears? + +## 🌐 Layer: +- **Application Layer** + +## πŸ” What to check: +- Web server logs (nginx / apache) +- Backend application logs +- Database connectivity issues +- API/service dependencies + +πŸ‘‰ Meaning: +HTTP 500 = server-side failure, not network issue + +--- + +# πŸ› οΈ 4. Two follow-up checks during a real incident + +## πŸ”Ž Check active listening services + +```bash id="cmd1" +ss -tulpn +``` +## πŸ”Ž Verify DNS and application response with: + +```dig ``` +```curl -I ``` \ No newline at end of file diff --git a/2026/day-15/day-15-networking-concepts.md b/2026/day-15/day-15-networking-concepts.md new file mode 100644 index 0000000000..a1586c0282 --- /dev/null +++ b/2026/day-15/day-15-networking-concepts.md @@ -0,0 +1,406 @@ +## Day 15 - Understand how DNS resolves names to IPs + +The Domain Name System (**DNS**) is the "phonebook of the Internet". +It translates human-readable domain names (e.g., `google.com`) into machine-readable IP addresses `(e.g., 192.0.2.1)`. + +Computers connect to each other using numbers, so DNS makes browsing the web user-friendly. + +## Task 1. How DNS Resolves Names to IPs + +When you type a web address into your browser, a highly structured sequence of events takes place to locate the correct server. + +**The Short DNS Flow** + +- πŸ“₯ Request: You type a URL `google.com` +- πŸ” Cache: Your device checks local memory first. +- πŸ”„ Resolver: If missing, your ISP server takes over. +- 🌐 Root: The resolver asks Root where the TLD is. +- 🏷️ TLD: The resolver asks .com (or similar) where the domain lives. +- πŸ”‘ Authoritative: The domain's nameserver gives the final IP. +- πŸ–₯️ Connect: The resolver hands the IP to your browser. +- 🌐 Load: The website opens. + +## DNS Record Types + +### A Record +Maps a domain name to an IPv4 address. + +### AAAA Record +Maps a domain name to an IPv6 address. + +### CNAME Record +Creates an alias from one domain name to another domain name. + +### MX Record +Specifies the mail servers responsible for receiving emails for a domain. + +### NS Record +Identifies the authoritative name servers for a domain. + +## `dig` Command + +### Command + +```bash +dig google.com +``` + +### Sample Output (Relevant Section) + +```text +;; ANSWER SECTION: +google.com. 300 IN A 142.250.187.14 +``` + +### Identify the A Record + +- A Record: `142.250.187.14` + +### Identify the TTL + +- TTL: `300` seconds + +### Understanding the Output + +```text +google.com. 300 IN A 142.250.187.14 +β”‚ β”‚ β”‚ +β”‚ β”‚ └── IPv4 Address (A Record) +β”‚ └────────────── TTL (seconds) +└───────────────────────────── Domain Name +``` + +--- + +## Note + +The exact IP address and TTL may vary depending on your location, DNS resolver, and the time the query is executed. + +Run the command below on your machine and record the actual values from the ANSWER SECTION: + +```bash +dig google.com +``` +--- + +## Task 2. IP addressing (IPv4, public vs private) + +An IP address (Internet Protocol address) is a unique label assigned to every device connected to a network. + +It ensures that data packets find the correct destination, similar to a physical mailing address + +**IPv4 Structure** + +- IPv4 uses a 32-bit format, which creates roughly 4.3 billion unique addresses. +- The Format: Written in "dotted-decimal" notation `(e.g., 192.168.1.1)`. +- The Blocks: Divided into four 8-bit numbers called octets. +- The Range: Each octet ranges from 0 to 255 `(e.g., 0.0.0.0 to 255.255.255.255)`. +- The Parts: Contains a Network ID (identifies the specific network) and a Host ID (identifies the specific device on that network). + +**Public vs. Private IP Addresses** + +| Feature | Private IP Address | Public IP Address | +|----------|-------------------|------------------| +| Scope | Internal (local network only) | External (global internet) | +| Visibility | Hidden from the internet | Visible to the entire world | +| Uniqueness | Unique only within your local network | Unique across the entire internet | +| Cost | Completely free to use | Usually assigned/leased by an ISP | +| Routing | Cannot be routed over the public internet | Fully routable across global routers | + +## Private IP Ranges + +These ranges are reserved for internal networks: + +- `10.0.0.0` β†’ `10.255.255.255` +- `172.16.0.0` β†’ `172.31.255.255` +- `192.168.0.0` β†’ `192.168.255.255` + + +## Identify Your IP Addresses (From `ip addr show`) + +### Observed Output +From the `eth0` interface: + +``` +inet 172.27.145.12/20 +``` + +From the `lo` (loopback) interface: + +``` +inet 127.0.0.1/8 +inet 10.255.255.254/32 +``` +## Analysis + +### Primary Private IP (eth0) +- **IP Address:** `172.27.145.12` +- This is your machine’s main network IP +- It is used for communication within your private network + +### Loopback Interface (lo) +- `127.0.0.1` β†’ Standard loopback address (your own machine) +- `10.255.255.254` β†’ Also a private IP assigned to loopback in your environment (virtual routing/internal setup) + +## Are these Private IPs? + +Yes β€” all of the following are private/internal: + +- `172.27.145.12` β†’ Private IP (belongs to 172.16.0.0 – 172.31.255.255 range) +- `10.255.255.254` β†’ Private IP (10.0.0.0 – 10.255.255.255 range) +- `127.0.0.1` β†’ Loopback (special internal testing address) + +## Key Observation + +Your system is running in a **virtualized or cloud-like environment**, which is why: + +- Your main IP is in the **172.27.x.x range** +- This is common in: + - WSL (Windows Subsystem for Linux) + - Docker networks + - Cloud VMs (AWS/Azure internal networking) + +## Final Summary + +- Your active interface: `eth0` +- Your working private IP: `172.27.145.12` +- Loopback is used for internal self-communication +- All observed IPs are non-public (private/internal) + +--- + +# Task 3: CIDR & Subnetting + +## What does `/24` mean in `192.168.1.0/24`? + +`/24` means that the first **24 bits are fixed as the network portion**, and the remaining **8 bits are available for host addresses**. + +- IPv4 address = 32 bits total +- `/24` β†’ 24 bits network + 8 bits host +- This defines a subnet with **256** total IP addresses +# Usable Hosts in Different Subnets (with IP Ranges) + +--- + +## /24 Subnet + +- Example Network: `192.168.1.0/24` +- Subnet Mask: `255.255.255.0` + +### IP Range +- Network Address: `192.168.1.0` +- Usable Hosts: `192.168.1.1 – 192.168.1.254` +- Broadcast Address: `192.168.1.255` + +### Summary +- Total IPs: 256 +- Usable Hosts: 254 + +--- + +## /16 Subnet + +- Example Network: `10.0.0.0/16` +- Subnet Mask: `255.255.0.0` + +### IP Range +- Network Address: `10.0.0.0` +- Usable Hosts: `10.0.0.1 – 10.0.255.254` +- Broadcast Address: `10.0.255.255` + +### Summary +- Total IPs: 65,536 +- Usable Hosts: 65,534 + +--- + +## /28 Subnet + +- Example Network: `192.168.1.0/28` +- Subnet Mask: `255.255.255.240` + +### IP Range +- Network Address: `192.168.1.0` +- Usable Hosts: `192.168.1.1 – 192.168.1.14` +- Broadcast Address: `192.168.1.15` + +### Summary +- Total IPs: 16 +- Usable Hosts: 14 + +## Why Do We Subnet? + +Subnetting is used to divide a large network into smaller, manageable networks. + +### Key reasons: + +- **Efficient IP usage** β†’ avoid wasting IP addresses +- **Better security** β†’ isolate network segments +- **Improved performance** β†’ smaller broadcast domains +- **Easier management** β†’ organize networks by teams/services +- **Scalability** β†’ easier to grow infrastructure + +--- + +## Quick CIDR Table + +| CIDR | Subnet Mask | Total IPs | Usable Hosts | +|------|---------------------|------------|--------------| +| /24 | 255.255.255.0 | 256 | 254 | +| /16 | 255.255.0.0 | 65,536 | 65,534 | +| /28 | 255.255.255.240 | 16 | 14 | + +## Key Formula + +``` +Total IPs = 2^(32 - CIDR) +Usable Hosts = Total IPs - 2 +``` +## Example Breakdown + +### /28 example: +- 32 - 28 = 4 host bits +- 2^4 = 16 total IPs +- 16 - 2 = 14 usable hosts + +--- + +# Task 4: Ports – The Doors to Services + +## What is a Port? + +A **port** is a logical communication endpoint used by operating systems to identify specific services running on a machine. + +### Why do we need ports? + +- A single machine can run multiple services +- IP address identifies the machine +- Port number identifies the specific service on that machine + +πŸ‘‰ Think of it like: +- IP Address = Building address +- Port = Apartment number inside the building + +## Common Ports and Services + +| Port | Service | +|------|----------------| +| 22 | SSH (Secure Shell) | +| 80 | HTTP (Web traffic) | +| 443 | HTTPS (Secure web traffic) | +| 53 | DNS (Domain Name System) | +| 3306 | MySQL Database | +| 6379 | Redis Cache | +| 27017 | MongoDB Database | + +## Checking Listening Ports + +### Command: +```bash +ss -tulpn +``` +## Understanding Output + +Example output snippet: +```text +LISTEN 0 128 0.0.0.0:22 +LISTEN 0 511 0.0.0.0:80 +``` +## Match Ports to Services (Example Interpretation) + +From a typical Linux system: + +- **Port 22** + - Service: SSH + - Used for remote server login + +- **Port 80** + - Service: HTTP + - Used for serving web pages + +--- + +## How to Identify Services in Your Output + +Look for lines like: + +```text +LISTEN 0 128 0.0.0.0:22 users:(("sshd",pid=1234)) +``` + +Interpretation: +- `22` β†’ Port number +- `sshd` β†’ Service name (SSH daemon) + +## Key Takeaway + +- Ports allow multiple services on one machine +- Without ports, only one service could run per IP +- DevOps engineers use `ss -tulpn` daily to debug services + +## Quick Mental Model + +- IP = machine +- Port = service inside machine +- Process = actual program using that port + +--- + +# Task 5: Putting It Together + +--- + +## 1. You run `curl http://myapp.com:8080` β€” what networking concepts are involved? + +This request involves **DNS resolution** to convert `myapp.com` into an IP address. Then a **TCP connection** is established to port `8080` on the server. Finally, the **HTTP protocol (Application layer)** is used to send the request and receive a response. + +--- + +## 2. Your app can't reach a database at `10.0.1.50:3306` β€” what would you check first? + +First, I would check **network connectivity** using `ping 10.0.1.50` and verify if the host is reachable. Then I would check if the **MySQL service is running and listening on port 3306** using `ss -tulpn`. Finally, I would inspect **firewall rules and security groups** that might be blocking access to that port. + +--- + +## Key Thinking Approach + +When troubleshooting: +- Start with **network reachability (IP layer)** +- Then check **port/service availability (Transport layer)** +- Finally verify **application/service health (Application layer)** + +--- + +# IPv4 vs IPv6 + +## IPv4 +- 32-bit addressing system +- Written in decimal format (e.g. `192.168.1.10`) +- Supports ~4.3 billion addresses +- Most widely used in current networks + +## IPv6 +- 128-bit addressing system +- Written in hexadecimal format (e.g. `2001:db8::1`) +- Supports a massive number of addresses +- Designed to replace IPv4 +- Mostly used in IOT, CDNs, AWS, Google + +## Why IPv6 Was Introduced + +# IPv4 addresses are running out due to: + +- Growth of the internet +- Mobile devices +- Cloud infrastructure +- IoT devices + +**IPv6 solves this by providing a massive address space.** + +# Examples + +- inet `172.27.145.12` -- **(IPv4)** +- inet6 `fe80::215:5dff` -- **(IPv6)** + +## Key Difference +IPv4 has limited addresses and uses NAT to cope, while IPv6 was introduced to solve address exhaustion with a much larger address space. \ No newline at end of file diff --git a/2026/day-23/day-23-notes.md b/2026/day-23/day-23-notes.md new file mode 100644 index 0000000000..0303e9af0b --- /dev/null +++ b/2026/day-23/day-23-notes.md @@ -0,0 +1,194 @@ +# Day 23 Notes β€” Git Branching & Working with GitHub + +## βœ… Task Summary +- Create `day-23-notes.md` answering the challenge questions and documenting commands. +- Practice creating branches, switching, committing, pushing to GitHub, and syncing forks. + +--- + +## πŸ”€ 1) What is a branch in Git? +A branch is a movable pointer to a commit. It represents an independent line of development so you can work on features, fixes, or experiments without changing the `main` branch. + +- Example: list branches + +```bash +git branch +``` + +--- + +## πŸ’‘ 2) Why use branches instead of committing everything to `main`? +- Isolate work: keep unfinished or experimental work separate. +- Collaboration: multiple people can work on different features simultaneously. +- Safer history: `main` stays stable and deployable. + +--- + +## 🧭 3) What is `HEAD` in Git? +`HEAD` is a pointer to the current commit (usually the tip of the current branch). When you switch branches, `HEAD` moves to point at the tip of that branch. + +- Show `HEAD` status: + +```bash +git status +``` + +--- + +## πŸ” 4) What happens to your files when you switch branches? +- Git updates your working directory to match the commit that `HEAD` points to on the target branch. Uncommitted changes may be preserved, or Git may ask you to stash/commit them before switching if they would conflict. + +--- + +## πŸ”§ Task 2 β€” Branching Commands (Hands-On) +Commands and examples to perform the requested steps: + +- List branches + +```bash +git branch +``` + +- Create a new branch `feature-1` + +```bash +git branch feature-1 +``` + +- Switch to `feature-1` (modern command) + +```bash +git switch feature-1 +``` + +- Create and switch in one command (`feature-2`) + +```bash +git switch -c feature-2 +# or legacy: git checkout -b feature-2 +``` + +- Difference: `git switch` vs `git checkout` + - `git switch` is focused on switching branches (safer, clearer). + - `git checkout` can switch branches *and* restore files; it's more powerful but more confusing. + +- Make a commit on `feature-1` that does not exist on `main`: + +```bash +# on feature-1 +git add . +git commit -m "Add feature-1 changes" +``` + +- Switch back to `main` and verify the commit is not there + +```bash +git switch main +git log --oneline --decorate --graph -n 5 +``` + +- Delete a branch you no longer need + +```bash +git branch -d feature-1 # safe delete (only if merged) +# or force delete: +git branch -D feature-1 +``` + +- Push branch to remote and set upstream + +```bash +git push -u origin feature-1 +``` + +Add these commands to your `git-commands.md` as practice. + +--- + +## 🌐 Task 3 β€” Push to GitHub +Steps to push to a new GitHub repo (do not initialize remote with README): + +```bash +# create repo on GitHub via website +git remote add origin git@github.com:YOURUSERNAME/devops-git-practice.git +git push -u origin main +git push -u origin feature-1 +``` + +- `origin` vs `upstream`: + - `origin` is the default name for the remote you cloned from (your remote fork or repo). + - `upstream` commonly refers to the original repository you forked from. Use `upstream` when you want to fetch changes from the original project. + +--- + +## πŸ”„ Task 4 β€” Pull from GitHub +- Make a change on GitHub using the editor, then pull locally: + +```bash +git pull +# or fetch then merge manually: +git fetch origin +git merge origin/main +``` + +- `git fetch` vs `git pull`: + - `git fetch` downloads commits and refs from remote into your local repo but does not change your working tree. + - `git pull` is `git fetch` followed by `git merge` (or `git rebase` if configured) into your current branch. + +--- + +## 🍴 Task 5 β€” Clone vs Fork +- `git clone` copies a remote repository to your local machine. + +```bash +git clone https://github.com/OWNER/REPO.git +``` + +- `Fork` (GitHub): creates your own copy of a repository on GitHub. Then clone your fork to work on it. + +When to use which: +- Clone: when you already have write access or are working within the same repo. +- Fork: when you want to contribute to someone else's project without direct write access. + +Keeping your fork in sync with the original repo (common approach): + +```bash +# add upstream once +git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPO.git +# fetch upstream changes +git fetch upstream +# update your main +git switch main +git merge upstream/main +# or rebase +git rebase upstream/main +# push updated main to your fork +git push origin main +``` + +--- + +## βœ… Notes & Recommended Commands to Add to `git-commands.md` +- `git branch`, `git branch ` +- `git switch `, `git switch -c ` +- `git checkout -b ` (legacy) +- `git add .`, `git commit -m "msg"` +- `git push -u origin ` +- `git remote add origin ` +- `git remote add upstream ` +- `git fetch upstream`, `git merge upstream/main` + +--- + +## πŸ“Œ Submission Checklist +- [ ] Add `day-23-notes.md` to `2026/day-23/` (this file) +- [ ] Update `git-commands.md` in your `devops-git-practice` repo +- [ ] Push branches and repo to GitHub + +--- + +If you'd like, I can also: +- Add these commands into your `git-commands.md` for you βœ… +- Run a quick checklist script to verify remote branches (requires shell access) πŸ” + +Happy learning! πŸš€ diff --git a/2026/day-24/day-24-notes.md b/2026/day-24/day-24-notes.md new file mode 100644 index 0000000000..152918d8e2 --- /dev/null +++ b/2026/day-24/day-24-notes.md @@ -0,0 +1,533 @@ +# Day 24 Notes β€” Advanced Git: Merge, Rebase, Stash & Cherry Pick + +## βœ… Overview +Master integrating branches back into `main`, managing work-in-progress, and applying selective commits. These skills separate confident Git practitioners from beginners. + +--- + +## πŸ”€ Task 1: Git Merge β€” Combining Branches + +### What is Git Merge? + +`git merge` combines the changes from one branch into another. There are two types: **fast-forward** and **merge commit**. + +--- + +### Type 1: Fast-Forward Merge + +**When it happens:** +- `main` has not moved since the feature branch was created +- Git can simply move `main` pointer to the feature branch's head +- No new commit is created + +**Example:** +```bash +git switch -c feature-login +# (add commits on feature-login) +git switch main +git merge feature-login +# Result: fast-forward merge (no merge commit) +``` + +**History:** +``` +Before: main ●───── feature-login ●─● +After: main ●─●─● +``` + +--- + +### Type 2: Merge Commit + +**When it happens:** +- Both `main` and the feature branch have new commits since they diverged +- Git creates a **new merge commit** that ties both histories together + +**Example:** +```bash +git switch -c feature-signup +# (add commits on feature-signup) +git switch main +# (add a commit on main) +git merge feature-signup +# Result: merge commit created +``` + +**History:** +``` +Before: main ●─● + β•± + feature-signup ●─● + +After: main ●─●─●─╲ + β•± β•² (merge commit) + feature-signup ●─●─╱ +``` + +--- + +### What is a Merge Conflict? + +A merge conflict occurs when **the same lines** in the **same file** are changed differently on both branches. + +**Example:** +```bash +# On main, line 1: "Hello World" +# On feature-fix, line 1: "Hello Universe" +git merge feature-fix +# Conflict! Git cannot auto-merge +``` + +**Git marks the conflict:** +``` +<<<<<<< HEAD +Hello World +======= +Hello Universe +>>>>>>> feature-fix +``` + +**To resolve:** +1. Edit the file and choose which version to keep +2. `git add ` +3. `git commit` to complete the merge + +--- + +### Commands + +```bash +git merge # Merge branch into current branch +git merge --no-ff # Force merge commit (no fast-forward) +git merge --squash # Squash and merge (see Task 3) +git merge --abort # Cancel merge if conflicts exist +``` + +--- + +## πŸ“ Task 2: Git Rebase β€” Rewriting History + +### What is Git Rebase? + +`git rebase` moves your commits on top of another branch. It **rewrites history** to create a linear, cleaner commit history. + +--- + +### How Rebase Works + +```bash +git switch -c feature-dashboard +# (add commits A, B, C) +git switch main +# (add commit D) +git switch feature-dashboard +git rebase main +``` + +**Before rebase:** +``` +main ●─●─D + β•± +feature-dashboard A─B─C +``` + +**After rebase:** +``` +main ●─●─D + β•± + A'─B'─C' (feature-dashboard) +``` + +Git **replays** commits A, B, C on top of D (creating new commits A', B', C'). + +--- + +### Rebase vs Merge: History Comparison + +**Merge approach:** +```bash +git merge feature-dashboard +``` + +``` +●─●─D─╲ + β•² (merge commit) +A─B─C─╱ +``` + +**Rebase approach:** +```bash +git rebase main +git switch main && git merge feature-dashboard +``` + +``` +●─●─D─A'─B'─C' +``` + +Rebase creates a **linear** history; merge creates a **branching** history. + +--- + +### ⚠️ Never Rebase Shared Commits + +**Why:** +- Rebase rewrites history +- Others who have the original commits will have diverged history +- Causes conflicts and confusion for the team +- Results in duplicate commits + +**Safe rule:** +```bash +# βœ… Safe: rebase before pushing (local only) +git rebase main +git push -u origin feature-dashboard + +# ❌ Unsafe: rebasing already pushed commits +git push origin feature-dashboard +git rebase main # DON'T DO THIS +git push -f origin feature-dashboard # Force push breaks for teammates +``` + +--- + +### When to Use Rebase vs Merge + +| Scenario | Use | +|---|---| +| Before pushing a feature | βœ… Rebase (clean history) | +| Integrating into shared branch | βœ… Merge (preserves history) | +| Local-only branch cleanup | βœ… Rebase | +| Already pushed to team | βœ… Merge | +| Want linear history | βœ… Rebase | +| Want to preserve all history | βœ… Merge | + +--- + +### Commands + +```bash +git rebase # Rebase current branch onto +git rebase main --interactive # Interactive rebase (edit commits) +git rebase --continue # After resolving conflicts +git rebase --abort # Cancel rebase +``` + +--- + +## πŸ”„ Task 3: Squash Commits vs Merge Commit + +### What is Squash Merging? + +`git merge --squash` combines all commits from a branch into **one single commit** before merging. + +--- + +### Squash Merge Example + +```bash +git switch -c feature-profile +# Commit 1: Add profile form +# Commit 2: Fix typo in form +# Commit 3: Add profile styling +# Commit 4: Fix mobile responsive + +git switch main +git merge --squash feature-profile +git commit -m "Add user profile feature" +``` + +**Result:** +``` +main ●─●─● (single squashed commit) + β””β”€β”€β”€β”€β”€β”˜ (replaces 4 commits) +``` + +--- + +### Regular Merge Example + +```bash +git switch -c feature-settings +# Commit 1: Add settings page +# Commit 2: Add dark mode toggle +# Commit 3: Save user preferences + +git switch main +git merge feature-settings +# (creates merge commit) +``` + +**Result:** +``` +main ●─●─●─╲ + β•² (merge commit + 3 individual commits visible) +A─B─C───────╱ +``` + +--- + +### Squash vs Regular: Comparison + +| Aspect | Squash | Regular | +|---|---|---| +| **Number of commits** | 1 (squashed) | All commits preserved | +| **History clarity** | Clean, simple | Detailed, shows work | +| **Git log readability** | Better for large features | Better for tracking changes | +| **Blame/git log -p** | Harder to find specific change | Easier to find specific commit | +| **When to use** | Many small commits, feature branch | Shared branches, want full history | + +--- + +### When to Use Each + +- **Squash:** Feature branches with many tiny commits (typos, formatting, iterations) +- **Regular:** Stable branches where you want to see all work done + +--- + +### Commands + +```bash +git merge --squash # Squash merge (stages changes, you commit) +git merge # Regular merge (preserves all commits) +``` + +--- + +## πŸ’Ύ Task 4: Git Stash β€” Saving Work-in-Progress + +### What is Git Stash? + +`git stash` temporarily saves uncommitted changes so you can switch branches without losing work. + +--- + +### Stash Workflow + +**Scenario:** +```bash +# You're on feature-A with uncommitted changes +# Urgent: need to switch to main to fix a bug + +# Without stash (Git blocks you): +git switch main +# error: Your local changes to 'file.txt' would be overwritten + +# With stash: +git stash +git switch main +# (do urgent work) +git switch feature-A +git stash pop +# (your changes are back) +``` + +--- + +### Stash vs Commit + +| | Stash | Commit | +|---|---|---| +| **Purpose** | Temporary, cleanup before switching | Permanent record | +| **When to use** | Context switch, work-in-progress | Completed work | +| **History** | Not in git log | Visible in git log | + +--- + +### Stash Commands + +```bash +git stash # Save uncommitted changes +git stash save "message" # Stash with description +git stash list # List all stashes +git stash pop # Apply and remove latest stash +git stash apply # Apply latest stash (keep it) +git stash apply stash@{2} # Apply specific stash +git stash drop # Delete latest stash +git stash drop stash@{1} # Delete specific stash +git stash clear # Delete all stashes +``` + +--- + +### Difference: `pop` vs `apply` + +**`git stash pop`:** +```bash +git stash pop +# Applies the stash AND removes it from the stash list +``` + +**`git stash apply`:** +```bash +git stash apply +# Applies the stash but KEEPS it in the stash list +# Useful if you want to apply to multiple branches +``` + +--- + +### Real-World Workflow Example + +```bash +# Working on feature-A +git add file.txt +# (unstaged changes exist) + +# Urgent bug needs fixing on main +git stash save "WIP: feature-A progress" +git switch main + +# Fix the bug +git add . && git commit -m "Fix urgent bug" +git push + +# Back to feature-A +git switch feature-A +git stash pop +# Continue feature-A work +``` + +--- + +## 🎯 Task 5: Cherry-Pick β€” Selective Commit Application + +### What is Cherry-Pick? + +`git cherry-pick` applies a **specific commit** from one branch to another, without merging the entire branch. + +--- + +### Cherry-Pick Workflow + +```bash +git switch -c feature-hotfix +# Commit A: Fix login bug +# Commit B: Add logging +# Commit C: Optimize database query + +# Only commit A needs to go to main immediately +git switch main +git cherry-pick +# (only commit A is applied to main) +``` + +**Before:** +``` +main ●─● + β•± +feature-hotfix A─B─C +``` + +**After:** +``` +main ●─●─A' + β•± +feature-hotfix A─B─C +``` + +--- + +### Real-World Use Cases + +- πŸ› **Hotfix:** Cherry-pick a bug fix from develop to production +- πŸ“¦ **Backport:** Apply a commit to an older release branch +- 🎯 **Selective features:** Apply only specific commits, skip others +- πŸ”€ **Merge conflicts:** Apply one commit when full merge has conflicts + +--- + +### Cherry-Pick Commands + +```bash +git cherry-pick # Apply specific commit +git cherry-pick # Apply multiple commits +git cherry-pick main..feature-branch # Apply all commits in range +git cherry-pick --continue # After resolving conflicts +git cherry-pick --abort # Cancel cherry-pick +``` + +--- + +### Finding Commit Hash + +```bash +git log --oneline feature-hotfix +# a1b2c3d Fix login bug +# d4e5f6g Add logging +# h7i8j9k Optimize database + +git cherry-pick a1b2c3d +``` + +--- + +### ⚠️ Risks of Cherry-Picking + +- **Duplicate commits:** Same changes applied twice (messy history) +- **Conflicts:** Cherry-picked commit may conflict in the target branch +- **Lost context:** Changes without their related commits may break things +- **Testing:** Changes may not work in isolation + +**Best practice:** Use cherry-pick sparingly, prefer merge when possible. + +--- + +## πŸ› οΈ Complete Command Reference (Days 22–25) + +### Merge & Rebase +```bash +git merge # Merge branch into current +git merge --no-ff # Force merge commit +git merge --squash # Squash merge (combine into 1 commit) +git rebase # Rebase current onto branch +git rebase -i HEAD~3 # Interactive rebase (edit last 3 commits) +``` + +### Stash +```bash +git stash # Save work-in-progress +git stash list # List all stashes +git stash pop # Apply and remove +git stash apply stash@{0} # Apply without removing +git stash drop stash@{1} # Delete specific stash +``` + +### Cherry-Pick +```bash +git cherry-pick # Apply specific commit +git cherry-pick # Apply multiple commits +git cherry-pick --continue # After resolving conflicts +``` + +### Viewing History +```bash +git log --oneline --graph --all # Visual branch history +git log --decorate # Show branch names +git show # Show specific commit details +``` + +--- + +## πŸŽ“ Summary & Key Takeaways + +βœ… **Merge:** Combines branches, preserves both histories +βœ… **Rebase:** Rewrites history linearly (local only, before push) +βœ… **Squash:** Combines multiple commits into one (clean history) +βœ… **Stash:** Temporarily saves WIP without committing +βœ… **Cherry-Pick:** Applies specific commits selectively +βœ… **Conflicts:** Resolve by editing files, then add & commit +βœ… **Never rebase shared commits** β€” use merge instead + +--- + +## πŸ“ Submission Checklist + +- [ ] Create `day-24-notes.md` (this file) +- [ ] Perform all hands-on tasks in `devops-git-practice` repo +- [ ] Update `git-commands.md` with all commands +- [ ] Commit and push to your fork +- [ ] Share merge vs rebase comparison on LinkedIn + +Happy learning! πŸš€ diff --git a/2026/day-25/day-25-notes.md b/2026/day-25/day-25-notes.md new file mode 100644 index 0000000000..5239468c5d --- /dev/null +++ b/2026/day-25/day-25-notes.md @@ -0,0 +1,447 @@ +# Day 25 Notes β€” Git Reset vs Revert & Branching Strategies - Date : 6th - June - 2026 + +## βœ… Overview +Master **undoing mistakes safely** and understand **branching strategies** used by engineering teams at scale. + +--- + +## πŸ”™ Task 1: Git Reset β€” Understanding the Three Modes + +### What is `git reset`? +`git reset` moves the `HEAD` pointer to a previous commit, optionally discarding or preserving changes. + +--- + +### Mode 1: `git reset --soft` + +**What happens:** +- `HEAD` moves to the target commit +- Staging area is updated to match that commit +- **Working directory is NOT changed** β€” your modified files remain + +**Use case:** You want to undo commits but keep changes staged, ready to recommit differently. + +```bash +git reset --soft HEAD~1 +``` + +**Example:** +```bash +# After reset --soft +# Your changes are still there, staged and ready to recommit +git status +# On branch main +# Changes to be committed: +# modified: file.txt +``` + +--- + +### Mode 2: `git reset --mixed` (Default) + +**What happens:** +- `HEAD` moves to the target commit +- Staging area is updated to match that commit +- **Working directory is NOT changed** β€” modified files remain, but are **unstaged** + +**Use case:** You want to undo commits and unstage changes so you can selectively re-add them. + +```bash +git reset --mixed HEAD~1 +# or simply: +git reset HEAD~1 +``` + +**Example:** +```bash +# After reset --mixed +# Your changes are still there, but unstaged +git status +# On branch main +# Changes not staged for commit: +# modified: file.txt +``` + +--- + +### Mode 3: `git reset --hard` ⚠️ DESTRUCTIVE + +**What happens:** +- `HEAD` moves to the target commit +- Staging area is updated to match that commit +- **Working directory IS changed** β€” all uncommitted changes are **discarded** + +**Use case:** You want to completely undo commits and lose all local changes (dangerous!). + +```bash +git reset --hard HEAD~1 +``` + +**Example:** +```bash +# After reset --hard +# Your uncommitted changes are gone forever! +git status +# On branch main +# nothing to commit, working tree clean +``` + +--- + +### 🎯 Key Differences: Soft vs Mixed vs Hard + +| Mode | HEAD | Staging Area | Working Directory | Safe? | +|------|------|--------------|-------------------|-------| +| `--soft` | Moves | Updated | Unchanged | βœ… Yes | +| `--mixed` | Moves | Updated | Unchanged | βœ… Yes | +| `--hard` | Moves | Updated | **Discarded** | ⚠️ No | + +--- + +### ⚠️ Which is Destructive and Why? + +**`git reset --hard` is destructive** because it permanently deletes uncommitted changes in your working directory. You cannot recover them unless they were previously committed. + +--- + +### πŸ“‹ When to Use Each + +- **`--soft`:** Redo your last commit with different changes (keep everything staged) +- **`--mixed`:** Undo commits and pick-and-choose what to re-stage +- **`--hard`:** Completely discard all changes and go back to a clean state (use with caution!) + +--- + +### ⚑ Should You Use `git reset` on Pushed Commits? + +**Short answer: NO, never on shared branches.** + +**Why:** +- `git reset` rewrites history +- Others who pulled those commits will have conflicts +- Their local history won't match the remote + +**Safe alternative:** Use `git revert` for shared branches (see Task 2). + +**When reset is OK:** +- On local-only branches (not yet pushed) +- On your personal fork before pushing + +--- + +## πŸ”„ Task 2: Git Revert β€” The Safe Way to Undo + +### What is `git revert`? + +`git revert` creates a **new commit** that undoes the changes from a previous commit. It **does NOT rewrite history**. + +```bash +git revert +``` + +--- + +### How it Works + +1. You specify a commit to revert +2. Git creates a **new commit** that reverses those changes +3. The original commit **stays in history** +4. The new commit is added to the top + +**Example:** + +```bash +# Current history: +# commit C (HEAD) +# commit B +# commit A + +git revert B +# Result: +# commit C' (new, with B's changes reversed) +# commit C +# commit B +# commit A +``` + +--- + +### βœ… Is Commit Y Still in History? + +**Yes!** When you revert commit Y, commit Y remains in the history. A **new commit** is created that reverses Y's changes. + +```bash +git log --oneline +# c9f3e2c Revert commit Y +# 4b2a1d1 commit Z +# 7e5f8c0 commit Y +# 9a3d2f1 commit X +``` + +--- + +### 🀝 Why Revert is Safer for Shared Branches + +- `git revert` **preserves history** β€” no rewrites, no surprises +- Everyone who pulled the original commit can still see it +- Safe to use on branches others depend on +- Can be easily reverted again if needed + +--- + +### πŸ”€ When to Use Revert vs Reset + +- **Use `reset`:** On local-only branches, before pushing +- **Use `revert`:** On shared/pushed branches, in production code + +--- + +## πŸ“Š Task 3: Reset vs Revert Comparison + +| | `git reset` | `git revert` | +|---|---|---| +| **What it does** | Moves `HEAD` to previous commit | Creates new commit that undoes changes | +| **Removes commit from history?** | Yes β€” history is rewritten | No β€” original commit stays | +| **Safe for shared/pushed branches?** | ❌ No (rewrites history) | βœ… Yes (preserves history) | +| **When to use** | Local branches before push | Shared/production branches | +| **Undoing the undo** | Difficult (`git reflog` helps) | Easy (`git revert `) | +| **Performance** | Fast | Slightly slower (creates commit) | + +--- + +## 🌳 Task 4: Branching Strategies + +### Strategy 1: GitFlow + +**Overview:** +GitFlow uses multiple long-lived branches for different purposes. It's structured and suitable for scheduled releases. + +**Branches:** +- `main` β€” production-ready code (stable) +- `develop` β€” integration branch (pre-release) +- `feature/*` β€” new features (from `develop`) +- `release/*` β€” release preparation (from `develop`) +- `hotfix/*` β€” urgent production fixes (from `main`) + +**Flow Diagram:** +``` + main (v1.0) + ↑ ↑ + | | + hotfix release/1.0 + | ↓ + -----+----+-----develop + | / | \ + feature/A / | \ feature/B + / | \ +``` + +**When used:** +- Large teams with formal release cycles +- Enterprise applications +- Examples: Git, Android OS, large open-source projects + +**Pros:** +- βœ… Clear separation of concerns +- βœ… Easy to manage multiple versions in parallel +- βœ… Hotfixes isolated from ongoing development + +**Cons:** +- ❌ Complex (many branch types) +- ❌ Slower release cycle +- ❌ Overhead for small teams + +--- + +### Strategy 2: GitHub Flow + +**Overview:** +GitHub Flow is simple and continuous. One main branch, short-lived feature branches, and pull requests. + +**Branches:** +- `main` β€” always deployable +- `feature/` β€” short-lived feature branches (from `main`) +- Pull Request β†’ Code Review β†’ Merge β†’ Deploy + +**Flow Diagram:** +``` + main (always ready to deploy) + ↑ ↑ ↑ + | | | + PR3 PR2 PR1 + | | | + feature-C feature-B feature-A +``` + +**When used:** +- Startups and fast-moving teams +- Continuous deployment environments +- Examples: GitHub itself, many modern SaaS products + +**Pros:** +- βœ… Simple to understand and implement +- βœ… Fast feedback loop +- βœ… Continuous deployment friendly + +**Cons:** +- ❌ Requires discipline (main must always be deployable) +- ❌ No long-term support for older versions +- ❌ Hard to manage multiple active releases + +--- + +### Strategy 3: Trunk-Based Development + +**Overview:** +Everyone commits directly to the main trunk (`main` or `trunk`). Feature branches are extremely short-lived (hours, not days). + +**Branches:** +- `main` β€” single source of truth +- `feature/` β€” short-lived (1-2 days max) +- Feature flags control new code visibility + +**Flow Diagram:** +``` +main ●─●─●─●─●─●─●─●─●─●─●─● + ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ + (rapid commits) +``` + +**When used:** +- High-velocity teams (Google, Netflix, Facebook) +- CI/CD-heavy workflows +- Large-scale distributed development + +**Pros:** +- βœ… Minimal merge conflicts +- βœ… Forces small, reviewable commits +- βœ… Continuous integration friendly + +**Cons:** +- ❌ Requires excellent test coverage +- ❌ High discipline required +- ❌ Hard for inexperienced teams + +--- + +### 🎯 Answering the Strategy Questions + +**Q: Which strategy for a startup shipping fast?** +- **Answer:** GitHub Flow β€” simple, fast, continuous deployment. + +**Q: Which strategy for a large team with scheduled releases?** +- **Answer:** GitFlow β€” structured, supports multiple versions. + +**Q: Which does your favorite open-source use?** +- **Examples:** + - React, Vue: GitHub Flow (rapid releases) + - Linux Kernel: Trunk-based with release branches + - Many enterprises: GitFlow (stable, versioned) + +Check by looking at the repo's branch structure on GitHub. + +--- + +## πŸ› οΈ Task 5: Git Commands Reference Update + +### Complete Git Command Reference (Days 22–25) + +#### Setup & Config +```bash +git config --global user.name "Your Name" +git config --global user.email "your@email.com" +git config --list +``` + +#### Basic Workflow +```bash +git init # Initialize a new repo +git add # Stage a file +git add . # Stage all changes +git status # View staged/unstaged changes +git commit -m "message" # Create a commit +git log --oneline # Show commit history +git log --graph --decorate --oneline # Visual history +git diff # Show unstaged changes +git diff --staged # Show staged changes +``` + +#### Branching +```bash +git branch # List local branches +git branch -a # List all branches (local + remote) +git branch # Create a branch +git switch # Switch to a branch (modern) +git checkout # Switch to a branch (legacy) +git switch -c # Create and switch in one command +git branch -d # Delete a branch (safe) +git branch -D # Force delete a branch +``` + +#### Remote & Sync +```bash +git remote add origin # Add remote +git remote -v # View remotes +git push -u origin # Push branch and set upstream +git push # Push current branch +git pull # Fetch and merge +git fetch # Download changes (no merge) +git clone # Clone a repository +git clone --depth 1 # Shallow clone +``` + +#### Merging & Rebasing +```bash +git merge # Merge branch into current +git rebase # Rebase current onto branch +git cherry-pick # Apply specific commit +``` + +#### Stash +```bash +git stash # Save work temporarily +git stash list # View stashed changes +git stash pop # Apply and remove stash +git stash apply # Apply stash without removing +git stash drop # Delete a stash +``` + +#### Reset & Revert +```bash +git reset --soft HEAD~1 # Undo commit, keep staged +git reset --mixed HEAD~1 # Undo commit, unstage changes +git reset --hard HEAD~1 # Undo commit, discard changes +git revert # Create commit that undoes changes +git reflog # View all Git operations (safety net) +``` + +#### Viewing History +```bash +git log # View commit history +git log --oneline -n 5 # Last 5 commits +git log --author="name" # Filter by author +git log -p # Show detailed changes +git show # Show specific commit +``` + +--- + +## πŸŽ“ Summary & Key Takeaways + +βœ… **Git Reset:** Use for local branches to rewrite history (destructive) +βœ… **Git Revert:** Use for shared branches to safely undo changes +βœ… **GitFlow:** Best for scheduled releases, large teams +βœ… **GitHub Flow:** Best for startups, continuous deployment +βœ… **Trunk-Based:** Best for high-velocity, experienced teams +βœ… **`git reflog`:** Your safety net after dangerous operations + +--- + +## πŸ“ Submission Checklist + +- [ ] Create `day-25-notes.md` (this file) +- [ ] Update `git-commands.md` with all commands from Days 22–25 +- [ ] Commit and push to your fork +- [ ] Share learning on LinkedIn + +Happy learning! πŸš€ diff --git a/README.md b/README.md index aff67ddb9c..8f5801efa0 100644 --- a/README.md +++ b/README.md @@ -127,4 +127,3 @@ One day at a time. One commit at a time. Happy Learning -**TrainWithShubham**