Skip to main content
< All Topics

Linux

Linux is the most popular “Open Source” operating system in the world. Unlike Windows, which you buy, Linux is free and created by a community. It is the backbone of the internet most servers, supercomputers, and cloud platforms (like AWS and Azure) run on Linux. If you want a career in IT, DevOps, or Cloud, Linux is not optional; it is mandatory.

Linux is built on a “Kernel.” The Kernel is the core that talks to the hardware (CPU, RAM). The “OS” is the kernel plus all the tools we use (like the file manager and shell).

Because Linux is open source, many groups have created their own “flavors” called Distributions (Distros):

DevSecOps Architect Level

At an architect level, you don’t just “use” Linux; you optimize it. You need to understand how the Kernel manages resources.

  • Kernel Namespaces & Cgroups: These are the secret sauce behind Docker and Kubernetes. They allow processes to be isolated (containerization).
  • Immutability: Modern DevSecOps architects prefer “Immutable OS” (like Flatcar Linux) where the OS cannot be changed after deployment, preventing security drifts.
  • Kernel Hardening: Using tools like SELinux or AppArmor to lock down what programs can do.

Linux File System

In Windows, you are used to C: DriveD: Drive, and folders like “My Documents” or “Program Files.” In Linux, there are no drives like C: or D:. Everything starts from one single point called Root, represented by a forward slash (/). Every file, folder, and even your hard disk or pen drive is strictly inside this Root.

The Linux directory structure follows a standard layout. You don’t need to memorize everything, but remember these crucial ones:

  • / (Root): Top of the hierarchy.
  • /root: The home folder specifically for the Super User (Administrator).
  • /home/username: Your personal space. (e.g., /home/rahul/).
  • /etc: Configuration files. If you want to change network settings or wifi passwords, you look here.
  • /var: Variable data. System logs (/var/log) are stored here.
  • /tmp: Temporary files. Files here are automatically deleted when the computer restarts.
  • /bin & /usr/bin: Binaries (programs) required to run commands.


Basic Linux Commands

In Windows, you use a mouse to click folders, copy files, and open applications. In Linux servers, there is no mouse. You use commands to tell the computer what to do. These commands are very powerful and faster than clicking.

These are the daily survival commands. You must practice these until your fingers remember them automatically.

  • Navigation:
    • pwd (Print Working Directory): Tells you exactly which folder you are standing in.
    • ls (List): Shows files in the folder. Use ls -l for details (size, date) and ls -a for hidden files.
    • cd (Change Directory): Moves you to another folder. cd .. takes you one step back.
  • File Operations:
    • touch filename: Creates an empty file.
    • mkdir foldername: Creates a new folder (directory).
    • cp source dest: Copies a file (Duplicate).
    • mv old new: Moves a file (Cut-Paste) OR Renames a file.
    • rm file: Deletes a file. Warning: There is no Recycle Bin in command line Linux!
  • Viewing Content:
    • cat file: Dumps the whole file content on screen.
    • less file: Opens file in a readable view (scroll up/down).
    • head / tail: Shows the top 10 lines or bottom 10 lines of a file.


File Permissions & Ownership 

Linux is designed for multiple users. Imagine 10 people using one computer. You don’t want Person A to delete Person B’s files. That is why Linux attaches “Permissions” to every single file. Every file has three types of access:

  1. Read (r): You can see the file.
  2. Write (w): You can edit or delete the file.
  3. Execute (x): You can run the file (like a program).

Think of Permissions as a Personal Diary in a Joint Family.

  • User (Owner – You): You can Read and Write in your diary. (rw)
  • Group (Family): You might let your siblings Read it, but not Write in it. (r--)
  • Others (Guests/Strangers): You don’t want them to even see it exists. No permission. (---)

When you type ls -l, you see something like -rwxvr-xr--. Let’s break this code:

  • The first character - means it’s a file (d means directory).
  • First 3 letters (Owner): rwx (Owner has full power).
  • Next 3 letters (Group): r-x (Group can read and run, but not edit).
  • Last 3 letters (Others): r-- (Outsiders can only read).

Two ways to change permissions:

  1. Numeric (Professional Way):
    • Read = 4
    • Write = 2
    • Execute = 1
    • Example: chmod 755 file (Owner=4+2+1=7, Group=4+0+1=5, Others=4+0+1=5).
  2. Symbolic (Easy Way):
    • chmod u+x file (Add execute to user).

DevSecOps Architect Level

At an architect level, permissions are about “The Principle of Least Privilege”. You never give full access (777) unless absolutely necessary.

  • SUID & SGID: Special permissions that allow a user to run a file with the owner’s permission (like running a password change command as root).
  • ACLs (Access Control Lists): Standard rwx is limited (only one owner, one group). Architects use setfacl to give permissions to specific multiple users without changing groups.
  • Security Context: In clouds like AWS, if permissions are wrong (chmod 400 for keys), the connection fails instantly.

Cheat Sheet

NumberLogicMeaning
74+2+1Read + Write + Execute (Full)
64+2Read + Write (No Run)
54+1Read + Execute (No Edit)
44Read Only
00No Access

Users & Groups Management

A Linux machine is a multi-user system. Even if you are the only person using the laptop, Linux runs many “Background Users” (like www-data for web servers) to keep things safe.

  • User: A specific person or service.
  • Group: A team of users who share permissions.
  • Root: The “Super User” or God of the system. Root can do anything.

Think of Users & Groups as Corporate Employees.

  • Root: The CEO. Can enter any room, fire anyone.
  • User: An employee. Has an ID card (User ID / UID).
  • Group: A Department (e.g., “DevOps Team”). If you join the DevOps group, you automatically get access to the DevOps server room.

You need to know how to add people and assign them to teams.

  • Files that store data:
    • /etc/passwd: Stores user info (Open to all).
    • /etc/shadow: Stores encrypted passwords (Secret).
    • /etc/group: Stores group info.
  • Key Commands:
    • useradd name: Create a new user.
    • passwd name: Set a password for them.
    • groupadd devops: Create a new group.
    • usermod -aG group user: Add a user to a group (Critical command!).

DevSecOps Architect Level

Architects deal with Identity Access Management (IAM). We rarely create users manually on 1000 servers.

  • Centralized Authentication: We use tools like LDAP or Active Directory so a user can log into any server with one password.
  • Sudoers File (/etc/sudoers): We never share the Root password. Instead, we give specific users sudo access. We edit this file using visudo (never edit it directly!).
  • Service Accounts: We create “System Users” (users with no shell access) just to run specific apps like Docker or Jenkins securely.

Practical Labs

  1. Create a User: sudo useradd testuser
  2. Check entry: tail -1 /etc/passwd
  3. Create Group: sudo groupadd testgroup
  4. Add User to Group: sudo usermod -aG testgroup testuser
  5. Check: id testuser

Cheat Sheet

CommandUsageTip
useraddCreate new userAlways use -m to create home folder.
passwdChange passwordOnly root can change others’ passwords.
usermodModify user-aG adds to group without removing old ones.
userdelDelete useruserdel -r removes files too.
idShow user detailsUseful for checking group access.

Process Management

Every time you open a program like Chrome, Spotify, or Python Linux creates a “Process”. A process is just a running program. Sometimes, programs hang or consume too much CPU. As a Linux Admin, you are the “Traffic Police.” You decide which process runs, which one waits, and which one gets “Killed” (stopped forcefully).

Think of Process Management as a Kitchen Manager.

  • CPU: The Stove (doing the actual work).
  • RAM: The Kitchen Table (holding ingredients ready to cook).
  • Process: A single dish being cooked (e.g., Making Tea).
  • PID (Process ID): The Token Number for that dish.
  • Kill: Throwing a burnt dish into the dustbin to stop it from ruining the kitchen.

Every process has a unique ID called PID. You need this ID to control the process.

  • Viewing Processes:
    • top: Shows real-time CPU/RAM usage (Like Windows Task Manager).
    • htop: A colorful, easier version of top.
    • ps -ef: Lists every process running on the system right now.
  • Stopping Processes:
    • kill PID: Asks the process nicely to stop.
    • kill -9 PID: Forces the process to die immediately (Use this if it’s frozen).

Architects care about Stability and Priority.

  • Background vs Foreground:
    • Running python app.py locks your terminal (Foreground).
    • Running python app.py & runs it in the background so you can keep working.
  • Zombie Processes: These are “Dead” processes that are still taking up space in the process table. They happen when a parent process dies but the child process is still confused.
  • Nice & Renice: You can change the priority of a process.
    • Value ranges from -20 (Highest Priority) to +19 (Lowest Priority).
    • If a backup script is slowing down the web server, we “renice” it to +19 so it only runs when the CPU is free.

Use Case

The “Frozen” Web Server: Your company website is loading very slowly.

  1. You login and run top.
  2. You see a process named backup_script using 99% CPU.
  3. Note the PID (e.g., 4512).
  4. Run kill -9 4512.
  5. The website instantly becomes fast again.

Technical Challenges

  • Killing the Wrong PID: If you accidentally kill PID 1 (Systemd/Init), the server will crash immediately.
  • Memory Leaks: Some badly written apps keep eating RAM until the server freezes (OOM – Out of Memory Crash).

Practical Labs

  1. Start a dummy sleep process: sleep 1000 &
  2. Find it: ps -ef | grep sleep
  3. Kill it: Note the PID and run kill <PID>.
  4. Check again: Run ps -ef | grep sleep (It should be gone).

Cheat Sheet

CommandUsageReal Life Logic
topReal-time MonitorCCTV Camera
ps -efList all historyGuest List
kill PIDStop ProcessAsking “Please Leave”
kill -9 PIDForce KillKicking them out
bgSend to Background“Go stand in the back”
fgBring to Foreground“Come to the stage”

Disk & Storage Management

Storage in Linux is different. In Windows, you plug in a Pen Drive and it pops up as E: Drive. In Linux, you have to manually “Mount” it (connect it) to a folder. Managing disk space is the #1 responsibility of an Admin because if the disk gets full, the server stops working.

Think of Storage as Warehouses.

  • Hard Disk: A physical Warehouse building.
  • Partition: Dividing the warehouse into rooms (Room A, Room B).
  • Mounting: Putting a sign on the door saying “This room is for Toys (/data)”. If you don’t put the sign (mount), you cannot put anything inside.

  • Checking Space:
    • df -h (Disk Free): Shows total space on hard disks. (The -h makes it human-readable: GB/MB instead of bytes).
    • du -sh foldername (Disk Usage): Tells you the size of a specific folder.
  • Listing Disks:
    • lsblk: Lists all attached block devices (Hard disks, SSDs, USBs).

DevSecOps Architect Level

Architects use LVM (Logical Volume Management).

  • Static Partitioning (Old way): You give 10GB to a database. If it fills up, you are stuck.
  • LVM (Modern way): You create a “pool” of storage. If the database needs more space, you can add 5GB “on the fly” without shutting down the server.
  • Mount Points:
    • /etc/fstab: This file controls which disks are mounted automatically when the computer starts. If you mess up this file, the computer won’t boot!

Use Case

Adding Storage to a Database Server: The /var/lib/mysql partition is full.

  1. You attach a new 100GB SSD to the server (physically or via AWS EBS).
  2. Run lsblk to see the new disk (e.g., /dev/xvdf).
  3. Format it: mkfs.ext4 /dev/xvdf.
  4. Mount it: mount /dev/xvdf /var/lib/mysql.
  5. Database is happy again.

Technical Challenges

  • Inodes Full: Sometimes df -h shows 50% free space, but you can’t create files. This is because “Inodes” (file index cards) are full (usually caused by millions of tiny files). Check with df -i.

Practical Labs

  1. Check Disks: Run lsblk.
  2. Check Space: Run df -h. Look for /.
  3. Check Folder Size: Run du -sh /var/log.

Cheat Sheet

CommandMeaningTip
lsblkList Blocks (Disks)Tree view of disks.
df -hDisk FreeChecks total capacity.
du -shDisk UsageChecks specific folder size.
mountConnect Diskmount /dev/sdb1 /data
umountDisconnect Diskumount /data

Networking in Linux

Networking is how your Linux machine connects to the internet or other computers. Every computer on a network needs an address, just like your house needs a postal address. In the computer world, this is called an IP Address. You also have Ports. If the IP address is the building, the “Port” is the specific door number to enter a specific room (Service).

Think of Networking as a Courier Service.

  • IP Address: The House Address (e.g., House No. 20, MG Road).
  • Port: The specific person in the house you want to meet.
    • Port 80 (Web): “I want to meet the Receptionist.”
    • Port 22 (SSH): “I want to meet the Security Guard.”
  • Ping: Knocking on the door to see if anyone is home.
  • DNS: The Phonebook. You don’t memorize numbers; you look up “Google” and get the number.

In the old days, we used ifconfig, but now the modern standard is the ip command.

  • Check IP Address:
    • ip a (Short for ip addr): Shows all your network cards and IP addresses. Look for eth0 or ens33.
  • Check Connectivity:
    • ping google.com: Sends small packets to Google to check if the internet is working. Press Ctrl + C to stop.
  • Downloading Files:
    • wget <link>: Downloads a file directly to your terminal.
    • curl <link>: Fetches the content of a webpage (very useful for testing APIs).

Architects don’t just check connectivity; they debug Traffic Flow.

  • Ports & Services: We use ss -tulnp or netstat -tulnp.
    • -t: TCP
    • -u: UDP
    • -l: Listening ports
    • -n: Numeric (don’t resolve names)
    • -p: Show Process ID (PID) using that port.
    • Why? If your web server isn’t starting, maybe another program is already using Port 80.
  • DNS Debugging: Using nslookup or dig to see why a website name isn’t resolving to an IP.
  • Routing: ip r shows the “Route Table” the map the computer uses to decide where to send data.

Practical Labs

  1. Check IP: Run ip a. Find your IP (inet).
  2. Check Open Ports: Run ss -tulnp. See what services are running.
  3. Test Web: Run curl -I https://google.com. You should see HTTP/2 200 (Success).

Cheat Sheet

CommandUsageReal Life Logic
ip aShow IP“What is my address?”
ping hostTest Connection“Are you there?”
curl urlFetch Webpage“Read this page for me.”
wget urlDownload File“Save this file.”
ss -tulnpCheck Ports“Who is listening at the door?”
nslookupCheck DNS“What is Google’s number?”

Package Management

In Windows, you go to a website, download an .exe file, double-click it, and install. In Linux, we don’t do that. We use a Package Manager. It is like an “App Store” (Play Store or App Store) built into the terminal. You just type the name of the app, and Linux downloads and installs it automatically from a safe place called a Repository.

Different Linux families use different managers. You must know which Linux you are using.

  • Debian Family (Ubuntu, Kali, Mint):
    • Tool: apt (Advanced Package Tool).
    • Update List: sudo apt update (Refreshes the menu card).
    • Install: sudo apt install vlc.
    • Remove: sudo apt remove vlc.
  • Red Hat Family (CentOS, RHEL, Fedora, Amazon Linux):
    • Tool: yum (Yellowdog Updater) or dnf (Newer version).
    • Install: sudo yum install httpd.

Architects care about Versions and Security.

  • Dependency Management: When you install Chrome, it needs 10 other small libraries to work. The Package Manager calculates this automatically (“Dependency Resolution”).
  • Repositories:
    • Official Repos: Safe, but sometimes have older versions.
    • Third-Party Repos (PPA): Used to get the latest bleeding-edge software (e.g., latest Node.js).
  • RPM/DEB Files: Sometimes you do download a file (like .rpm or .deb). You install these manually using dpkg -i file.deb or rpm -ivh file.rpm.

Use Case

Setting up a Web Server: You need to install a web server on a fresh Ubuntu machine.

  1. Update: sudo apt update (Always do this first!).
  2. Install: sudo apt install nginx -y.
  3. Check: nginx -v (Verify installation).

Benefits

  • Security: Software from official repositories is scanned for viruses.
  • Ease: One command updates all software on your computer (apt upgrade). No need to update apps one by one.

Practical Labs

  1. Update System: sudo apt update
  2. Install a tool: sudo apt install tree
  3. Use it: Run tree. (If you don’t install it, it won’t work).
  4. Remove it: sudo apt remove tree

Cheat Sheet

ActionUbuntu (Debian)RHEL (CentOS/Amazon)
Refresh Listapt updateyum check-update
Install Appapt install nameyum install name
Remove Appapt remove nameyum remove name
Search Appapt search nameyum search name
Update Allapt upgradeyum update

Services & Systemd

When you double-click an app in Windows, it opens. When you close it, it stops. But on a server, we want software (like a Web Server or Database) to run forever in the background, even if no one is logged in. These background programs are called Services (or Daemons). Systemd is the “Manager” that controls these services. It starts them when the computer turns on and restarts them if they crash.

Think of Systemd as a Strict Office Manager.

  • The Service (e.g., Nginx): An employee.
  • Systemd: The Manager.
    • start: “Start working now.”
    • stop: “Go home.”
    • restart: “Take a break and come back fresh.”
    • enable: “You must come to work every day automatically (Run on Startup).”
    • status: “Are you working or sleeping?”

The command to control services is systemctl (System Control). Let’s say you installed a web server named nginx.

  • Check Status: sudo systemctl status nginx (Green light = Good, Red light = Error).
  • Start: sudo systemctl start nginx (Turn it on now).
  • Stop: sudo systemctl stop nginx (Turn it off now).
  • Restart: sudo systemctl restart nginx (Stop and Start again – useful after config changes).
  • Enable: sudo systemctl enable nginx (Very Important: Tells Linux to start this service automatically after a reboot).

Architects don’t just use existing services; we create Custom Services.

  • Unit Files: Every service has a config file in /etc/systemd/system/.
    • Example: If you write a Python app, you create myapp.service so systemd manages it.
  • Dependencies: You can tell systemd: “Do not start my Web App until the Database is ready” (After=mysql.service).
  • Auto-Restart: We configure Restart=always in the service file. If the app crashes at 3 AM, systemd restarts it immediately without waking you up.

Technical Challenges

  • Masked Services: Sometimes a service is “masked” (disabled permanently). You cannot start it until you unmask it.
  • Timeout Errors: If a service takes too long to start, systemd kills it. You might need to increase the TimeoutStartSec value.

Systemd for Administrators (Freedesktop.org)

Cheat Sheet

CommandActionReal Life Logic
startTurn On“Wake up.”
stopTurn Off“Go to sleep.”
restartReload“Refresh yourself.”
enableAuto-Start“Set an alarm for daily work.”
disableManual Only“Don’t come unless I call.”
statusCheck Health“Are you feeling okay?”


Boot Process & Run levels

Have you ever wondered what happens in the few seconds between pressing the Power Button and seeing the Login Screen? That is the Boot Process. The computer has to check hardware, find the hard disk, load the kernel, and start the services. If any step fails, the computer won’t start.

The Linux Boot Process has 4 Main Stages:

  1. BIOS / UEFI: The motherboard program. It checks RAM/CPU (POST) and looks for a bootable device (Hard Disk).
  2. GRUB (Grand Unified Bootloader): The blue/black screen where you choose “Ubuntu” or “Windows”. It loads the Kernel into memory.
  3. Kernel: The brain initializes hardware and mounts the Root File System (/).
  4. Systemd (Init): The first process (PID 1). It looks at the “Target” (Runlevel) and starts all necessary services (GUI, Wifi, Sound).

Architects need to know Runlevels (Targets) to fix broken servers.

  • Graphical Target (Runlevel 5): Full mode with Mouse/Desktop (Normal Laptop).
  • Multi-User Target (Runlevel 3): Text-only mode with Networking (Server Mode). Servers always run here to save RAM.
  • Emergency/Rescue Target (Runlevel 1): Safe mode. No network, no multi-user. Used to reset root passwords or fix disk errors.

Technical Challenges

  • Kernel Panic: The “Blue Screen of Death” for Linux. The Kernel crashes during boot. Usually hardware fault or corrupted updates.
  • Corrupted GRUB: Windows updates often delete the Linux GRUB, making Linux invisible. You have to reinstall GRUB using a Live USB.

Cheat Sheet

StageResponsibilityFailure Symptom
BIOSHardware CheckBlank Screen, Beep Sounds
GRUBOS Selector“No Bootable Device” or grub> prompt
KernelLoad DriversKernel Panic (Caps Lock blinking)
SystemdStart ServicesHangs at “Starting User Manager…”

Logs & Monitoring

Every time something happens on a Linux server (a user logs in, a file is downloaded, an email is sent), the system writes a note about it in a file. These notes are called Logs. Monitoring is just checking these logs and the system health (CPU, RAM) to make sure everything is running smoothly.

Linux stores almost all logs in the /var/log directory.

  • Important Log Files:
    • /var/log/syslog (Ubuntu) or /var/log/messages (CentOS): The main diary. Contains general system info.
    • /var/log/auth.log (Ubuntu) or /var/log/secure (CentOS): Security logs. Shows who logged in, failed passwords, and sudo usage.
    • /var/log/dmesg: Hardware logs (what drivers loaded during boot).
    • /var/log/nginx/access.log: Web server logs (who visited your website).
  • Tools to Read Logs:
    • tail -f /var/log/syslog: The Best Command. It shows new log lines live as they happen.
    • cat: Dumps the whole file (too big to read usually).
    • grep "error" /var/log/syslog: Searches for the word “error” inside the file.

Architects don’t read logs on the server; we send them to a Central Dashboard.

  • Centralized Logging: We use tools like ELK Stack (Elasticsearch, Logstash, Kibana) or Splunk.
    • The server sends logs to a central database.
    • We build colorful graphs to see trends (e.g., “Attack attempts from China increased by 200%”).
  • Journalctl: Modern Linux uses journalctl to query logs from Systemd services efficiently.
    • journalctl -u nginx --since "1 hour ago": “Show me Nginx logs for the last 1 hour only.”

Use Case

Investigating a Hack Attempt: You suspect someone is trying to guess your password.

  1. Check Auth Log: grep "Failed password" /var/log/auth.log
  2. Result: You see thousands of lines saying “Failed password for root from IP 192.168.x.x”.
  3. Action: You block that IP using a Firewall.
  • Debugging: Finds the root cause of crashes.
  • Audit: Proves who did what (e.g., “Rahul deleted the database at 4 PM”).

Technical Challenges

  • Disk Space: Logs grow indefinitely. If you don’t delete old ones, the disk fills up.
  • Solution: Logrotate. A built-in tool that automatically compresses old logs (e.g., syslog.1.gz) and deletes very old ones.

Ubuntu Logging Guide

Cheat Sheet

CommandUsage
tail -f fileWatch live updates.
grep “text” fileSearch inside file.
head -n 20 fileRead first 20 lines.
journalctl -xeCheck detailed system errors.
dmesgCheck hardware/kernel messages.

Performance Tuning

Sometimes your server becomes slow, just like a mobile phone running too many apps. Performance Tuning is the art of acting like a Doctor. You check the patient’s vitals (CPU, RAM, Disk) to find out which organ is failing, and then you give the right medicine (kill process, add RAM, or tune settings).

Think of Performance Tuning as Driving a Car with a Dashboard.

  • CPU: The Engine Speed (RPM). If it’s 100%, the engine is screaming.
  • RAM: The Seats. If you have 4 seats and 5 people, one person has to wait outside (Swap memory).
  • Load Average: Traffic Jam. A load of 5.0 on a 4-core CPU means traffic is moving, but 1 car is waiting.
  • Disk I/O: The Trunk speed. How fast can you load/unload luggage?

You must know the “Holy Trinity” of resources:

  1. CPU:
    • Command: top or htop.
    • Look for: %CPU. If a process is constantly >80%, it’s the culprit.
  2. Memory (RAM):
    • Command: free -m.
    • Look for: available. If it’s near 0, your server will crash soon.
  3. Disk (Storage Speed):
    • Command: iostat or iotop.
    • Sometimes CPU is free, but the server is slow because it’s waiting for the Hard Disk to write data (High “I/O Wait”).

Architects tune the Kernel Parameters using sysctl.

  • Swappiness: Linux moves unused apps from RAM to Disk (Swap) to save space.
    • Default is 60. For servers (like Databases), we lower it to 10 (vm.swappiness=10) because Disk is slow and we want to use RAM as much as possible.
  • File Descriptors: Every connection (like a website visitor) is a “file”. Default limit is 1024.
    • For high-traffic servers, we increase this to 65,000 (ulimit -n) so the server doesn’t reject visitors.
  • OOM Killer (Out of Memory): When RAM is full, the Kernel panics and shoots (kills) the biggest process to save the OS. Usually, it kills your Database. Architects tune priorities so the Kernel kills less important things first.

Use Case

The “Slow Database” Mystery: Users complain the app is slow.

  1. Check CPU: top says CPU is 5% (Idle).
  2. Check RAM: free -m says 50% free.
  3. Check Disk: iostat shows %iowait is 90%.
  4. Conclusion: The Hard Disk is too slow for the database queries.
  5. Fix: Upgrade from HDD to NVMe SSD.

Technical Challenges

  • Misleading Metrics: High “Cached” memory in free -m looks like the RAM is full, but it’s actually good. Linux uses free RAM to cache files for speed. It frees it up instantly if apps need it. Beginners panic and restart servers unnecessarily.

Linux Performance (Brendan Gregg – The Guru)


Linux Security

Linux is secure by design, but it is not “hack-proof.” When you put a server on the internet (cloud), bots will try to attack it within minutes. Linux Security is about locking the doors. You turn off things you don’t need, hide the keys, and set up a watchman (Firewall).

Think of Linux Security as Defending a Fort.

  • Firewall (UFW/Iptables): The Main Gate. It only lets people in who have an appointment (Port 80/443).
  • SSH Key: A Biometric Fingerprint Scanner. Passwords can be stolen, but your fingerprint (Private Key) cannot.
  • Root User: The King. We never let the King walk around casually. We use a General (Sudo user) to do daily tasks.
  • Fail2Ban: A Sniper. If someone knocks on the door wrongly 3 times, they get “banned” instantly.

  • SSH Hardening: This is Step 1.
    • Disable Root Login: Edit /etc/ssh/sshd_config and set PermitRootLogin no.
    • Disable Passwords: Set PasswordAuthentication no. Only allow SSH Keys.
  • Firewall:
    • UFW (Ubuntu): sudo ufw enablesudo ufw allow 22sudo ufw allow 80.
    • Firewalld (CentOS): sudo firewall-cmd --add-service=http --permanent.
  • File Permissions: ensure your keys (.pem files) are chmod 400 or 600. If they are 777, SSH will refuse to work.

Architects use Defense in Depth (Multiple layers of security).

  • SELinux (Security Enhanced Linux): This is the toughest layer. Even if a hacker becomes Root, SELinux can stop them from accessing certain files. It labels every file and process.
    • Modes: Enforcing (On), Permissive (Warnings only), Disabled.
  • Auditing: Using tools like auditd to track exactly what command a user ran.
  • Compliance: We use tools like OpenSCAP to automatically scan servers and say “This server is 90% secure according to CIS Benchmarks.”

Use Case

Stopping a Brute-Force Attack: You see thousands of login attempts in /var/log/auth.log from Russia and China.

  1. Install Fail2Ban: sudo apt install fail2ban.
  2. Configure: Tell it “If anyone fails password 3 times, block their IP for 1 hour.”
  3. Result: The attacker is blocked by the Firewall automatically.

OpenSSH Security Guide, UFW (Uncomplicated Firewall) Guide

Cheat Sheet

ToolPurposeCommand
SSHSecure Accessssh -i key.pem user@ip
UFWFirewall (Ubuntu)ufw allow 80
Fail2banBlock Hackerssystemctl start fail2ban
chmod 600Secure Keychmod 600 mykey.pem
LastWho logged in?last

Shell Scripting

Shell Script is just a text file containing a list of commands. Instead of typing mkdir foldercd foldertouch file one by one, you write them all in a file and run the file. Linux executes them one after another. It is the first step towards DevOps Automation.

Think of Shell Scripting as a Cooking Recipe.

  • You don’t tell the chef “Cut onions” then wait, then “Boil water” then wait.
  • You give him a Recipe Card (Script). He follows the steps top-to-bottom automatically without asking you anything.
  • The Shebang (#!): Every script must start with #!/bin/bash. This tells Linux “Use the Bash shell to read this recipe.”
  • Permissions: Scripts are not executable by default. You must run chmod +x script.sh.
  • Variables: Store data to reuse. NAME="Rahul". Use it as $NAME.

Example script file

#!/bin/bash
# This is a comment
NAME="DevOps Guru"
echo "Hello, $NAME!"
echo "Today is $(date)"
mkdir -p /tmp/test-folder
echo "Setup Complete."

Architects use scripting for “Glue Code”.

  • Automation: We write scripts to backup databases, clean old Docker images, or check server health.
  • Cron Jobs: We use the cron scheduler to run scripts automatically at specific times (e.g., “Run backup.sh every night at 2 AM”).
    • Command: crontab -e
    • Syntax: * * * * * /path/to/script.sh (Minute, Hour, Day, Month, Weekday).
  • Error Handling: Professional scripts use set -e. This command tells the script to Stop Immediately if any line fails, preventing a chain reaction of errors.

Bash Guide for Beginners

Crontab Guru (To test cron schedules)

Cheat Sheet

SyntaxMeaningExample
#!/bin/bashShebangAlways line 1.
VAR=valueVariableCITY="Delhi"
$VARUse Variableecho $CITY
$1, $2Arguments./script.sh arg1 arg2
if [ .. ]; thenConditionIf-Else logic.
chmod +xMake RunnableRequired before running.

Video to learn more about Linux.

Contents
Scroll to Top