DevOps

Linux Essentials for DevOps Engineers

· Pavan Y N · linux, devops, containers

Linux is the operating system underneath most DevOps work: container hosts, Kubernetes nodes, and CI runners are overwhelmingly Linux, and every Linux container shares the kernel of its host. EduGeek explains the commands, files, and habits that matter most for DevOps engineers, using current tools such as systemd, journalctl, ss, and ip instead of the older service, netstat, and ifconfig commands.

# Why Linux for DevOps?

Containers, Kubernetes nodes, CI runners, and most cloud services are Linux environments, so troubleshooting almost always ends at a shell prompt.

Key advantages:

  • →Open source and free to use
  • →A mature security model with file permissions, namespaces, control groups, and mandatory access control
  • →Powerful command-line tools that compose through pipes
  • →First-class support for automation through shell scripts, systemd, and configuration management
  • →Consistent behavior from a laptop to a production server

# Essential shell commands

## Navigation and file management

code
# List files with details, including hidden files
ls -la

# Change directory
cd /path/to/directory
cd ~    # home directory
cd -    # previous directory

# Print the working directory
pwd

# Create directories
mkdir new-folder
mkdir -p parent/child/grandchild    # create nested directories

# Remove files and directories (there is no recycle bin)
rm file.txt
rm -r directory/                    # recursive removal
rm -rf directory/                   # also ignores prompts and missing files; double-check the path

# Copy and move
cp source.txt destination.txt
cp -a source-dir/ backup-dir/       # archive mode: keeps permissions, ownership, and timestamps
mv old-name.txt new-name.txt

## File content operations

code
# View file contents
cat file.txt
less file.txt              # paginated view (press q to quit)
head -n 10 file.txt        # first 10 lines
tail -n 20 file.txt        # last 20 lines
tail -f /var/log/app.log   # follow a log file as it grows

# Search in files
grep "error" logfile.txt
grep -rn "pattern" /path/  # recursive search with line numbers
grep -i "case-insensitive" file.txt

# Text processing
sed 's/old/new/g' file.txt        # replace text and print the result
sed -i 's/old/new/g' file.txt     # edit the file in place (GNU sed)
awk '{print $1}' file.txt         # print the first whitespace-separated column
awk -F',' '{print $1, $3}' data.csv
cut -d',' -f1,3 data.csv          # extract columns 1 and 3

# Find files, then act on them
find /var/log -name "*.log" -mtime +7       # modified more than 7 days ago
find . -name "*.tmp" -delete

# File permissions

## Understanding the permission system

Every file has an owner, a group, and a set of permission bits for three classes of users: the owner, members of the file's group, and everyone else. ls -l prints them as ten characters:

code
-rwxr-xr-x
│└┬┘└┬┘└┬┘
│ │  │  └── others: r-x
│ │  └───── group:  r-x
│ └──────── owner:  rwx
└────────── type: - file, d directory, l symbolic link
BitValueOn a fileOn a directory
r4Read the contentsList the names inside
w2Modify the contentsCreate, rename, or delete entries
x1Execute as a programEnter the directory and access entries by name

The owner is the user the file belongs to, which is usually its creator but can be changed with chown.

## Managing permissions

code
# Change permissions
chmod 755 script.sh     # rwxr-xr-x
chmod u+x script.sh     # add execute for the owner
chmod go-w file.txt     # remove write for group and others

# Change ownership (usually requires root)
chown user:group file.txt
chown -R user:group directory/

# View permissions
ls -l file.txt
stat file.txt           # detailed metadata, including octal mode

## Common permission patterns

ModeSymbolicTypical use
644rw-r--r--Regular files
755rwxr-xr-xExecutables and directories
640rw-r-----Config files readable by a service group
600rw-------Private files such as SSH private keys
700rwx------Private directories and scripts

## The umask and special bits

New files start from mode 666 and new directories from 777, and the process umask turns bits off. With the common umask of 022, a new file is 644 and a new directory is 755. Run umask to see the current value.

Three special bits exist: setuid (4000) and setgid (2000) run a program, or create files, with the owner's or group's identity, and the sticky bit (1000) on a directory lets only a file's owner delete it. /tmp is mode 1777 for that reason. Avoid setuid binaries unless they are necessary.

# Process management

## Viewing processes

code
# List all processes
ps aux
ps -ef

# Top CPU consumers
ps -eo pid,ppid,%cpu,%mem,cmd --sort=-%cpu | head

# Real-time process monitor
top
htop    # enhanced version, often needs to be installed

# Find a process by name (-a prints the full command line)
pgrep -a nginx

# Process tree
pstree -p

## Managing processes

code
# Start a process in the background, list jobs, bring one to the foreground
command &
jobs
fg %1

# Keep a process running after the terminal closes (use systemd for real services)
nohup ./long-job.sh > job.log 2>&1 &

# Signal processes
kill PID           # SIGTERM (15): asks the process to shut down cleanly
kill -9 PID        # SIGKILL (9): last resort, cannot be caught or cleaned up after
pkill -f pattern   # match against the full command line; check with pgrep -af first
killall nginx      # signal every process with exactly this name

SIGKILL and SIGSTOP cannot be caught, blocked, or ignored, so a process killed with -9 gets no chance to flush buffers or release locks. Try SIGTERM first.

## System services with systemd

Most distributions use systemd to start and supervise services:

code
# Service management
systemctl status nginx
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx          # stop, then start
sudo systemctl reload nginx           # re-read configuration, if the service supports it
sudo systemctl enable --now nginx     # start on boot and start now
sudo systemctl disable --now nginx    # do not start on boot, and stop now

# Query state in scripts
systemctl is-active nginx
systemctl is-enabled nginx

# Find problems
systemctl --failed
systemctl cat nginx                   # show the unit file and its drop-ins
sudo systemctl edit nginx             # create a drop-in override
sudo systemctl daemon-reload          # re-read unit files after editing them by hand

enable alone creates the boot-time links and does not start the service, which is why --now is commonly added. reload asks the service to re-read its own configuration, which differs from daemon-reload, which makes systemd re-read unit files.

A service is defined by a unit file. This example runs the Prometheus node exporter, which the Prometheus guide covers in more detail.

code
# /etc/systemd/system/node_exporter.service
[Unit]
Description=Prometheus node exporter
Wants=network-online.target
After=network-online.target

[Service]
User=node_exporter
Group=node_exporter
ExecStart=/usr/local/bin/node_exporter
Restart=on-failure
RestartSec=5
NoNewPrivileges=true
ProtectHome=true

[Install]
WantedBy=multi-user.target
code
sudo useradd --system --no-create-home --shell /usr/sbin/nologin node_exporter
sudo systemctl daemon-reload
sudo systemctl enable --now node_exporter

## Resource limits with cgroups v2

Linux limits CPU, memory, and process counts through control groups (cgroups). Current distributions use the unified cgroup v2 hierarchy, and systemd exposes it through unit settings:

code
# Prints "cgroup2fs" when the unified cgroup v2 hierarchy is mounted
stat -fc %T /sys/fs/cgroup

# Run a command in a transient scope with limits
sudo systemd-run --scope -p MemoryMax=512M -p CPUQuota=50% ./batch-job.sh

# Make limits permanent with a drop-in: sudo systemctl edit myapp
#   [Service]
#   MemoryHigh=400M
#   MemoryMax=512M
#   CPUQuota=100%
#   TasksMax=512

MemoryHigh is a throttle point: above it, processes are slowed and memory is reclaimed aggressively, but the OOM (out-of-memory) killer does not run. MemoryMax is the hard limit, and the OOM killer runs inside the unit when usage cannot be brought under it. CPUQuota=100% equals one CPU, and larger values allow more than one. Container runtimes and Kubernetes use the same cgroup limits for --memory and CPU limits.

# Package management

FamilyToolInstall a package
Debian, Ubuntuapt, apt-getsudo apt update && sudo apt install nginx
Fedora, RHEL, Rocky, Almadnfsudo dnf install nginx
SUSEzyppersudo zypper install nginx
Alpineapksudo apk add nginx
Archpacmansudo pacman -S nginx

apt is designed for interactive use and may change behavior between versions. In scripts, the Debian documentation advises using the dedicated apt-get and apt-cache tools, which keep backward compatibility. Run apt update before installing, because it refreshes the package index.

# Mandatory access control: SELinux and AppArmor

Standard permissions can be bypassed by anything running as root or as the file's owner. Mandatory access control adds a second layer that confines each program to a policy.

  • →SELinux is the default on the Red Hat family. It runs in enforcing mode by default. getenforce shows the mode, ls -Z and ps -Z show security contexts, and denials are logged to /var/log/audit/audit.log as type=AVC records. Use setenforce 0 only to test whether SELinux is the cause of a failure, because the change does not survive a reboot. Disabling SELinux permanently is strongly discouraged by Red Hat.
  • →AppArmor is installed and loaded by default on Ubuntu. Profiles live in /etc/apparmor.d/, aa-status lists loaded profiles, and aa-complain and aa-enforce switch a profile between logging-only and blocking mode. Blocked access appears in dmesg as apparmor="DENIED".

When a service works as root in a shell but fails under systemd, check the SELinux or AppArmor logs before changing file permissions.

# Bash scripting fundamentals

## Basic script structure

code
#!/usr/bin/env bash
# The shebang selects the interpreter

# Variables (no spaces around =)
NAME="DevOps"
COUNT=10

# Output
echo "Hello, $NAME"
printf 'Count: %s\n' "$COUNT"

# Command substitution
CURRENT_DATE="$(date +%Y-%m-%d)"
FILE_COUNT="$(find . -maxdepth 1 -type f | wc -l)"

## Conditionals

code
# if statement (the [[ ]] test is a Bash feature and avoids many quoting traps)
if [[ -f "file.txt" ]]; then
    echo "File exists"
elif [[ -d "directory" ]]; then
    echo "Directory exists"
else
    echo "Neither exists"
fi

# File tests
# -f regular file exists   -d directory exists   -s file is not empty
# -r readable   -w writable   -x executable

# String comparison
if [[ "$VAR" == "value" ]]; then
    echo "Match"
fi

# Numeric comparison
NUM=15
if (( NUM > 10 )); then
    echo "Greater than 10"
fi
# Inside [ ] or [[ ]]: -eq -ne -lt -le -gt -ge

## Loops

code
# for loop
for i in {1..5}; do
    echo "Number: $i"
done

# Loop through files (nullglob makes an unmatched pattern expand to nothing)
shopt -s nullglob
for file in *.txt; do
    echo "Processing: $file"
done

# while loop
COUNT=0
while (( COUNT < 5 )); do
    echo "Count: $COUNT"
    COUNT=$((COUNT + 1))
done

# Read a file line by line
while IFS= read -r line; do
    echo "Line: $line"
done < input.txt

## Functions

code
# Define a function
backup_files() {
    local source=$1
    local dest=$2

    echo "Backing up $source to $dest"
    cp -a "$source" "$dest"
}

# Call it
backup_files "/data" "/backup"

# Functions return output through stdout, and an exit status through return
get_timestamp() {
    date +%Y%m%d_%H%M%S
}

TIMESTAMP="$(get_timestamp)"

# Log analysis and troubleshooting

## Viewing logs

Most current distributions collect logs in the systemd journal. Text files such as /var/log/syslog (Debian and Ubuntu) and /var/log/messages (Red Hat family) exist only when a syslog daemon such as rsyslog is installed. Debian 12 no longer installs rsyslog by default, so /var/log/syslog can be missing there, and journalctl is the reliable starting point.

code
# Journal logs
journalctl -u nginx                   # one unit
journalctl -u nginx -f                # follow new entries
journalctl -u nginx --since today
journalctl -p err -b                  # priority "err" and worse, current boot
journalctl --since "1 hour ago"
journalctl -k                         # kernel messages only
journalctl -xeu nginx                 # jump to the end of one unit's log, with explanatory text

# Application and web server logs
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

-e jumps to the end of the journal in the pager, and -x adds explanatory text from the message catalog where available. Neither option filters for errors, so combine them with -u or -p. Add --no-pager when piping output to other tools.

## Log analysis

code
# Count matching lines
grep -c "ERROR" app.log

# Top client IPs in an access log
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head

# Extract specific fields
grep "ERROR" app.log | awk '{print $1, $2, $5}'

# Filter by a time range (both patterns must appear in the file)
sed -n '/2026-10-15 10:00/,/2026-10-15 11:00/p' app.log

# Networking basics

code
# Interfaces, addresses, and routes
ip -br addr show
ip route

# Test connectivity
ping -c 4 example.com

# DNS lookup
dig example.com +short
getent hosts example.com        # resolves the way applications do

# Show listening sockets with the owning process (root sees all processes)
sudo ss -tulpn

# Established HTTPS connections
ss -tn state established '( dport = :443 )'

# Test whether a TCP port is reachable
nc -zv hostname 80

# Download files
wget https://example.com/file.zip
curl -fsSLO https://example.com/file.zip    # fail on HTTP errors, follow redirects, keep the remote name

ip and ss come from the iproute2 package and replace ifconfig and netstat from the older net-tools package, which minimal installations often omit. In ss, -t selects TCP, -u UDP, -l listening sockets, -p the owning process, and -n numeric ports and addresses.

# Disk and system management

code
# Disk usage
df -h                          # filesystem usage
du -sh /path                   # total size of a directory
du -h -d 1 /path               # size of each subdirectory, one level deep
lsblk                          # block devices and mount points

# Find large files without crossing into other filesystems
sudo find / -xdev -type f -size +100M

# System information
uname -a       # kernel and architecture
uptime         # uptime and load averages
free -h        # memory usage
lscpu          # CPU details
nproc          # number of CPUs available

# Practical DevOps scripts

## Deployment script

code
#!/usr/bin/env bash
set -euo pipefail

APP_NAME="myapp"
VERSION="${1:-}"

if [[ -z "$VERSION" ]]; then
    echo "Usage: $0 <version>" >&2
    exit 1
fi

echo "Deploying $APP_NAME version $VERSION"

# Pull the latest code (fail instead of creating a merge commit)
git pull --ff-only origin main

# Build the image
docker build -t "$APP_NAME:$VERSION" .

# Replace the running container (the app is briefly unavailable)
docker stop "$APP_NAME" 2>/dev/null || true
docker rm "$APP_NAME" 2>/dev/null || true

docker run -d --name "$APP_NAME" \
    -p 8080:8080 \
    "$APP_NAME:$VERSION"

echo "Deployment complete"

Stopping the old container before starting the new one causes downtime. Production deployments start the new version first and switch traffic only after a health check passes, which orchestrators such as Kubernetes do with rolling updates (see Kubernetes fundamentals). Container basics are in Docker fundamentals.

## Backup script

code
#!/usr/bin/env bash
set -euo pipefail

BACKUP_DIR="${BACKUP_DIR:-/backup}"
SOURCE_DIR="${SOURCE_DIR:-/data}"
KEEP_DAYS=7
DATE="$(date +%Y%m%d_%H%M%S)"
BACKUP_FILE="backup_${DATE}.tar.gz"

mkdir -p "$BACKUP_DIR"

# -C stores relative paths instead of absolute ones
tar -czf "$BACKUP_DIR/$BACKUP_FILE" \
    -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"

# Delete backups older than KEEP_DAYS days
find "$BACKUP_DIR" -maxdepth 1 -name 'backup_*.tar.gz' -mtime +"$KEEP_DAYS" -delete

echo "Backup created: $BACKUP_FILE"

# Best practices

  1. •Quote variables: write "$VAR" so spaces and wildcards in values do not split or expand.
  2. •Start scripts with set -euo pipefail: exit on errors, treat unset variables as errors, and fail a pipeline if any stage fails. set -e has edge cases, such as commands inside if conditions, so test failure paths.
  3. •Test commands directly: write if command; then instead of running a command and checking $? afterward.
  4. •Use absolute paths for files and tools in scripts that run from cron or systemd, where the environment is minimal.
  5. •Use trap to clean up temporary files and locks on exit.
  6. •Lint with ShellCheck before committing scripts.
  7. •Log what scripts do, and send errors to stderr with >&2.
  8. •Keep scripts in version control, and review changes like any other code. See Git version control.

# Key takeaways

  • →Use ip and ss instead of ifconfig and netstat, because the newer tools ship with iproute2 and are present on minimal installs.
  • →systemctl enable does not start a service, reload is not daemon-reload, and journalctl -u <unit> is the first place to look when a service fails.
  • →Permission bits mean different things on directories (list, modify entries, traverse) than on files, and the umask decides the defaults for new files.
  • →Try SIGTERM before SIGKILL, because a process killed with kill -9 cannot clean up after itself.
  • →cgroup v2 limits such as MemoryMax and CPUQuota can be set per service in a systemd unit or per command with systemd-run.
  • →SELinux and AppArmor can block actions that file permissions allow, so check their logs when a service fails only under systemd.
  • →Start scripts with #!/usr/bin/env bash and set -euo pipefail, quote every variable, and run ShellCheck.

# Further reading

Test yourself: Linux Essentials for DevOps assessment

All posts