Linux Hour 2: System Management and Production Readiness

On the lab VM of Lesson 1 linuxlab , turn the manually run myapp into a server that "can be handed over to colleagues on duty": Reinforced systemd Services, controllable logs, scalable LVM storage, mounts that won’t freeze startup, understandable network and DNS, hardened SSH, reliable scheduled tasks and time synchronization, and finally a production readiness review
Ubuntu Server 26.04 LTSsystemd 259Linux 7.0OpenSSH 10.2chrony 4.8Verified according to man7.org / freedesktop / Ubuntu documentation · 2026-11-17
Overall learning objectives
  • Read and write systemd units: distinguish between sort (After=/Before=) and requirements (Wants=/Requires=/BindsTo=), understand multi-user.target startup transaction, restart strategy and startup frequency limit; write and strengthen myapp.service for myapp (User=myapp, EnvironmentFile=, Restart=on-failure, ProtectSystem=strict, NoNewPrivileges=yes, etc.), use systemd-analyze security quantification.
  • Use journalctl to accurately check logs, configure journald persistence and capacity limit; understand the relationship between rsyslog and journald; write the correct logrotate rules (create vs copytruncate, postrotate).
  • Understand the layering of block devices → partitions → LVM (PV/VG/LV) → file systems (ext4/xfs), use loopback devices to "build volumes → online expansion", and know that xfs cannot be shrunk.
  • Write /etc/fstab to prevent the server from being stuck in emergency mode: UUID, nofail, x-systemd.device-timeout=, x-systemd.automount, _netdev, and swap files and swappiness.
  • Use ip, ss, resolvectl to track the whole process of connection (socket → routing table → network card) and domain name query (getaddrinfo() → NSS → systemd-resolved 127.0.0.53 → upstream DNS); understand Ubuntu's Netplan and RHEL-based NetworkManager.
  • Configure SSH keys with ~/.ssh/config, use /etc/ssh/sshd_config.d/ fragments to harden sshd, avoid the Ubuntu socket activation (ssh.socket) trap of changing ports, and don’t lock yourself out.
  • Choose between cron and systemd timer (OnCalendar=, Persistent=, RandomizedDelaySec=), and confirm chrony synchronization and NTS status.
  • Evaluate linuxlab according to the production readiness list, and use the troubleshooting tree to locate faults such as "the service cannot be started/the disk is full/the connection cannot be made/the time is wrong".

1-hour time allocation table

#TimeModuleCore contentAnimation/InteractionExperiment (linuxlab · ~/linuxlab)
0Before classConnection and warm-upStart the linuxlab of lesson 1 and confirm that it is installed myapp (/opt/myapp/app, /opt/myapp/venv, myapp.env, myapp user) and redis-server, prepare loopback disk imageEnvironment self-check listSelf-check script
100–06systemd: unit, service and dependencyUnit type and search path, drop-in, startup transaction and target, After/Wants/Requires/BindsTo, Type=, Restart= and StartLimit, sandboxCore animation: startup dependency graph + Failure and restart strategyWrite and strengthen myapp.service, systemd-analyze security scoring
206–13Log: journald, rsyslog and log rotationjournald Fields and queries, persistence and capacity, rate limits, rsyslog forwarding, logrotate rules and triggersLog flow animation (stdout → journald → rsyslog → file → logrotate)journald quota + myapp text log + logrotate walkthrough
313–21Storage: disk, partition, LVM and file systemBlock device, GPT partition, PV/VG/LV, PE, ext4 vs xfs, online expansion, snapshot, df vs duLVM layer builder (add disk → expand VG → Expand LV → Expand file system)Build vgdata and expand lvdata on the loopback device
421–28Mount, fstab and swap spacemount and systemd .mount unit, fstab Six columns, UUID, nofail, x-systemd.*, _netdev, swap file, swappinessStart the mount simulator: will it enter emergency mode when the disk is missingPersistent mounting /srv/data, 1 GiB swap file
528–35Network: ip, ss, routing and DNS resolutionInterfaces and addresses, route tables and ip route get, neighbor tables, socket status, systemd-resolved stubs, Netplan / networkd vs NetworkManagerCore Animation: A packet's journey (socket → route → Network card + DNS)Tracking myapp → redis and apt → Internet connection
635–42SSH: keys, configuration and reinforcementKey types and agent, ~/.ssh/config, known_hosts, sshd_config.d fragment and "first value takes effect", ssh.socket, sshd -TSSH connection and authentication process + configuration validity determinerEd25519 keys, hardened fragments, secure verification
742–50Scheduled tasks: cron and systemd timer, time synchronizationcrontab syntax and environment, timer unit, OnCalendar, Persistent, random delay, chrony and NTS, timedatectlMissed tasks during shutdown: cron vs Persistent timer timelinemyapp data backup timer + chrony check
850–60Production readiness review and common mistakesReadiness list (service, log, storage, network, access, time, patch), common errors, interactive troubleshooting treeReadiness scorecard + troubleshooting treeFault injection and repair
—After classCheat sheet · Comprehensive labIndependently deliver the second service myapp-worker to a production-ready stateFinal test (12 questions)Comprehensive experiment

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands/configurationExperiment
systemd Units and dependencies✓✓·✓·✓✓✓systemctl, systemd-analyze, After=/Wants=myapp.service
Service reinforcement✓····✓·✓ProtectSystem=strict, NoNewPrivileges=, systemd-analyze securityM1 scoring
Log query and retention✓✓···✓✓✓journalctl -u -p -b --since, logrotate -dM2
Disk, partition, LVM··✓✓···✓lsblk, parted, pvcreate/vgextend/lvextend -rLoopback equipment LVM
Mount and fstab, swap✓·✓✓···✓findmnt --verify, nofail, swapon/srv/data + /swapfile
Network and DNS troubleshooting···✓✓✓✓✓ip route get, ss -tlnp, resolvectl queryM5 tracking
SSH access and reinforcement·✓··✓✓·✓ssh-keygen -t ed25519, sshd -T, sshd_config.dM6 reinforcement
Scheduled tasks and time✓✓····✓✓OnCalendar=, systemctl list-timers, chronyc trackingBackup timer
Production readiness review and troubleshooting✓✓✓✓✓✓✓✓systemctl --failed, df -h, troubleshooting treeM8 fault injection

What is not covered in this lesson (and where to learn it)

TopicWhy not in this lessonWhere to learn
Shell, files and permissions, users and groups, processes and signals, apt software packages, manual running of myappLesson 1 has been taughtLesson 1
Linux on the cloud: cloud-init, metadata service, cloud disk and hosting identity, cloud logs and patchesBelongs to "Towards a cloud platform"Lesson 3 (Azure), Lesson 4 (AWS)
Firewall (nftables/ufw/firewalld) in-depth, SELinux/AppArmor, auditing, patch automationBelongs to security and automated operation and maintenanceNo. 5 Subsequent courses from the course
Performance analysis (CPU/memory/IO/network), kernel parameter tuning, in-depth troubleshootingYou need to master the system components of this course firstLesson 7 · Lesson 9 (Questions and Interviews)
Application of namespaces / cgroups in containersDocker lesson explained from the container perspectiveDocker 8 hours
Complete the configuration of this lesson in batches with AnsibleConfiguration management toolAnsible 8 hours
Indicator monitoring and alarm (node_exporter, Grafana)Monitoring systemPrometheus & Grafana 8 hours

How to use this courseware

10 paginations for each module
Principle · Diagram · Animation · Commands · Experiments · Production examples · Troubleshooting · Quizzes · Voice · Video. Let’s look at the “principle” and “animation” first, and then do the “experiment”. All experiments are accumulated on the same linuxlab, and a server that passes the review will be obtained at the end of the course.
Learning Progress
Test score ≥ 70% or click "Mark this module completed" will be counted into the progress and saved in this browser (cleared after refreshing when the browser prohibits local storage).
Chinese Voice
The "Voice" page uses the browser's built-in Web Speech API (en-US) to read the explanation script, and English terms are pronounced in en-US; when there is no Chinese voice package, the explanation script can still be read or handed over to the TTS tool.
Release NotesThis lesson uses Ubuntu Server 26.04 LTS (Resolute Raccoon, released in April 2026) as the baseline: systemd 259, Linux 7.0 Kernel, OpenSSH 10.2, chrony 4.8 (replacing systemd-timesyncd as the default time service for new installations since 25.10, using Ubuntu's NTS server by default), sudo-rs and rust-coreutils are the default implementations (since 25.10). cgroup v1 support has been removed since systemd 258; 26.04 is the last Ubuntu LTS to support the SysV service script compatibility layer (removed in upstream systemd 260).
Differences from 24.04 LTS: 24.04 uses systemd 255, OpenSSH 9.6, Linux 6.8, systemd-timesyncd (not chrony), traditional sudo and GNU coreutils; the commands in this lesson are in 24.04 They are basically the same, and the differences will be marked separately (for example, RestartSteps= requires systemd ≥ 254, both are satisfied).
RHEL system comparison: Rocky Linux / AlmaLinux 10 (host name rhellab, optional) uses NetworkManager, chronyd, firewalld, xfs by default, and the service name is sshd(Ubuntu is ssh).

Module 0 · Connection and Warm-up (Lesson 1 Experimental Machine)

Start linuxlab, confirm that the myapp installation and redis-server left in lesson 1 are still available, and prepare the "virtual disk" for the LVM experiment in this lesson
Before class ≈ 10 minutesMultipass / any Ubuntu 26.04 VMCost: 0 (all local)
Prereq (reuse linuxlab directly from end of lesson 1)
  • Local VM linuxlab: Ubuntu Server 26.04 LTS, 2 vCPU / 4 GiB / 20 GiB (created with multipass launch --name linuxlab --cpus 2 --memory 4G --disk 20G in Lesson 1); administrator labadmin (with sudo); working directory ~/linuxlab.
  • myapp (Flask + gunicorn + Redis application for Docker class) has been installed natively in Lesson 1: system user myapp (no login shell, home directory /opt/myapp), code /opt/myapp/app/ (in app.py app, requirements.txt), virtual environment /opt/myapp/venv, startup script /opt/myapp/run.sh, configuration /etc/myapp/myapp.env (root:myapp 0640: REDIS_HOST=127.0.0.1, APP_VERSION=1.0, BIND=0.0.0.0:5000, WORKERS=2, PYTHONDONTWRITEBYTECODE=1), port 5000, health check /healthz. Lesson 1 only ran it manually; Module 1 of this lesson creates myapp.service for it.
  • Redis comes from the distribution package redis-server, the service name is redis-server.service, and the listener is 127.0.0.1:6379.
Cost · Permissions · Risk · CleanupAll in native VMs, No cloud fees. Requires sudo permissions in linuxlab. This lesson will modify the sshd configuration,/etc/fstab and swap space - these three configuration errors may prevent the machine from logging in or starting, so: ① When doing SSH experimentsAlways keep a logged-in session(Multipass Users can also use multipass shell to enter at any time, without relying on the sshd configuration you changed); ② Modify fstab first findmnt --verify and mount -a, and then consider restarting; ③ Take a snapshot of the virtual machine before starting (step 1 below). For cleaning steps, see the last step of "Comprehensive Experiment".

Step 1: Start linuxlab and take a snapshot

# Execute on the host (Windows / macOS / Linux)
multipass start linuxlab
multipass list
# Multipass snapshot requires the virtual machine to be stopped
multipass stop linuxlab && multipass snapshot linuxlab --name before-part2 && multipass start linuxlab
multipass shell linuxlab          # Enter as the default user ubuntu; you can also ssh labadmin@
Name                    State             IPv4             Image
linuxlab                Running           172.25.112.34    Ubuntu 26.04 LTS
Snapshot taken: linuxlab.before-part2

Hyper-V / VirtualBox users use their respective checkpoint / snapshot functions. WSL2 needs to enable [boot] systemd=true in /etc/wsl.conf to have systemd, and the disk, mount, network and startup are all managed by Windows. The results of the LVM/fstab experiment of modules 3 and 4 will be different from the network part of module 5. It is strongly recommended to use a real virtual machine.

Step 2: Switch to labadmin and confirm the results of Lesson 1

sudo -iu labadmin                 # Multipass users first switch to the unified administrator account of the course
mkdir -p ~/linuxlab && cd ~/linuxlab
cat /etc/os-release | grep -E '^(PRETTY_NAME|VERSION_ID)='
systemctl --version | head -n 1
id myapp
sudo ls -ld /opt/myapp /opt/myapp/app /opt/myapp/app/app.py /opt/myapp/venv /opt/myapp/run.sh /etc/myapp/myapp.env
sudo grep -vE '^#|^$' /etc/myapp/myapp.env
systemctl is-active redis-server
redis-cli ping
PRETTY_NAME="Ubuntu 26.04 LTS"
VERSION_ID="26.04"
systemd 259 (259.5-1ubuntu1)
uid=998(myapp) gid=998(myapp) groups=998(myapp)
drwxr-x--- 4 root myapp 4096 Nov 17 11:18 /opt/myapp
drwxr-x--- 2 root myapp 4096 Nov 17 11:18 /opt/myapp/app
-rw-r----- 1 root myapp  612 Nov 17 11:18 /opt/myapp/app/app.py
drwxr-xr-x 5 root root  4096 Nov 17 11:19 /opt/myapp/venv
-rwxr-x--- 1 root myapp  290 Nov 17 11:19 /opt/myapp/run.sh
-rw-r----- 1 root myapp  118 Nov 17 11:19 /etc/myapp/myapp.env
REDIS_HOST=127.0.0.1
APP_VERSION=1.0
BIND=0.0.0.0:5000
WORKERS=2
PYTHONDONTWRITEBYTECODE=1
active
PONG

uid, ​​time, and systemd patch number are subject to your machine. run.sh is the manual startup wrapper script from Lesson 1, which is replaced by ExecStart in this lesson. /opt/myapp is 0750 root:myapp, labadmin requires sudo to view. The code is owned by root and myapp is read-only. This is the prerequisite for reinforcement in this lesson: the service process does not have the right to modify its own code. The unit directly uses BIND and WORKERS in the env file.

Step 3: Confirm that myapp can be run manually (and then stop)

sudo -u myapp /opt/myapp/run.sh > ~/linuxlab/myapp-manual.log 2>&1 &
sleep 2; curl -s http://127.0.0.1:5000/healthz; echo
sudo pkill -u myapp -f gunicorn   # Stop the manually run process and hand over module 1 to systemd management
{"status": "ok"}

run.sh is the startup script of the comprehensive experiment in Lesson 1 (set -a; . /etc/myapp/myapp.env after exec gunicorn --chdir /opt/myapp/app --bind "$BIND" ...). If sudo -u myapp cannot read myapp.env, execute sudo chown root:myapp /etc/myapp/myapp.env && sudo chmod 0640 /etc/myapp/myapp.env.

Step 4: Prepare "extra disk" - loopback device (used in modules 3 and 4)

LVM experiments require additional block devices. As of the date of verification, Multipass does not have a command to add a second disk to an existing instance, so this lesson uses a loop device: treating ordinary files as block devices, which is no different from real disks to LVM and file systems.

sudo apt-get update && sudo apt-get install -y lvm2 xfsprogs parted   # Usually pre-installed, whatever is missing
sudo mkdir -p /var/lib/linuxlab-disks
sudo truncate -s 2G /var/lib/linuxlab-disks/disk1.img      # Sparse files, will not fill 2 GiB immediately
sudo truncate -s 2G /var/lib/linuxlab-disks/disk2.img
ls -lsh /var/lib/linuxlab-disks/
df -h /                                                    # Confirm that the root file system has at least 5 GiB free
total 0
0 -rw-r--r-- 1 root root 2.0G Nov 17 09:20 disk1.img
0 -rw-r--r-- 1 root root 2.0G Nov 17 09:20 disk2.img
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        19G  2.9G   16G  16% /
Use real virtual disk (optional)Hyper-V: Host PowerShell New-VHD -Path C:\VMs\linuxlab-data.vhdx -SizeBytes 2GB -Dynamic; Add-VMHardDiskDrive -VMName linuxlab -Path C:\VMs\linuxlab-data.vhdx (When Multipass uses Hyper-V on Windows, the virtual machine name is linuxlab); VirtualBox: Virtual Machine Settings → Storage → Add Hard Disk. After joining, /dev/sdb will appear in linuxlab. In module 3, replace $D1 with /dev/sdb . The loopback device will not automatically reappear after restarting - this is used to demonstrate the value of nofail in Module 4.

Warm-up: answer from memory (30 seconds)

In Lesson 1, the process started by sudo -u myapp …gunicorn…, who is the parent process? What happens to the terminal after it is closed?

The parent process is your shell (via sudo); the session receives a SIGHUP when the terminal is closed, and the process usually exits. So use systemd: started and supervised by PID 1, does not rely on login sessions, and restarts according to policies after a crash.

Why is the code directory of myapp owned by root instead of the myapp user?

Minimum permissions: After the service is compromised, the attacker only gets the permissions of the myapp user; if the code directory is owned by myapp, the attacker can rewrite the code to achieve persistence. Module 1's ProtectSystem=strict goes a step further and makes almost the entire file system read-only for the service.

Environment self-check list

Module 1 · systemd: units, services and dependencies

00:00 – 06:00 · PID 1 is not "executing scripts in sequence", but counting units and dependencies as one transaction, and then executing them in parallel as much as possible; whether your service can start reliably and how to recover after failure are all written in the unit file
6 minutessystemd 259Core Animation★★★★★
Learning Objectives
  • Name common unit types (service, socket, target, timer, mount, path, slice) and the priorities of the three search locations of unit files (/etc/systemd/system > /run/systemd/system > /usr/lib/systemd/system), will use drop-in (systemctl edit) to overwrite the package's own unit.
  • Distinguish between requirement dependencies (Wants=, Requires=, Requisite=, BindsTo=, PartOf=) and ordering dependencies (After=, Before=), and explain why two services are started at the same time when only writing Requires but not After.
  • Understand the startup transaction: default.target → multi-user.target → basic.target → sysinit.target's pull relationship, and enable turns WantedBy= into a symbolic link.
  • Write out for myapp Use Sandbox hardening such as ProtectSystem=strict, NoNewPrivileges=yes, PrivateTmp=yes, etc., and verified with systemd-analyze security.
Prerequisite knowledge: Processes, signals, users and permissions in Lesson 1. Importance:★★★★★ (The logs, mounts, and scheduled tasks of the rest of the modules in this lesson are all built on the systemd unit)

What: systemd manages "units"

systemd is Linux's PID 1 (init) and service manager. The objects it manages are called units, each described by an INI-style unit file. The extension is the unit type:

TypeObject describedExample of this lesson
.serviceOne or a group of processesmyapp.service, redis-server.service, ssh.service
.targetSynchronization point/unit grouping (equivalent to the modern version of "run level")multi-user.target, network-online.target
.socketListen to the socket and start the service when the connection comes (socket activation)ssh.socket (module 6)
.mount / .automount / .swapMount point/mount on demand/swap space, usually automatically generated by /etc/fstabsrv-data.mount (module 4)
.timerActivate another unit regularlymyapp-backup.timer (Module 7)
.pathActivate unit when file/directory changes—
.slice / .scopecgroup resource group/externally created process groupsystem.slice, user-1000.slice

Search path and priority (system instance, high → low): /etc/systemd/system/ (administrator) → /run/systemd/system/ (runtime) → /usr/lib/systemd/system/ (package; on Ubuntu /lib links to /usr/lib). Files with the same name have high priority and are completely overwritten; name.d/*.conf drop-in only overwrites individual settings. Always use drop-in (systemctl edit redis-server) to change the units that come with the software package. Directly changing the files under /usr/lib will be overwritten by the upgrade.

Why: Why use systemd to host myapp instead of nohup / screen

  • Supervision: When the process exits, systemd (the parent process, receives SIGCHLD) immediately knows and restarts according to the Restart= policy; the nohup process dies and no one cares.
  • Complete life cycle: Each service has a cgroup, systemctl stop can end all child processes (including gunicorn workers).
  • Dependencies and order: Redis starts before myapp when booting; the order is reversed when shutting down, and myapp stops first.
  • Log: Standard output/error automatically enters journald, with fields such as unit name, PID, priority (module 2).
  • Security: Run as a dedicated user, overlay sandbox (read-only file system, private /tmp, prohibit privilege escalation, system call filtering), only a few lines of configuration in the unit file.

How ①: Demand dependence vs ordering dependence (the most commonly misunderstood point)

"Whether to start together" and "who comes first" in systemd are two independent dimensions. systemd.unit(5) makes it clear: requirement dependencies do not imply an order; just write Requires=b.service but not After=b.service, and both units will start simultaneously.

CommandDimensionMeaningWhen the dependent unit fails to startWhen the dependent unit is stopped later
Wants=Demand (weak)When you start me, start it by the wayI start it as usualDoesn’t affect me
Requires=Demand (strong)It must be started when I start itOnly writing After= at the same time will make my startup fail (otherwise it may have been started in parallel)When I explicitly stop/restart it, I am also stopped/restarted
Requisite=RequirementsIt must be already running, not starting itI failed immediatelySame as Requires
BindsTo=Requirements (strongest)Same as Requires, and it enters inactive in any way (including crashing itself, the device disappears) I will also stopSame as RequiresI will definitely be stopped
PartOf=One-way propagationOnly propagates stop/restart, not pulling it up—When I stop/restart it, I also stop/restart
After= / Before=SortBothare in this transaction When starting up, I start it after it is started; when shutting down, the order is reversed——

Official recommendation: In most cases, use Wants= + After=. When Redis is temporarily unavailable, myapp should start normally, report dependency exceptions in /healthz and reconnect in the code, instead of failing to start the entire service - so this lesson uses Wants=redis-server.service + After=redis-server.service.

How ②: What happens when booting

  1. Firmware → GRUB → Kernel + initramfs → Switch to the real root file system → Execute /sbin/init (i.e. systemd, PID 1).
  2. systemd runs generators (generators): For example, systemd-fstab-generator translates each line of /etc/fstab into .mount/.swap units (so daemon-reload is required after changing fstab, module 4).
  3. Load all units, starting from default.target (linked to multi-user.target on the server) along Wants=/Requires= to recursively collect the units to be started to form a transaction (transaction), check for conflicts and sorting loops.
  4. After sorting by After=/Before=, units without sorting relationships are started in parallel. Main synchronization points: local-fs.target → sysinit.target → basic.target → Normal service → multi-user.target.
  5. Ordinary services have implicit dependencies by default (DefaultDependencies=yes): Requires=sysinit.target, After=sysinit.target basic.target, Conflicts=shutdown.target, etc., myapp does not need to be declared after basic.target.

systemctl enable myapp is very simple: read [Install]'s WantedBy=multi-user.target and create a link /etc/systemd/system/multi-user.target.wants/myapp.service - equivalent to adding a link to multi-user.target Wants=myapp.service.

How ③: Type= determines the time when "startup is completed"

Type=The time when systemd considers startup to be completedApplicable
simple (with ExecStart and no Type specified (default)Immediately after fork()Foreground process; however, exec failure (wrong path, wrong permissions) will also be reported as "started" first
execAfter the binary is successfully execve()Recommended front-end service type: A path error will cause systemctl start to fail directly; myapp uses it
notify / notify-reloadThe process sends READY=1True "ready" is considered startup (requires program support)
forkingThe parent process exitsTraditional daemon process, officially discouraged
oneshotThe main process exitsOne-time tasks (backup scripts, initialization), often combined with timer

How ④: Failure, restart and startup frequency limit

  • Restart=: Default no, optional on-success, on-failure, on-abnormal, on-watchdog, on-abort, always. on-failure Restarts when exiting with non-zero exit code, exception signal, timeout, watchdog timeout, or OOM termination, and does not restart when exiting normally (0). A stop caused by systemctl stop never triggers a restart.
  • RestartSec=: Waiting time before restarting, default 100ms. Systemd ≥ 254's RestartSteps= and RestartMaxDelaySec= let the interval increase exponentially from RestartSec to the upper limit to avoid crazy restarts.
  • Start frequency limit ([Unit] section): After more than StartLimitBurst= starts within StartLimitIntervalSec=, the unit enters failed (start-limit-hit) and no longer automatically restarts (default from system.conf, usually 5 times in 10 seconds). After repairing, use systemctl reset-failed myapp to clear the count.
  • TimeoutStartSec=/TimeoutStopSec=: If it exceeds the time and is not ready/stopped, it will be judged to fail and SIGKILL.

How ⑤: Sandbox (systemd.exec(5)) - each line is a permission reduction

OptionsEffectIs myapp applicable
User=myapp / Group=myappRun as an unprivileged user✓ Required
NoNewPrivileges=yesProcesses and child processes cannot obtain new permissions through setuid and file capabilities (kernel no_new_privs flag)✓
ProtectSystem=strictThe entire file system is read-only (except /dev, /proc, /sys, there are other options); where writing is required, use ReadWritePaths= or StateDirectory= Open✓ myapp only needs to write /var/lib/myapp
ProtectHome=yes/home, /root, /run/user are not visible✓
PrivateTmp=yesIndependent /tmp and /var/tmp✓ (gunicorn's worker heartbeat file is written in the temporary directory)
PrivateDevices=yesPrivate /dev, only pseudo-devices such as null, zero, random, etc.✓
ProtectKernelTunables=/ProtectKernelModules=/ProtectKernelLogs=/ProtectControlGroups=/ProtectClock=/ProtectHostname=It is prohibited to change kernel parameters, load modules, read kernel logs, change cgroups, change clocks, and change host names✓
CapabilityBoundingSet=(empty)Clear capability set✓ Ports 5000 > 1024, CAP_NET_BIND_SERVICE not required
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIXOnly allow these socket types✓
SystemCallFilter=@system-serviceOnly allow the set of system calls required by general services✓ (the process is terminated by SIGSYS when violated)
MemoryDenyWriteExecute=yesProhibit writable and executable memory△ CPython is not required by default, but extensions with JIT will fail (Ubuntu 26.04 is enabled by default for Apache, affecting PHP JIT), this lesson does not enable it

EnvironmentFile= is read by systemd (PID 1, root) before applying the sandbox, so /etc/myapp/myapp.env can be root:myapp 0640, and the service process does not even need read permission.

When: When to write your own unit

  • Any process that requires long-term running, self-starting, and crash self-healing: write .service and put it into /etc/systemd/system/.
  • I only want to modify a few parameters of the software package service: systemctl edit service name (drop-in).
  • Temporarily test the performance of a command in the sandbox: systemd-run -p ProtectSystem=strict --pty bash (transient unit).

Comparison with similar technologies

systemd serviceSysV init scriptsupervisordContainer (Docker restart policy)
Dependencies and orderDeclarative, transactional computing, parallelScript number sequential executionpriority numbercompose depends_on
Process trackingcgroup, child process will not escapePID fileChild processContainer cgroup
SandboxDozens of options in unit filesNoneNonenamespaces + seccomp are enabled by default
StatusUbuntu/RHEL DefaultUbuntu 26.04 is the last LTS to retain a compatibility layerThird PartySee Docker course
Common misunderstandings① "Writing Requires= will wait for it to start" - waiting is only done by After= Decision. ② “After=network.target can ensure that the network is available"——network.target Only means that the network management service has been started; use it when you need a real IP/routing Wants=+After=network-online.target (not required for myapp to listen to 0.0.0.0). ③ "Restart=always Can restart indefinitely"——still subject to StartLimit constraint, the unit stops at failed. ④ "Changes to the unit file will take effect after restart" - you must first systemctl daemon-reload, otherwise systemd will still use the old definition in the memory (status will prompt changed on disk) ⑤ "ProtectSystem=full is strict enough" - full only /usr, /boot, /etc Set to read-only, /var, /opt can still be written; strict is the entire file system

Start the dependency graph: from default.target to myapp

default.target → multi-user.targetThe final target of the serverssh.socket / ssh.serviceWantedBy=multi-userredis-server.servicePackage unitmyapp.service/etc/systemd/systemchrony / cron / …Other services (parallel)Wants (enable symbolic links created)Wants= + After=basic.targetsockets / timers / paths / slices readysysinit.targetjournald, udev, tmpfiles, swaplocal-fs.target ← fstab generated .mountDefaultDependencies=yes implies:After=basic.target · Requires=sysinit.target
Figure 1-1 The solid arrow is the demand (who pulls up who); the dotted line is myapp's Wants + After for Redis; the bottom three synchronization points are represented by DefaultDependencies are implicitly ranked before ordinary services

State machine and restart strategy of a single service

inactiveactivating(start)active(running)failedexit-code / signalactivating (auto-restart)Waiting for RestartSecfailedstart-limit-hitThe process exited abnormally + Restart=on-failureRestartExceeded StartLimitBurst in the windowsystemctl stop (will not trigger restart)
Figure 1-2 Restart= determines whether to enter auto-restart after abnormal exit; stop at failed after frequency limit hit, manual operation required reset-failed

Unit file anatomy: myapp.service

[Unit]: Who am I and who am I related toDescription=Wants= / Requires= / BindsTo=After= / Before=StartLimitIntervalSec= / Burst=ConditionPathExists= …[Service]: How to runType= · ExecStart= · ExecReload=User= · WorkingDirectory= · EnvironmentFile=Restart= · RestartSec= · Timeout*Sec=Sandbox: ProtectSystem= · NoNewPrivileges= …Resources: MemoryMax= · TasksMax= · CPUQuota=Directory: StateDirectory= · LogsDirectory=[Install]: What to do when enableWantedBy=multi-user.targetRequiredBy= · Alias=enable = Create symbolic linkDo not read this section during runtime
Figure 1-3 [Unit] and [Install] are common to all unit types; the execution and sandbox options in [Service] come from systemd.exec(5), and resource control comes from systemd.resource-control(5)

Core animation: systemd startup transaction, dependency and restart strategy

Select the scenario and myapp's dependency on Redis, single-step or automatic playback. Color: gray = inactive, yellow = activating, green = active, red = failed except for scenario ④. After=redis-server.service

local-fs.targetinactivesysinit.targetinactivebasic.targetinactivenetwork.targetinactivessh.socketinactiveredis-server.serviceinactivemyapp.serviceinactivemulti-user.target(default.target)inactivemyapp restart countStartLimitBurst=5IntervalSec=600 / 5—Wants+After
Select the scene and click "Next".
Key points to observeScenario ② Play with Wants and Requires respectively: the former myapp starts as usual (only /healthz reports that Redis is unavailable), and the latter myapp fails due to dependency . In scenario ④, the two are started in parallel, and myapp may connect before Redis listens. Scenario ⑤ When using Wants, myapp is not affected, but when using Requires/BindsTo, myapp is stopped together - and itwill not automatically come back after Redis is restored.

Common commands for systemctl and systemd-analyze

CommandFunctionDescription
systemctl status myappStatus, main PID, cgroup process tree, last 10 Line logFirst debugging command
systemctl start|stop|restart|reload myappRuntime operationreload requires unit definition ExecReload=
systemctl enable --now myappAutostart and start immediately after bootingenable only creates symbolic links, --now and start
systemctl daemon-reloadReload all unit files and re-run the generatorMust be executed after modifying unit files or fstab
systemctl cat myappDisplay unit files and all drop-inLook at the source of "final effect"
systemctl show myapp -p Restart,User,NRestarts,ResultQuery the parsed attributesNRestarts = number of automatic restarts
sudo systemctl edit myappCreate/edit drop-in /etc/systemd/system/myapp.service.d/override.confAutomatically daemon-reload after saving; --full Edit the entire copy
systemctl list-dependencies myapp / --reverseDependency tree/reverse dependencyWho pulls it up, who it pulls up
systemctl --failedList failed unitsReadiness review first item
sudo systemctl reset-failed myappClear failed status and start counthit start-limit Then use
systemctl get-defaultDefault targetThe server is multi-user.target
systemd-analyze verify /etc/systemd/system/myapp.serviceStatic check unit fileSpelling errors, unknown instructions, paths do not exist
systemd-analyze security myappSandbox exposure score (0 safe – 10 unsafe)It is a heuristic score, not a vulnerability scan
systemd-analyze critical-chain myapp.serviceTime-consuming to start the critical path"@" is the start time, "+" is the time spent on this unit
systemd-analyze blame / plot > boot.svgStartup time-consuming ranking/timeline chartThe blame numbers cannot be added directly when starting in parallel
systemd-run --pty -p ProtectSystem=strict bashRun commands in transient units and apply attributesQuickly test sandbox options
systemctl list-units --type=service --state=running --no-pager | head
systemctl show redis-server -p FragmentPath,DropInPaths,After,Wants
ls -l /etc/systemd/system/multi-user.target.wants/ | head
  UNIT                      LOAD   ACTIVE SUB     DESCRIPTION
  chrony.service            loaded active running chrony, an NTP client/server
  cron.service              loaded active running Regular background program processing daemon
  redis-server.service      loaded active running Advanced key-value store
  systemd-journald.service  loaded active running Journal Service
  …
FragmentPath=/usr/lib/systemd/system/redis-server.service
DropInPaths=
After=network.target basic.target sysinit.target system.slice systemd-journald.socket
Wants=
lrwxrwxrwx 1 root root 40 … chrony.service -> /usr/lib/systemd/system/chrony.service
lrwxrwxrwx 1 root root 46 … redis-server.service -> /usr/lib/systemd/system/redis-server.service
…

How to verify:systemctl show's After= contains basic.target and sysinit.target automatically added by DefaultDependencies - that is, implicit dependencies. Common mistakes: Use "Active: active" of systemctl status to determine application health - it only indicates that the process is alive, and health depends on /healthz.

Experiment 1: Write, harden and verify systemd service for myapp (about 10 minutes)

Write the first version (unhardened) unit file, first confirm that it can run:
sudo tee /etc/systemd/system/myapp.service >/dev/null <<'EOF'
[Unit]
Description=myapp Flask API (gunicorn)
Wants=redis-server.service
After=network.target redis-server.service
StartLimitIntervalSec=60
StartLimitBurst=5

[Service]
Type=exec
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp/app
EnvironmentFile=/etc/myapp/myapp.env
# ${BIND} / ${WORKERS} from myapp.env (Lesson 1: BIND=0.0.0.0:5000, WORKERS=2)
ExecStart=/opt/myapp/venv/bin/gunicorn --chdir /opt/myapp/app --bind ${BIND} --workers ${WORKERS} --access-logfile - app:app
SyslogIdentifier=myapp
Restart=on-failure
RestartSec=2s
TimeoutStopSec=20s

[Install]
WantedBy=multi-user.target
EOF
sudo systemd-analyze verify /etc/systemd/system/myapp.service && echo verify-ok
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
systemctl status myapp --no-pager | head -n 12
curl -s http://127.0.0.1:5000/healthz; echo
verify-ok
Created symlink '/etc/systemd/system/multi-user.target.wants/myapp.service' → '/etc/systemd/system/myapp.service'.
● myapp.service - myapp Flask API (gunicorn)
     Loaded: loaded (/etc/systemd/system/myapp.service; enabled; preset: enabled)
     Active: active (running) since Tue 2026-11-17 09:40:12 UTC; 2s ago
   Main PID: 2311 (gunicorn)
      Tasks: 3 (limit: 4596)
     Memory: 61.2M (peak: 61.5M)
     CGroup: /system.slice/myapp.service
             ├─2311 /opt/myapp/venv/bin/python3 /opt/myapp/venv/bin/gunicorn --chdir /opt/myapp/app --bind 0.0.0.0:5000 …
             ├─2313 /opt/myapp/venv/bin/python3 /opt/myapp/venv/bin/gunicorn --chdir /opt/myapp/app --bind 0.0.0.0:5000 …
             └─2314 /opt/myapp/venv/bin/python3 /opt/myapp/venv/bin/gunicorn --chdir /opt/myapp/app --bind 0.0.0.0:5000 …
{"status": "ok"}

ExecStart ${BIND} and ${WORKERS} are expanded by systemd using the value of EnvironmentFile (${VAR} is expanded into a parameter; the shell's ${VAR:-default value} is not supported, and when the env file lacks these two variables, gunicorn receives empty parameters and fails to start). WorkingDirectory= and --chdir both point to /opt/myapp/app. systemctl show myapp -p ExecStart to see the command line before expansion, ps -o args -C gunicorn to see the command line after expansion.

Measure exposure before hardening:
systemd-analyze security myapp --no-pager | tail -n 3
✗ RestrictAddressFamilies=~AF_UNIX           Service may allocate local sockets              0.1
→ Overall exposure level for myapp.service: 9.2 UNSAFE 😨
Verify restart strategy: Kill the main process (simulate crash) and observe automatic restart; then use stop to prove that manual stop does not trigger restart.
sudo systemctl kill -s SIGKILL --kill-whom=main myapp
sleep 3
systemctl show myapp -p NRestarts,ActiveState,SubState
journalctl -u myapp -n 5 --no-pager -o short-iso
NRestarts=1
ActiveState=active
SubState=running
2026-11-17T09:42:01+00:00 linuxlab systemd[1]: myapp.service: Main process exited, code=killed, status=9/KILL
2026-11-17T09:42:01+00:00 linuxlab systemd[1]: myapp.service: Failed with result 'signal'.
2026-11-17T09:42:03+00:00 linuxlab systemd[1]: myapp.service: Scheduled restart job, restart counter is at 1.
2026-11-17T09:42:03+00:00 linuxlab systemd[1]: Started myapp.service - myapp Flask API (gunicorn).
Reinforcement: Use drop-in to superimpose the sandbox option (Do not modify the main file, easy for comparison and rollback):
sudo mkdir -p /etc/systemd/system/myapp.service.d
sudo tee /etc/systemd/system/myapp.service.d/10-hardening.conf >/dev/null <<'EOF'
[Service]
# Exponential backoff: 2s → … → up to 30s
RestartSteps=5
RestartMaxDelaySec=30s
# Writable directory: /var/lib/myapp (automatically created and owned by myapp)
StateDirectory=myapp
UMask=0027
# Permissions and file systems
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
# Kernel interfaces and system calls
CapabilityBoundingSet=
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@privileged
# Resource limit
MemoryMax=512M
TasksMax=64
EOF
sudo systemctl daemon-reload
sudo systemctl restart myapp
systemctl is-active myapp && curl -s http://127.0.0.1:5000/healthz; echo
systemd-analyze security myapp --no-pager | tail -n 1
active
{"status": "ok"}
→ Overall exposure level for myapp.service: 2.4 OK 🙂

If the service fails to start after hardening, check journalctl -u myapp -n 30 Depending on the reason, comment out a group of options at a time for binary search. The most common: SystemCallFilter results in status=31/SYS (Python extension uses filtered system calls); ProtectSystem=strict should be written under /opt/myapp/app (such as generating .pyc - the env file has been set PYTHONDONTWRITEBYTECODE=1 - or write log file), store writable application data in StateDirectory instead.

Verify the sandbox in practice: Run a transient shell with the same properties:
sudo systemd-run --pty --quiet -p User=myapp -p ProtectSystem=strict -p ProtectHome=yes \
  -p PrivateTmp=yes -p NoNewPrivileges=yes -p StateDirectory=myapp-test bash -c '
  touch /opt/myapp/app/x 2>&1 | head -1
  touch /var/lib/myapp-test/ok && echo "state dir writable"
  ls /home 2>&1 | head -1
  sudo -n true 2>&1 | head -1'
touch: cannot touch '/opt/myapp/app/x': Read-only file system
state dir writable
sudo: The "no new privileges" flag is set, which prevents sudo from running as root.

ls /home No output (replaced with an empty directory). Note: The sandbox is an additional line of defense for already restricted myapp users and does not replace file permissions.

Observe the difference between Wants and Requires:
sudo systemctl stop redis-server
systemctl is-active myapp            # Wants: still active
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:5000/healthz
sudo systemctl start redis-server
systemctl list-dependencies myapp --no-pager | head -n 6
active
200
myapp.service
● ├─redis-server.service
● ├─system.slice
● └─sysinit.target
●   ├─apparmor.service
…

/healthz The return code depends on whether myapp checks Redis (the Docker class version only returns ok). Replace drop-in with Requires=redis-server.service and try again, myapp will stop along with Redis - change it back to Wants after experimenting.

(Optional) Demo start-limit-hit: Temporarily point ExecStart to a command that fails immediately, observe 5 times and then enter failed and stop retrying:
sudo systemctl edit myapp --drop-in=99-broken --stdin <<'EOF'
[Service]
ExecStart=
ExecStart=/bin/false
RestartSteps=0
RestartSec=1s
EOF
sudo systemctl restart myapp; sleep 12
systemctl show myapp -p Result,NRestarts
sudo rm /etc/systemd/system/myapp.service.d/99-broken.conf
sudo systemctl daemon-reload && sudo systemctl reset-failed myapp && sudo systemctl start myapp
Result=start-limit-hit
NRestarts=4

First write empty ExecStart= in drop-in It is a fixed writing method: clear first and then assign value, otherwise it will become two ExecStarts (non-oneshot services will report an error). systemctl edit --stdin requires systemd ≥ 256 (26.04 is sufficient, 255 of 24.04 is not supported). For older versions, use sudo tee /etc/systemd/system/myapp.service.d/99-broken.conf to write and then daemon-reload.

Case 1: API occasionally gets 500 after booting, just restart the service

Problem: The unit has written Requires=postgresql.service but not After=. The application and the database are started in parallel when booting, and the database has not yet been monitored when the connection pool is initialized. Some workers Running with a bad connection. How to do it: Add After=postgresql.service, let the application retry the connection when it starts, and expose dependency status in /healthz. Restrictions:After only guarantees that the other party is "started up"; if the database is Type=simple, it may not be listening at this time - you need to use the notify type or try on the application side.

Case 2: Service "disappeared" in the early morning without anyone stopping it

Problem: Service Restart=always, NFS thrashing in the early morning made it crash every second, hit start-limit after restarting 5 times in 10 seconds, stopped at failed until morning. How to do it:Use RestartSteps=/RestartMaxDelaySec= for exponential backoff; amplify StartLimitIntervalSec=, and set StartLimitIntervalSec=0 when you really need to retry forever; use OnFailure= to trigger the alarm unit and alert systemctl --failed (see Prometheus class).

Case 3: An RCE vulnerability, but the attacker cannot exploit it

Problem: A dependency on a certain Python service has a remote code execution vulnerability. Results: The unit has ProtectSystem=strict, NoNewPrivileges=yes, PrivateTmp=yes, RestrictAddressFamilies= enabled, and the payload cannot be written to /usr/local/bin, /etc/cron.d, nor can it be passed through setuid The program has elevated privileges and can only be active in memory, and will be cleared upon restart. Limitations: The sandbox reduces the impact but does not prevent data leakage - what the service can read, the attacker can also read.

Common errors and solutions

myapp.service: Main process exited, code=exited, status=203/EXEC

Cause: ExecStart cannot be executed: wrong path, no execution permission, the first line interpreter of the script does not exist (venv is deleted or moved), noexec is mounted.

systemctl cat myapp | grep ExecStart
sudo ls -l /opt/myapp/venv/bin/gunicorn /opt/myapp/app/app.py; sudo head -1 /opt/myapp/venv/bin/gunicorn

Fix:ExecStart must be an absolute path (or in the systemd fixed search path); venv must be rebuilt after being moved (its script shebang has hard-coded absolute paths).

status=217/USER or Failed to determine user credentials: No such process

Reason:User= The specified user does not exist. Fix:id myapp Confirm; create a system user as in Lesson 1 (useradd --system --no-create-home --shell /usr/sbin/nologin myapp), or use DynamicUser=yes (services that do not require a fixed UID).

Failed to load environment files: No such file or directory / status=243/CREDENTIALS and other pre-start errors

Cause: The file pointed to by EnvironmentFile= does not exist. Fix: Check the path; optional files are written as EnvironmentFile=-/etc/myapp/myapp.env (the prefix - means it is ignored if it does not exist). EnvironmentFile is not a shell script: export and command substitution are not supported, and quotes are parsed according to systemd rules.

Warning: The unit file, source configuration file or drop-ins of myapp.service changed on disk. Run 'systemctl daemon-reload' to reload units.

Reason: The unit file has been changed without daemon-reload, but the old definition is still used. Fixed:sudo systemctl daemon-reload && sudo systemctl restart myapp. systemctl edit will automatically reload.

myapp.service: Start request repeated too quickly. / Failed with result 'start-limit-hit'.

Cause:The number of restarts in a short period of time exceeds StartLimitBurst. Repair: First look at the real error (journalctl -u myapp -b --no-pager | grep -v 'Scheduled restart'), then fix it and then systemctl reset-failed myapp to start again.

code=killed, status=31/SYS (killed on startup after hardening)

Cause:SystemCallFilter= intercepted the system call used by the program, and the kernel sent SIGSYS. Fix: Find the syscall number from journalctl -k | grep -i seccomp or dmesg; relax the filter, or temporarily set SystemCallErrorNumber=EPERM (return an error without killing the process) to locate it.

OSError: [Errno 30] Read-only file system: '/opt/myapp/app/…'

Reason: ProtectSystem=strict should be used to write the installation directory. Fix: Rewrite $STATE_DIRECTORY (StateDirectory= sets this variable to point to /var/lib/myapp); use ReadWritePaths= to open the directory accurately when necessary, and do not fall back to ProtectSystem=full.

Command line operation questions
1. Do not modify /usr/lib/systemd/system/redis-server.service, let redis-server restart 5 seconds after the crash, and view the final merged unit.
sudo systemctl edit redis-server
# Write in the editor:
# [Service]
# Restart=on-failure
# RestartSec=5s
systemctl cat redis-server
systemctl show redis-server -p Restart,RestartUSec
2. Find out the critical path that slows down the startup of myapp during this boot.
systemd-analyze critical-chain myapp.service
Scenario analysis question
A colleague wrote BindsTo=redis-server.service and Restart=always for a service that relies on Redis. The reason is that "the service should be stopped when Redis is down, and the service will automatically restart after Redis is restored." Is this reasoning correct?

First half of the sentence: The service is stopped when Redis enters inactive under BindsTo. The second half of the sentence is wrong: This is a stop job caused by dependency propagation, which does not trigger Restart=; the service will not be pulled up in reverse when Redis is restarted (unless the Redis unit writes Wants=/Upholds= pointing to it; the propagation of PartOf only takes effect when "restarting"). More secure: Wants= + After=, the application reconnects on its own, and health checks and monitoring are used to reflect dependency status.

Verified teaching video

▶
Systemd Explained: How to Manage Linux Services Easily — Learn Linux TV
English · systemctl, unit file location priority, editing service unit
▶
systemd on Linux 1: Intro and Unit Files — tutoriaLinux
English · Introduction to unit file structure (recorded earlier)
▶
systemd on Linux 3: Targets — tutoriaLinux
English · target and startup target
▶
Using systemd features to secure services - DevConf.CZ 2020 — DevConf
English · Conference Speech: Sandbox Options and systemd-analyze security (some options will be enhanced in subsequent versions)

Official Document

Video storyboard script (about 100 seconds)

This courseware cannot directly generate video/MP3. The following storyboards and explanations can be produced by video tools.

Shot 1 · 0–20s
Screen: The kernel hands over control to PID 1; default.target appears in the center and expands downward into a dependency tree.
Narration: systemd does not execute scripts by number, but starts from the default target and counts the required units as a transaction.
Shot 2 · 20–45s
Screen: Two lines are marked "Wants/Requires (who pulls whom)" and "After (who waits for whom)"; after removing After, redis and myapp light up yellow at the same time.
Narrator: Requirements and sequences are two different things. If only Requires is written without After, both services will be started at the same time.
Shot 3 · 45–75s
Screen: myapp crashes and turns red, enters auto-restart, counts 1, 2, 3, 4, 5, and becomes start-limit-hit for the sixth time.
Narration: Restart determines whether to restart, StartLimit determines the maximum number of restarts, and exponential backoff prevents crazy restarts.
Shot 4 · 75–100s
Screen: layers of transparent masks on myapp: read-only file system, private tmp, prohibition of privilege escalation, system call filtering; the score in the upper right corner dropped from 9.2 to 2.4.
Narration: Each line of sandbox configuration reduces permissions once, quantified using systemd-analyze security.
Or score ≥ 70% in the Quiz

Module 2 · Log: journald, rsyslog and log rotation

06:00 – 13:00 · A line of log starts from the stdout of myapp, passes through the structured storage of journald, and may be rsyslog Written as a text file, it is finally cut, compressed, and deleted by logrotate - each station has a capacity and retention policy to set
7 minutesjournald · rsyslog · logrotate★★★★☆
Learning goals
  • Speaks the input to journald (service stdout/stderr, syslog() socket, kernel kmsg, native API) and its additional trusted fields (_SYSTEMD_UNIT, _PID, _UID, PRIORITY, _BOOT_ID…).
  • Proficient in using journalctl filtering: -u, -p, -b, --since/--until, -g, field matching, -o json, -f.
  • Configure journald persistence (Storage=) and capacity (SystemMaxUse=, MaxRetentionSec=), and understand rate limits.
  • Understand the division of labor between rsyslog and journald, configure rsyslog text log rules as needed; write and test logrotate configuration (-d, -f).
Prerequisite knowledge:myapp.service of module 1. Importance:★★★★☆ (first-hand information on troubleshooting; the disk being filled with logs is one of the most common production accidents)

What: Three-layer logs on Linux

ComponentsWhat to doStorageUbuntu 26.04 status
systemd-journaldCollect almost all logs, plus metadata fields, indexedBinary log files: persistence in /var/log/journal//, volatile in /run/log/journal/Run by default, sysinit phase starts
rsyslogTraditional syslog Daemon process: write text files according to rules and forward to remote (TCP/RELP/TLS)/var/log/syslog, /var/log/auth.log and other text filesUse dpkg -l rsyslog Confirm whether it is pre-installed: Multiple data show that some installation methods of the new version of Ubuntu no longer include rsyslog by default. At this time, there is no /var/log/syslog
logrotateCut text logs by time/size, compress, retain N copies, execute postrotateConfiguration /etc/logrotate.conf + /etc/logrotate.d/*Triggered by logrotate.timer (systemd timer, every day)

journald input: ① Service stdout/stderr (received to journald's stream socket, so gunicorn --access-logfile - directly enter journal); ② syslog() call (/dev/log is taken over by journald); ③ kernel kmsg; ④ sd_journal_send() API; ⑤ audit subsystem. Each record comes with Trusted fields (starting with an underscore, filled in by journald according to socket credentials, and cannot be forged by applications): _PID, _UID, _COMM, _SYSTEMD_UNIT, _BOOT_ID, _HOSTNAME, etc., and PRIORITY (0 emerg... 7 debug), SYSLOG_IDENTIFIER, MESSAGE.

Why: Why care about text logs and rotation at the same time

  • journald is good at native query (by unit, by startup, by priority, by time slice), and it also has automatic rotation and automatic quota.
  • But many tools and compliance requirements are still oriented to text files or syslog protocols: log platform collectors, legacy scripts with tail -F, audit clauses that require certified logs to be forwarded to SIEMs. This is taken care of by rsyslog.
  • Some applications write their own files (Nginx's access.log, Java's log4j files) without journald, and must be managed by logrotate (or the application's own rolling), otherwise the disk will be filled up.

How ①: persistence and capacity of journald

Options (journald.conf [Journal])MeaningDefault value (upstream systemd current document)
Storage=volatile (/run only, lost after restart)/ persistent (write /var/log/journal)/ auto (the directory is persisted only if it exists)/ noneCurrent upstream document: The default journal namespace is persistent (determined at compile time, the old version was auto). Ubuntu comes pre-built with /var/log/journal, and both are persistent by default
SystemMaxUse= / SystemKeepFree=The persistent log occupies at most/at least the free space reserved10% / 15% of the file system size, with an upper limit of 4G per item
SystemMaxFileSize=Single log file size, rotate after exceeding 1/8 of SystemMaxUse
MaxRetentionSec=Delete old files by time0 (not delete by time)
RateLimitIntervalSec= / RateLimitBurst=Rate limits per service10,000 messages in 30 seconds; excess ones are discarded and "Suppressed N messages" are logged
ForwardToSyslog=Forward messages to syslog socketUpstream defaults only to wall; the distribution's rsyslog package will configure the reading method as needed (imuxsock or imuxsock or imjournal)

Don't change /etc/systemd/journald.conf directly, write drop-in /etc/systemd/journald.conf.d/*.conf and then systemctl restart systemd-journald; use systemd-analyze cat-config systemd/journald.conf See the final configuration. A single service can set LogRateLimitIntervalSec=/LogRateLimitBurst=, LogLevelMax= (discard logs below a certain level) in the unit.

How ②: Two cutting methods of logrotate

MethodProcessPremiseRisk
create (default)Rename app.log to app.log.1, create an empty app.log, and then notify the application to reopen the file (signal/reload) in postrotateThe application supports "reopening the log file"If there is no notification, the application continues to write the old inode (i.e. app.log.1), and the new file is always empty
copytruncateCopy app.log to app.log.1, and then truncate the original file to 0The application does not support reopening and is opened with O_APPENDLogs written between copying and truncation will be lost; without O_APPEND, "sparse files + file size does not decrease" will appear

Common commands: daily|weekly|monthly, size 100M/maxsize, rotate 14, compress + delaycompress (the latest one is not compressed, leaving room for the process that is still writing), missingok, notifempty, create 0640 user group, su user group (required when the directory is not owned by root), sharedscripts, dateext. logrotate is run once a day by timer, "size 100M" refers to daily check before it is exceeded - high traffic logs need to be run more frequently.

When: Which one to choose

  • Newly written service (such as myapp): the log is written to stdout and handed over to journald, no file is written, and no logrotate is required. In centralized collection, the collector reads the journal (or forwards rsyslog).
  • Must have text file (compliance, old tool): rsyslog is diverted to /var/log/myapp/myapp.log according to $programname, equipped with logrotate.
  • The application writes its own file: logrotate + the restart signal supported by the application; or use the application's own scrolling, do not use both together.

Comparison with similar technologies

journaldrsyslogCloud Logging Agent (Lesson 3/4)
FormatBinary, structured fields, indexText lines / TemplateStructured, sent to cloud
Queryjournalctl, by fieldgrep / awkKQL(Azure)/ Logs Insights(AWS)
Remote forwardingsystemd-journal-upload (less used)Mature: TCP, RELP, TLS, queueNative
ReservedBy size / Time automaticallyDepends on logrotateBy workspace/log group policy
Common misunderstandings① “rm Deleting large logs can free up space" - if the process still opens the file, the space will not be released until the process closes the file (lsof +L1 You can see the deleted file); it should be truncated (: > file) or let the process reopen. ② "journald will grow infinitely" - it has a default upper limit (10%/4G), but the upper limit is calculated based on the file system, and it may also be considerable on a small disk. ③ "journalctl --vacuum-size is the configuration" - it is just a one-time cleanup, and the long-term limit must be written into journald.conf. ④ "logrotate's size will be triggered in real time" - it is only checked when logrotate is running.

Log flow

myapp(gunicorn)stdout / stderrsshd / sudo / cronsyslog() → /dev/logKernelprintk → /dev/kmsgnginx and other self-written file applicationsDirectly write /var/log/…systemd-journaldAdditional trusted fields _SYSTEMD_UNIT…Rate limit · IndexSystemMaxUse automatically deletes the oldest files/var/log/journal/<machine-id>/journalctlQuery by fieldrsyslog (optional)imuxsock / imjournalText file/var/log/syslog · auth.loglogrotatelogrotate.timer dailyRemote syslogTCP / RELP / TLSjournald manages its own binary (no need for logrotate); text files are managed by logrotate
Figure 2-1 The stdout and syslog() of the service are imported into journald; rsyslog is an optional downstream; the application of self-written files bypasses journald and is directly managed by logrotate

logrotate's create and copytruncate

create (default)copytruncateapp.log(inode 100)app.log.1 (still inode 100)renameNew app.log (inode 200)postrotate: notification reopenedUnnotified → process continues writing inode 100 (app.log.1)app.log(inode 300)app.log.1 (copy)copytruncate → 0 bytescopy and truncate The lines written in between will be lost
Figure 2-2 The process writes the inode through the file descriptor instead of the file name: this determines the behavioral difference between the two methods

Animation: the life of a log

Select the log source and configuration, and track who receives this line of log, which fields are added, where it is written, and how it is finally deleted.

Source process—systemd-journald——/var/log/journal/…—rsyslog—Text file—logrotate—Your query—
Select the configuration and click "Next".

journalctl / journald / rsyslog / logrotate common commands

CommandFunctionDescription
journalctl -u myapp -fFollow the log of a certain unitCan write multiple -u
journalctl -u myapp -b -p warningThis startup, warning and more serious-p err..alert Specified range
journalctl -b -1 -eThe last startup log, jump to the endTroubleshoot "Why restarted"; persistence required
journalctl --list-bootsList saved startup recordsOnly 1 description is not persisted
journalctl --since "10 min ago" --until nowTime sliceYou can also write "2026-11-17 09:00"
journalctl -u myapp -g 'HTTP/1.1" 5'Filter MESSAGE by regularity-g i.e. --grep
journalctl _UID=998 _COMM=gunicornMatch by fieldMultiple values in the same field are OR, different fields are AND
journalctl -kKernel log (equivalent to dmesg)OOM killer, disk error
journalctl -u myapp -o json-pretty -n 1Show all fields-o cat Only display messages
journalctl -F _SYSTEMD_UNITList all values of a fieldWhich units have written logs
journalctl --disk-usageJournal occupation—
sudo journalctl --vacuum-size=200M / --vacuum-time=2weeksClean the archive files at one timeOnly delete archived (inactive) files
sudo journalctl --verifyCheck log file integrity—
systemd-cat -t myjob echo hiWrite command output to journalUse in script; logger -t myjob hi Use syslog interface
systemd-analyze cat-config systemd/journald.confjournald final configuration (including drop-in)—
sudo logrotate -d /etc/logrotate.d/myappDebug run (without any modification)First -d and then -f
sudo logrotate -f /etc/logrotate.d/myappForce rotation onceVerification postrotate
systemctl list-timers logrotate.timerLogrotate next run timeStatus file /var/lib/logrotate/status
rsyslogd -N1Check rsyslog configuration syntaxModify and restart rsyslog
journalctl -u myapp -n 1 -o json-pretty | grep -E '"(MESSAGE|PRIORITY|_SYSTEMD_UNIT|_PID|_UID|SYSLOG_IDENTIFIER|_TRANSPORT)"'
        "_TRANSPORT" : "stdout",
        "PRIORITY" : "6",
        "SYSLOG_IDENTIFIER" : "myapp",
        "_UID" : "998",
        "_PID" : "2313",
        "_SYSTEMD_UNIT" : "myapp.service",
        "MESSAGE" : "127.0.0.1 - - [17/Nov/2026:09:50:02 +0000] \"GET /healthz HTTP/1.1\" 200 20 \"-\" \"curl/8.x\""

How to verify: _TRANSPORT=stdout means standard output from the service; stdout default priority is 6 (info), and the error gunicorn hits stderr is also info, unless the line starts with a <3> prefix (SyslogLevelPrefix=). Common mistake: Thinking that -p err can filter out all Python exceptions - they are info level.

Experiment 2: Set an upper limit on the log and configure rotation for the text log (about 8 minutes)

Confirm that the journal has been persisted and check the usage:
ls -d /var/log/journal/*/ && journalctl --list-boots | tail -n 3
journalctl --disk-usage
/var/log/journal/3f1c0e9a2b7d4e8f9a0b1c2d3e4f5a6b/
 -1 8d2e… Mon 2026-11-16 20:02:11 UTC Mon 2026-11-16 22:40:03 UTC
  0 c71a… Tue 2026-11-17 09:15:40 UTC Tue 2026-11-17 09:51:12 UTC
Archived and active journals take 48M in the file system.
Write journald drop-in: limit 300M, maximum retention of 30 days:
sudo mkdir -p /etc/systemd/journald.conf.d
sudo tee /etc/systemd/journald.conf.d/10-linuxlab.conf >/dev/null <<'EOF'
[Journal]
Storage=persistent
SystemMaxUse=300M
SystemKeepFree=1G
MaxRetentionSec=30day
EOF
sudo systemctl restart systemd-journald
systemd-analyze cat-config systemd/journald.conf | grep -E '^(Storage|SystemMaxUse|SystemKeepFree|MaxRetentionSec)'
Storage=persistent
SystemMaxUse=300M
SystemKeepFree=1G
MaxRetentionSec=30day
To myapp Set rate limit(drop-in; log identification SyslogIdentifier=myapp has been written in the main unit, so each course can be journalctl -t myapp queried):
sudo tee /etc/systemd/system/myapp.service.d/20-logging.conf >/dev/null <<'EOF'
[Service]
# SyslogIdentifier=myapp has been set in the main unit (consistent with the unit written by cloud-init in Lessons 3 and 4)
LogRateLimitIntervalSec=30s
LogRateLimitBurst=2000
EOF
sudo systemctl daemon-reload && sudo systemctl restart myapp
for i in $(seq 1 5); do curl -s -o /dev/null http://127.0.0.1:5000/healthz; done
journalctl -t myapp -n 3 --no-pager -o short-iso
2026-11-17T09:55:03+00:00 linuxlab myapp[2402]: 127.0.0.1 - - [17/Nov/2026:09:55:03 +0000] "GET /healthz HTTP/1.1" 200 20 "-" "curl/8.x"
…
(when a text file is required) Use rsyslog to offload myapp to /var/log/myapp/myapp.log:
dpkg -l rsyslog 2>/dev/null | grep -q '^ii' || sudo apt-get install -y rsyslog
sudo install -d -o syslog -g adm -m 0750 /var/log/myapp
sudo tee /etc/rsyslog.d/30-myapp.conf >/dev/null <<'EOF'
if $programname == 'myapp' then {
    action(type="omfile" file="/var/log/myapp/myapp.log" fileOwner="syslog" fileGroup="adm" fileCreateMode="0640")
    stop
}
EOF
sudo rsyslogd -N1 && sudo systemctl restart rsyslog
curl -s -o /dev/null http://127.0.0.1:5000/healthz; sleep 1
sudo tail -n 1 /var/log/myapp/myapp.log
rsyslogd: version 8.25xx, config validation run (level 1), master config /etc/rsyslog.conf
rsyslogd: End of config validation run. Bye.
Nov 17 09:56:10 linuxlab myapp[2402]: 127.0.0.1 - - [17/Nov/2026:09:56:10 +0000] "GET /healthz HTTP/1.1" 200 …

stop Stops these lines from being written to /var/log/syslog (to avoid duplication). Ubuntu's rsyslog runs as the syslog user, so the directory belongs to syslog. $programname is taken from SYSLOG_IDENTIFIER, so the main unit sets SyslogIdentifier=myapp (otherwise the identifier is gunicorn).

Write logrotate rules for myapp.log and test:
sudo tee /etc/logrotate.d/myapp >/dev/null <<'EOF'
/var/log/myapp/*.log {
    daily
    rotate 14
    maxsize 50M
    missingok
    notifempty
    compress
    delaycompress
    create 0640 syslog adm
    su syslog adm
    sharedscripts
    postrotate
        /usr/lib/rsyslog/rsyslog-rotate
    endscript
}
EOF
sudo logrotate -d /etc/logrotate.d/myapp 2>&1 | tail -n 6
sudo logrotate -f /etc/logrotate.d/myapp
curl -s -o /dev/null http://127.0.0.1:5000/healthz; sleep 1
sudo ls -l /var/log/myapp/
rotating pattern: /var/log/myapp/*.log  forced from command line (14 rotations)
…
renaming /var/log/myapp/myapp.log to /var/log/myapp/myapp.log.1
creating new /var/log/myapp/myapp.log mode = 0640 uid = … gid = …
running postrotate script
-rw-r----- 1 syslog adm 132 Nov 17 09:58 myapp.log
-rw-r----- 1 syslog adm 911 Nov 17 09:57 myapp.log.1

/usr/lib/rsyslog/rsyslog-rotate is a script that comes with the Ubuntu/Debian rsyslog package (sends HUP to rsyslogd to make it reopen the file), /etc/logrotate.d/rsyslog also uses it; if there is no such file, use systemctl kill -s HUP rsyslog.service instead. The new myapp.log has content, indicating that rsyslog has switched to the new inode.

(Experience) Deleting a file that is still open does not free up space:
sudo bash -c 'exec 3>/var/tmp/big.log; head -c 200M /dev/zero >&3; rm /var/tmp/big.log; df -h /var/tmp | tail -1; ls -l /proc/$$/fd/3; exec 3>&-; df -h /var/tmp | tail -1'
/dev/sda1   19G  3.3G   16G  18% /
l-wx------ 1 root root 64 … /proc/4012/fd/3 -> /var/tmp/big.log (deleted)
/dev/sda1   19G  3.1G   16G  17% /

Case 1: The disk is filled with a 40 GB catalina.out

Problem:Java applications write logs to their own files and do not rotate; colleagues on duty rm files, df remains unchanged. Method:lsof +L1 Find the process holding the deleted file, truncate /proc//fd/ or restart the process; add logrotate (use copytruncate when the application cannot be reopened) and add maxsize; let the application write stdout to journald in the long term. Limitations:copytruncate has a small window for losing logs.

Case 2: "What happened before restart" cannot be found after the server restarts

Problem:journal is volatile (Storage=volatile, or auto and /var/log/journal is accidentally deleted), after restarting journalctl -b -1 reports "Specifying boot ID or boot offset has no effect, no persistent journal was found". Method: Set Storage=persistent and solidify it in image and configuration management. Limitations: The last few seconds before kernel panic may not allow disk download, requiring serial console/kdump (lessons 3 and 4).

Case 3: An error loop writes 50,000 rows per second, "crowding out" the logs of other services

Problem:journald is limited by the service rate by default (10,000 entries in 30 seconds), and is discarded if it exceeds the limit, but the service still generates a large amount of I/O, and the part within the limit is quickly exhausted SystemMaxUse, old logs are deleted in advance. How to do it: Set LogRateLimitBurst= and LogLevelMax= for the noise service; fix the error loop of the application; alert on "Suppressed... messages".

Common errors and solutions

No journal files were found. / -- No entries --

Cause: The current user does not have permission to read the system log (ordinary users can only read their own user logs), or the filtering conditions are too strict. Repair: Use sudo, or join the adm/systemd-journal group (sudo usermod -aG systemd-journal labadmin, log in again to take effect); remove the filter conditions and add them back one by one.

Specifying boot ID or boot offset has no effect, no persistent journal was found.

Reason:journal is not persisted. Fixed: Set Storage=persistent (or systemd-tmpfiles --create --prefix /var/log/journal after creating /var/log/journal) and restart journald.

systemd-journald[…]: Suppressed 12345 messages from myapp.service

Reason: Triggered rate limit. Repair: First confirm whether there is an error loop; if a large amount of logs is really needed, increase the LogRateLimitBurst= of the service, or sample/turn off access logs.

error: skipping "/var/log/myapp/myapp.log" because parent directory has insecure permissions (It's world writable or writable by group which is not "root") Set "su" directive in config file to tell logrotate which user/group should be used for rotation.

Cause: The log directory is not writable by root or group, and logrotate refuses to operate as root. Repair: Add su user group (this lesson su syslog adm) to the rule, or modify the directory permissions.

After rotation, the new app.log has always been 0 bytes, and the old app.log.1 is still growing

Cause: Postrotate in create mode does not let the process reopen the file, and the process still writes the old inode. Fixed: Postrotate sends signals supported by the application (nginx's USR1, rsyslog's HUP), or use copytruncate instead; use ls -l /proc//fd | grep log to confirm which file is opened by the process.

/var/log/syslog: No such file or directory

Reason: rsyslog is not installed - all logs are in the journal. Fixed: Use journalctl to check; when a text file is really needed, sudo apt install rsyslog.

Command line operation questions
1. View all err and higher severity kernel and service logs in the last startup, only the last 50 lines are displayed.
sudo journalctl -b -1 -p err -n 50 --no-pager
2. View all access logs of myapp containing "500" between 09:00 and 09:30 today, output in pure message format.
journalctl -u myapp --since "today 09:00" --until "today 09:30" -g ' 500 ' -o cat
Scenario analysis question
Compliance requires "authentication logs to be retained for 180 days and forwarded to SIEM in real time", and the server disk only has 20 GB. How do you design?

① Real-time and long-term retention are handed over to SIEM: rsyslog is forwarded by TCP/RELP + TLS auth,authpriv.*, and is equipped with a disk auxiliary queue to tolerate network interruptions. ② This machine only retains short-term: journald SystemMaxUse= several hundred MB, MaxRetentionSec= 14–30 days; logrotate weekly + rotate 4 + compress when writing /var/log/auth.log. ③ Monitor whether forwarding continues to be successful (queue length, SIEM last reception time). ④ Separate the log disk from the root disk (the LVM volume of module 3 is mounted to /var/log) to prevent the root file system from filling up.

Verified teaching video

▶
journalctl Basics: How to Easily Check Your Linux Logs — Learn Linux TV
English · journalctl common filtering
▶
Logrotate - Log Management on Linux Servers — Better Stack
English · logrotate configuration and common instructions

journald collaborates with rsyslog (imuxsock / imjournal): No verified video found, please refer to the illustrations of this module and official documents.

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate videos/MP3s. The following storyboards and explanations can be produced by video tools.

Shot 1 · 0–25s
Screen: The three pipelines of myapp, sshd, and kernel are imported into journald; each log is labeled with _SYSTEMD_UNIT, _PID, and PRIORITY.
Narration: Almost all logs are advanced by journald, which appends fields that cannot be forged by the application, so they can be queried by unit, startup, and level.
Shot 2 · 25–50s
Screen: journald storage tank has a red line SystemMaxUse; the oldest file is pushed out when exceeded.
Narration: journald manages its own capacity and retention, and does not require logrotate; however, the default upper limit is calculated based on the disk ratio, and must be clearly set in production.
Shot 3 · 50–90s
Screen: rsyslog writes part of the log into text; logrotate renames app.log, creates a new file, and sends HUP; compare copytruncate to copy and truncate.
Narration: Text logs are managed by logrotate. The process writes the inode instead of the file name, so the create method must notify the process to restart.
Or score ≥ 70% on the Quiz

Module 3 · Storage: Disks, Partitions, LVM and File Systems

13:00 – 21:00 · Block devices → Partitions → Physical volumes → Volume groups → Logical volumes → File system: Each layer solves a problem, and when expanding, it must be expanded layer by layer
8 minuteslvm2 · e2fsprogs · xfsprogs★★★★★
Learning objectives
  • Use lsblk, blkid, df Understand the storage layout and distinguish between block devices, partitions, device-mapper and file systems.
  • Know the difference between GPT and MBR, use parted to create partitions and set the LVM flag.
  • Explain LVM's PV / VG / LV and PE (physical extension block), and complete "Create Volume → Format → Add Disk → Expand VG → Expand LV and File System".
  • Compare ext4 and xfs (online expansion, reduction, inode, default release), know that lvextend -r expands two layers at a time.
Prerequisite knowledge:"Everything is a file" in Lesson 1 and /dev. Importance:★★★★★ ("The disk is full and needs to be expanded" is the most common work order for operation and maintenance)

What: Storage tiers

LayerWhat is itlinuxlab Examples onView commands
Block devicesDevices exposed by the kernel and read and written randomly by blocks: virtual disks, cloud disks, NVMe, loopback devices/dev/sda, /dev/loop10lsblk
Partition table/partitionCut the disk into segments. GPT (modern default, up to 128 partitions, supports > 2 TiB, two partition tables for the first and last) vs MBR (4 primary partitions, 2 TiB upper limit)/dev/sda1, /dev/loop10p1parted -l, fdisk -l
LVM physical volume PVPartition or entire disk managed by LVM, the header is written to LVM Metadata/dev/loop10p1pvs
Volume Group VGA storage pool composed of one or more PVs, split by PE (default 4 MiB)vgdatavgs
Logical volume LVAllocate several numbers from the VG A "virtual partition" composed of PEs is mapped into a block device by device-mapper/dev/vgdata/lvdata(= /dev/mapper/vgdata-lvdata)lvs
File systemOrganize files, directories, inodes, journals (journal) on block devicesext4, xfsblkid, df -hT
Mount pointsConnect the file system to the directory tree (module 4)/srv/datafindmnt

Why: Why LVM

  • Online expansion: Add disk → Add VG → Expand LV → Expand file system, no downtime or uninstallation (both ext4 and xfs can be grown online). When a partition is used directly, it cannot be expanded without continuous free space thereafter.
  • Spanning: A LV can span multiple PVs.
  • Snapshot: Copy-on-write (CoW) snapshot, suitable for freezing a consistent view before backup.
  • Migration: pvmove Move the data online to the new disk, and then remove the old disk.
  • Cost: One more layer of abstraction; if any one of the cross-disk LV disks is damaged, the entire LV data will be damaged (LVM does not provide redundancy, and redundancy relies on RAID or cloud disks).

Ubuntu Server installer creates ubuntu-vg/ubuntu-lv when installing "Full disk + LVM", and only allocates a part of the space by default to the root LV (the rest is left in VG) - a common reason for "only half of the 100G root partition", vgs can be confirmed by looking at VFree. Multipass cloud images do not use LVM. The root file system is directly in /dev/sda1 and is expanded to the entire disk when cloud-init's growpart is started for the first time.

How: A four-layer expansion action

  1. The block device becomes larger or added: The cloud disk is expanded on the portal / a new disk is attached / a loopback device is added.
  2. Partition and PV: When the PV is on the partition, first expand the partition (growpart /dev/sda 3) and then pvresize; the new disk is pvcreate + vgextend.
  3. LV: lvextend -L +10G or -l +100%FREE.
  4. File system: ext4 uses resize2fs device, xfs uses xfs_growfs mount point; or add -r (--resizefs) in step 3 to complete it together with lvextend.

ext4 vs xfs

ext4xfs
Defaults toUbuntu, DebianRHEL / Rocky / Alma
Online growth✓ (resize2fs, mountable state)✓ (xfs_growfs, must be mounted)
Reduce✓ Can only be offline (uninstall, e2fsck, resize2fs first)✗ Not supported - can only be backed up, reconstructed and restored
inodeFixed number during formatting ("space available, inode exhausted" may occur)Dynamic allocation
Good atGeneral purpose, small files, mature toolsLarge files, parallelism I/O, very large file system
Minimum sizeVery smallThe new version of xfsprogs requires about 300 MB or more
Check for repairse2fsck (needs to be uninstalled)xfs_repair (needs to be uninstalled)

The other two are worth knowing: btrfs (CoW, subvolume, snapshot, compression, openSUSE/Fedora desktop default) and ZFS (ZFS 2.4.1 available in Ubuntu 26.04). This lesson focuses on the most common server LVM + ext4/xfs.

When: When to use what

  • Separate the data disk from the system disk: data, logs, and databases each have one LV or one disk. If they are full, the root file system will not be brought down.
  • On the cloud: LVM is not required when one data disk has one file system (the cloud disk can be expanded online, just growpart + expand the file system); LVM is used when multiple disks are combined into one or snapshot/migration is required.
  • Volume where the data may need to be shrunk: select ext4, not xfs.
Common misunderstandings① "The df becomes larger after lvextend" - without adding -r , only the block device becomes larger, and the file system remains the original size. ② "xfs can be reduced like ext4" - No. ③ "If df shows full but du adds up to very little, df must be wrong" - usually a file that has been deleted but is still open (module 2), or the file is "covered" by the mount point (the directory was written before mounting). ④ "LVM spanning two disks is redundant" - on the contrary, reliability decreases. ⑤ "Just use /dev/sdb to write fstab" - the device name may change after restarting, and module 4 uses UUID.

LVM tiering and PE allocation

Block devicedisk1.img → /dev/loop10(2 GiB)disk2.img → /dev/loop11(2 GiB)PartitionGPT · /dev/loop10p1(flag: lvm)(The entire disk is used as PV, no partitioning)PVPV: metadata + 511 4 MiB PEPV: metadata + 511 PEVGvgdata: PE pool (~4 GiB)LVlvdata 2 GiB (across two PVs)lvarchive 512 MiBVFree (unallocated)File systemext4 LABEL=data → /srv/dataxfs → /srv/archive
Figure 3-1 The layout at the end of the experiment of this module: the entire disk2 is added to vgdata as the second PV, and lvdata is expanded from 1 GiB to 2 GiB and spans two PVs (PE Numbers are for illustration)

device-mapper: How LV becomes a block device

/dev/vgdata/lvdata→ /dev/dm-0 (symbolic link)Kernel device-mapper mapping table (linear)Sector 0 – 2097151 → loop10p1 offset 2048Sector 2097152 – … → loop11 offset 2048/dev/loop10p1/dev/loop11
Figure 3-2 sudo dmsetup table vgdata-lvdata You can see the real mapping table; LVM The tool just writes metadata and configures this table (numbers are illustrative)

Interaction: LVM layer builder

Click the buttons in sequence to see which layer each command changes. You can also press the wrong button on purpose (for example, expand the file system or shrink xfs without expanding LV) to see what errors are reported by the real system.

PV/dev/loop10p1 (not initialized)/dev/loop11 (not initialized)VG(no volume group)LV(no logical volume)File System(Unformatted)df -h /srv/data: —
Click starting from ①.

Storage and LVM commands

CommandFunctionDescription
lsblk -f / lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTSBlock device tree + file systemThe most commonly used "panorama"
sudo blkidUUID, LABEL, TYPEWrite fstab using
df -hT / df -iFile system space / inode usage"No space left" may also be inode full
sudo du -xhd1 /var | sort -hFind large directories (not across file systems)-x is very important
sudo losetup -fP --show files / losetup -a / losetup -dCreate/list/delete loopback devices-P Scan partitions
sudo parted -s DEV mklabel gpt mkpart data 1MiB 100% set 1 lvm onGPT + one LVM partition1MiB starting guaranteed alignment
sudo growpart /dev/sda 1Expand the partition to the end of the diskcloud-guest-utils package; use after cloud disk expansion
pvcreate / pvs / pvdisplay / pvresize / pvmovePhysical volume—
vgcreate / vgextend / vgreduce / vgsVolume groupVFree List to see remaining
lvcreate -n NAME -L 1G VG / -l 100%FREECreate logical volume-L absolute size, -l by PE or percentage
lvextend -r -L +1G VG/LVExpand LV and expand file system at the same time-r = --resizefs
lvcreate -s -n snap -L 200M VG/LVCoW snapshotInvalid when the snapshot space is full
mkfs.ext4 -L LABEL DEV / mkfs.xfs -L LABEL DEVCreate a file systemThe xfs label can be up to 12 characters
resize2fs DEV / xfs_growfs MOUNTPOINTExpand the file systemNote that one parameter is the device and the other is the mount point
sudo dmsetup ls / dmsetup tabledevice-mapper mappingLV's bottom layer
wipefs -a DEVClear signature⚠ Destructive, confirm device name
lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTS
sudo vgs 2>/dev/null || echo "(This machine has no LVM volume group)"
NAME    SIZE TYPE FSTYPE MOUNTPOINTS
loop0  50.9M loop squashfs /snap/snapd/…
sda      20G disk
├─sda1   19G part ext4   /
├─sda14   4M part
├─sda15 106M part vfat   /boot/efi
└─sda16 913M part ext4   /boot
sr0     4M  rom  iso9660
(This machine has no LVM volume group)

Partition number and size vary from image to image; when installing ISO and selecting LVM's Ubuntu Server, you will see ubuntu--vg-ubuntu--lv. Common mistakes: Before executing the mkfs/wipefs - destructive command on /dev/sda instead of /dev/sdb, lsblk confirm that the target has no mount points and is of the correct size.

Experiment 3: Build LVM on the loopback device and expand online (about 10 minutes)

Convert the image file into a block device and build a GPT partition on disk1:
cd ~/linuxlab
D1=$(sudo losetup -fP --show /var/lib/linuxlab-disks/disk1.img)
sudo parted -s "$D1" mklabel gpt mkpart data 1MiB 100% set 1 lvm on
sudo partprobe "$D1"
echo "D1=$D1" | tee disks.env
lsblk "$D1"
D1=/dev/loop10
NAME       MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS
loop10       7:10   0   2G  0 loop
└─loop10p1 259:0    0   2G  0 part
Create PV, VG and two LVs:
sudo pvcreate "${D1}p1"
sudo vgcreate vgdata "${D1}p1"
sudo lvcreate -n lvdata -L 1G vgdata
sudo lvcreate -n lvarchive -L 512M vgdata
sudo pvs; sudo vgs; sudo lvs
  Physical volume "/dev/loop10p1" successfully created.
  Volume group "vgdata" successfully created
  Logical volume "lvdata" created.
  Logical volume "lvarchive" created.
  PV            VG     Fmt  Attr PSize  PFree
  /dev/loop10p1 vgdata lvm2 a--  <2.00g <508.00m
  VG     #PV #LV #SN Attr   VSize  VFree
  vgdata   1   2   0 wz--n- <2.00g <508.00m
  LV        VG     Attr       LSize   Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  lvarchive vgdata -wi-a----- 512.00m
  lvdata    vgdata -wi-a----- 1.00g
Format (one each for ext4 and xfs) and temporarily mount:
sudo mkfs.ext4 -q -L data /dev/vgdata/lvdata
sudo mkfs.xfs -q -L archive /dev/vgdata/lvarchive
sudo mkdir -p /srv/data /srv/archive
sudo mount /dev/vgdata/lvdata /srv/data
sudo mount /dev/vgdata/lvarchive /srv/archive
df -hT /srv/data /srv/archive
Filesystem                   Type  Size  Used Avail Use% Mounted on
/dev/mapper/vgdata-lvdata    ext4  974M   24K  907M   1% /srv/data
/dev/mapper/vgdata-lvarchive xfs   448M   35M  414M   8% /srv/archive

The size of ext4 is less than 1G: reserved blocks (default 5% for root) and metadata occupation. tune2fs -m 1 can reduce the data disk retention ratio to 1%.

Write data to nearly full:
sudo fallocate -l 800M /srv/data/blob.bin
df -h /srv/data | tail -1
/dev/mapper/vgdata-lvdata  974M  801M  107M  89% /srv/data
"Add a disk": The entire disk2 is added to VG as a PV:
D2=$(sudo losetup -f --show /var/lib/linuxlab-disks/disk2.img)
echo "D2=$D2" | tee -a disks.env
sudo pvcreate "$D2"
sudo vgextend vgdata "$D2"
sudo vgs vgdata
D2=/dev/loop11
  Physical volume "/dev/loop11" successfully created.
  Volume group "vgdata" successfully extended
  VG     #PV #LV #SN Attr   VSize VFree
  vgdata   2   2   0 wz--n- 3.99g <2.49g
Online expansion: LV and file system are completed in one step(The data disk remains mounted and the application does not need to be stopped):
sudo lvextend -r -L +1G vgdata/lvdata
df -h /srv/data | tail -1
sudo lvs -o lv_name,lv_size,devices vgdata
  Size of logical volume vgdata/lvdata changed from 1.00 GiB (256 extents) to 2.00 GiB (512 extents).
  File system ext4 found on vgdata/lvdata mounted at /srv/data.
  Extending file system ext4 to 2.00 GiB (2147483648 bytes) on vgdata/lvdata...
  …
  Logical volume vgdata/lvdata successfully resized.
/dev/mapper/vgdata-lvdata  2.0G  801M  1.1G  43% /srv/data
  LV        LSize   Devices
  lvarchive 512.00m /dev/loop10p1(256)
  lvdata      2.00g /dev/loop10p1(0)
  lvdata      2.00g /dev/loop11(0)

lvdata is now composed of two segments, divided into two PVs. New versions of lvm2's -r are called directly by lvextend to resize2fs/xfs_growfs (older versions via fsadm), the output wording varies by version.

Expand xfs and experience "cannot shrink":
sudo lvextend -L +256M vgdata/lvarchive
sudo xfs_growfs /srv/archive | tail -1
sudo lvreduce -r -L 512M vgdata/lvarchive || echo "↑ xfs does not support shrinking"
data blocks changed from 131072 to 196608
  File system xfs found on vgdata/lvarchive mounted at /srv/archive.
  File system size (768.00 MiB) is larger than the requested size (512.00 MiB).
  File system reduce is required and not supported (xfs).
↑ xfs does not support shrinking

lvreduce without -r will only shrink the block device, regardless of the file system - directly damaging the data. Always use -r in production, and back up before shrinking.

Clean test files, keep volume for module 4 use:
sudo rm /srv/data/blob.bin
sudo umount /srv/data /srv/archive     # Module 4 is permanently mounted using fstab
cat ~/linuxlab/disks.env

Case 1: Newly installed Ubuntu server with half root partition

Problem: 200 GB disk, df -h / only 100 GB, database full. Method:sudo vgs shows that ubuntu-vg has about 100 GB VFree, sudo lvextend -r -l +100%FREE ubuntu-vg/ubuntu-lv is completed online. Limitations: When VFree is 0, expand the underlying disk, growpart, pvresize first.

Case 2: No new space is visible in the system after cloud disk expansion

Problem: The cloud portal expanded the data disk from 100 GB to 200 GB, and df remained unchanged. Method: Confirm layer by layer: lsblk (Has the block device become larger? Some environments require echo 1 > /sys/class/block/sdc/device/rescan) → growpart (partition) → pvresize (PV) → lvextend -r (LV + file system). Lessons 3 and 4 are hands-on on Azure/AWS.

Case 3: "No space left on device", but df shows 40% idle

Problem: The mail queue/cache directory generates millions of small files, and the ext4 inode is used up. Method:df -i Confirm IUse% 100% and clean up small files; long-term: cleanup strategy + use mkfs.ext4 -i during reconstruction to lower the number of bytes per inode, or use xfs that dynamically allocates inodes.

Common errors and solutions

Can't open /dev/loop10p1 exclusively. Mounted filesystem? / Device /dev/sdb excluded by a filter.

Cause: The device is mounted, occupied by other programs, or old partition table/file system signatures remain (rejected by LVM by default). Fixed:lsblk -f and findmnt confirm that it is not in use; after confirming that it is an empty disk, sudo wipefs -a device clears the signature (⚠ irreversible).

Insufficient free space: 256 extents needed, but only 127 available

Cause:VG has insufficient free PEs. Fixed:sudo vgs to see VFree; add vgextend, or -l +100%FREE to use up the rest.

lvextend is successful but df remains unchanged

Reason: No -r is added, only the block device is expanded. Fixed: ext4: sudo resize2fs /dev/vgdata/lvdata; xfs: sudo xfs_growfs /srv/archive.

xfs_growfs: /dev/mapper/vgdata-lvarchive is not a mounted XFS filesystem

Reason:xfs_growfs requires a mount point and must be mounted. Fix: Execute sudo xfs_growfs /srv/archive after mounting.

WARNING: Device for PV xxxx not found or rejected by a filter. / VG vgdata is missing PV

Reason: One of the PVs that make up the VG is no longer there - in this experiment, the loopback device was not rebuilt after restarting; in production, the disk failed or was not mounted. Fixed: During the experiment, losetup was re-created after two images sudo vgchange -ay vgdata; in production, restore the disk first, and do not write to VG when the disk is missing.

mount: /srv/data: wrong fs type, bad option, bad superblock on /dev/mapper/…

Cause: There is no file system on the device, the type is wrong, or the file system is damaged. Fixed:sudo blkid device to see the type; after uninstalling e2fsck -f / xfs_repair -n (check only); journalctl -k to see the kernel error.

Command line operation questions
1. Allocate all remaining space in the volume group vgdata to lvdata, and expand its ext4 file system at the same time.
sudo lvextend -r -l +100%FREE vgdata/lvdata
2. Find the five largest first-level subdirectories under /var and do not span to other file systems.
sudo du -xh --max-depth=1 /var 2>/dev/null | sort -h | tail -n 6
Scenario analysis question
The team wants to place the PostgreSQL data directory on an LVM linear volume spanning three cloud disks to obtain "a 3 TB large disk". Please evaluate.

Linear LV spans three disks: if any one disk fails, the entire file system will be damaged, and the failure probability is about three times that of a single disk; the performance is not superimposed (linear mapping uses PE in sequence). Recommendations: ① Prioritize using a large enough cloud disk (with built-in redundancy and online expansion); ② Use LVM striping (lvcreate -i 3) to superimpose IOPS and accept the reliability cost, or use a high-performance cloud disk; ③ Both have backup and recovery drills; ④ Database volumes can be xfs or ext4, and avoid xfs if they may be reduced in the future.

Verified teaching video

▶
Linux Logical Volume Manager (LVM) Deep Dive Tutorial — Learn Linux TV
English · PV/VG/LV, expansion, snapshot complete demonstration
▶
Linux Crash Course - Everything You Need to Know for Formatting and Mounting Disks — Learn Linux TV
English · Partitioning, formatting and mounting

Official document

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video/MP3. The following storyboards and explanations can be produced by video tools.

Shot 1 · 0–25s
Screen: The file disk1.img is losetup into /dev/loop10, and then the partition is cut out and PV label is attached.
Narration: To LVM, there is no difference between a loopback device and a real disk. A physical volume is the smallest unit managed by LVM.
Shot 2 · 25–55s
Screen: PV is cut into one grid. 4 MiB PE is poured into the vgdata pool; lvdata takes away 256 grids.
Narration: The volume group is a storage pool. Logical volumes are allocated from the pool according to PE, and then mapped into block devices by device-mapper.
Shot 3 · 55–90s
Screen: The file system bar is red to 90%; disk2 is put into the pool; lvextend -r makes the LV bar and the file system bar become longer at the same time, and the red ratio decreases. A red cross appears when the xfs bar tries to shrink.
Narration: To expand the capacity, you need to expand it layer by layer. Add -r to complete it in one step. Both ext4 and xfs can grow online, but xfs cannot shrink.
Or score ≥ 70% on the Quiz

Module 4 · Mounts, fstab and swap space

21:00 – 28:00 · Each line of /etc/fstab will become a systemd .mount unit at boot; if one line is written incorrectly, the server may stop in emergency mode, and you can only access it through SSH
7 minutesutil-linux · systemd-fstab-generator★★★★★
Learning objectives
  • Explain the essence of mounting (connecting the file system to the directory tree) and the relationship between mount, findmnt, and /proc/self/mountinfo.
  • Read and write fstab six columns; use UUID or LABEL instead of /dev/sdX; understand nofail, noauto, x-systemd.device-timeout=, x-systemd.automount, x-systemd.requires=, _netdev.
  • Know how systemd-fstab-generator translates fstab to srv-data.mount and mounts it to local-fs.target, and why it enters emergency mode when a disk is missing.
  • Create and persist swap files, understand vm.swappiness and "swap space is not a substitute for memory".
Prerequisite knowledge:The units and dependencies of module 1, and the LV of module 3. Importance:★★★★★ (fstab error is the number one reason why cloud hosts "cannot start and cannot log in")

What: Mounting and fstab

Linux There is only one directory tree. Mounting connects the file system on the device to a directory (mount point) in the tree, and then accessing the directory is accessing that file system; the files in the original directory are "covered" rather than deleted. The kernel mount table is in /proc/self/mountinfo and findmnt is displayed in a tree format.

/etc/fstab Six columns per row:

ColumnsMeaningExampleKey points
1 deviceFile system to be mountedUUID=7c1e…, LABEL=data, /dev/vgdata/lvdata/dev/sdb and other kernel names are assigned in the order of detection, and may change after adding disks/changing controllers; use UUID (unique at the file system level) or LVM path (by name, stable)
2 Mount pointDirectory/srv/data; replace with noneDirectory must exist
3 TypeFile system typeext4, xfs, swap, nfs—
4 optionsMount options, comma separateddefaults,nofail,noatimeSee table below
5 dumpWhether to be dumped backup0almost always 0
6 passboot fsck orderroot is 1, other ext4 is 2, xfs/network/swap is 0xfs does not fsck at boot

Key options

OptionEffect
defaultsrw, suid, dev, exec, auto, nouser, async
nofailThis mount is not a hard requirement of local-fs.target (becomes Wants). The device does not exist or the mount fails. It does not prevent booting
noautoIt does not mount when booting. Manually when needed mount
x-systemd.device-timeout=10sTime to wait for device to appear (default 90 seconds, from DefaultDeviceTimeoutSec)
x-systemd.mount-timeout=Timeout for the mount command itself
x-systemd.automountGenerate .automount Unit: only establishes an automatic mount point when booting, and only mounts (network storage, disks that may not be present) when accessed for the first time
x-systemd.idle-timeout=Works with automount, and automatically unmounts after idle
x-systemd.requires= / x-systemd.after=Add dependencies to the generated .mount unit
_netdevDeclare the need for network: Subordinate remote-fs.target, mount after the network is ready (nfs/cifs automatically recognized, local file systems on block devices such as iSCSI need to be added manually)
noatime / nodev,nosuid,noexecDoes not update access time (reduces writing)/security hardening (such as /tmp, data disk)

How: How to deal with systemd fstab

  1. When booting and every time systemctl daemon-reload, systemd-fstab-generator reads fstab and generates units for each line to /run/systemd/generator/: /srv/data → srv-data.mount (in the path / becomes -); swap → swapfile.swap.
  2. Each .mount unit depends on the corresponding device unit (such as dev-disk-by\x2duuid-7c1e….device), wait until udev reports that the device appears, and fail if it times out.
  3. Local mounts without nofail are local-fs.target Requires; either fails → local-fs.target fails → its OnFailure=emergency.target takes effect → enters emergency mode (console only, SSH not yet started).
  4. When there is nofail, it is just a Wants relationship: if the mount fails, only the .mount failed, and the boot continues; the services that rely on it are available RequiresMountsFor=/srv/data to decide whether to start.

So after changing fstab, before restarting execute sudo findmnt --verify (check the syntax, whether the device exists, and whether the type matches), sudo systemctl daemon-reload (regenerate the unit), sudo mount -a (actually mount it once).

Swap space (swap)

  • Function: Swap out inactive anonymous pages to disk to free up memory for page cache and active processes; provide buffering during memory peaks to avoid triggering the OOM killer immediately.
  • Cost: The swapped-out page has to wait for disk I/O before accessing it again; the system is extremely slow when swapping is severe (a large amount of si/so) - "Swap space cannot replace memory."
  • vm.swappiness (0–200, default 60): The higher the value, the more likely it is to swap out anonymous pages, the lower the value, the more likely it is to reclaim the file page cache. Database server standing 1–10.
  • Forms: swap partition, swap file (most flexible), zram (in-memory compressed swap). Ubuntu ISO installation usually creates /swap.img; cloud images (including Multipass instances) have no swap space by default.
  • The swap file must be chmod 600 (otherwise swapon will warn "insecure permissions"), and can be created with fallocate on ext4/xfs; btrfs requires special processing (btrfs filesystem mkswapfile).

When: Which writing method to choose

ScenarioRecommended writing method
Root, /boot and other necessary volumes for the systemUUID, not added nofail
Data disk (the service cannot run without it)UUID + nofail,x-systemd.device-timeout=10s; service unit added RequiresMountsFor=
Possible disk, USB, experimental loopback devicenofail or noauto,x-systemd.automount
NFS / SMB_netdev,nofail,x-systemd.automount (Mounted only when accessed, network jitter does not affect startup)
Temporary disk on the cloud (Azure resource disk/AWS instance storage)Managed by cloud-init, see 3 and 4 class; don’t just write it into fstab
Common misunderstandings① "If you change the fstab execution mount -a If it succeeds, everything will be fine" - mount -a will not help you find the problem of "this disk will not be there after restarting". The behavior at boot is determined by systemd Unit dependency determines, nofail is the insurance. ② "nofail makes booting faster" - when the device does not exist, it will still wait for device-timeout (default 90 seconds), so it needs to cooperate x-systemd.device-timeout=. ③ "The original file in the mount point directory was deleted" - it was just covered and reappeared after uninstalling. This is also one of the reasons why "df and du do not match". ④ "The bigger the swap, the better" - an excessively large swap will allow out-of-control processes to slow down the system for a long time instead of being terminated by OOM in time; set and monitor according to the workload.

From fstab to local-fs.target

/etc/fstabUUID=… / ext4 defaults 0 1UUID=… /srv/data ext4 nofail,… 0 2/swapfile none swap sw 0 0systemd-fstab-generatorRun on boot/daemon-reload-.mount (root, Requires)srv-data.mount(nofail → Wants)swapfile.swap → swap.targetdev-disk-by\x2duuid-….deviceudev reports device present; timeout device-timeoutBindsTo + Afterlocal-fs.targetOnFailure=emergency.targetemergency.targetConsole only; SSH not startedWhen hard requirements fail
Figure 4-1 Solid line = Requires (failure will drag down local-fs.target), dotted line = Wants generated by nofail (failure only affects itself)

Relationship between memory and exchange

Active anonymous pages (process heap, stack)Page cache (file data, can be discarded directly)Inactive anonymous pagesswapKernel recycling when memory is tight: discard the page cache (first when swappiness is low) or write inactive anonymous pages to swap (swappiness) More active when high)When there is no swap, the anonymous page has nowhere to go and can only recycle the page cache. If it is not enough, the OOM killer will be triggered
Figure 4-2 swappiness adjusts the preference between two types of recyclable memory

Interaction: Start up and mount the simulator - will this machine be stuck in emergency mode?

Select the writing method and actual boot situation for the /srv/data line, and then play the boot process.

fstab-generator—Device unit (udev)Waitingsrv-data.mountinactivelocal-fs.targetinactivemulti-user.targetinactiveSSH login available? —emergency.target—Time to boot0 sData integrity: —
Click "Next" after selection.

Mount and swap command

CommandFunctionDescription
findmnt / findmnt /srv/data / findmnt -t ext4,xfsMount tree/certain mount point/by typeClearer than mount | grep
sudo findmnt --verify --verboseStatic check fstabThe first step after changing fstab
sudo mount -aMount all unmounted, non-noauto entries in fstabSecond step (daemon-reload first)
sudo mount -o remount,ro /srv/dataRemount as read-onlyUse during maintenance
sudo umount /srv/data / umount -lUninstall/delay uninstallCheck who is using it first
sudo fuser -vm /srv/data / sudo lsof +f -- /srv/dataWho is using this mount pointWhen target is busy
systemd-escape -p --suffix=mount /srv/dataGet unit name from pathOutput srv-data.mount
systemctl status srv-data.mountMount unit statusFailure reason
systemctl list-units --type=mount,automount,swapAll mount related units—
swapon --show / free -hSwap space/memory overview—
sudo mkswap /swapfile / swapon / swapoffCreate/enable/close swap—
sysctl vm.swappiness / /etc/sysctl.d/*.confView/persistent settingssudo sysctl --system Reload
vmstat 1 5Look at si/so (swapping in and out every second)Continuous non-zero indicates insufficient memory
findmnt -o TARGET,SOURCE,FSTYPE,OPTIONS / /boot
systemd-escape -p --suffix=mount /srv/data
TARGET SOURCE    FSTYPE OPTIONS
/      /dev/sda1 ext4   rw,relatime,discard,errors=remount-ro,commit=30
/boot  /dev/sda16 ext4  rw,relatime
srv-data.mount

Experiment 4: Mount the data volume persistently, create a swap file, and verify boot safety (about 8 minutes)

Get the UUID and write it fstab(backup first):
sudo cp -a /etc/fstab /etc/fstab.bak.$(date +%F)
DATA_UUID=$(sudo blkid -s UUID -o value /dev/vgdata/lvdata)
ARCH_UUID=$(sudo blkid -s UUID -o value /dev/vgdata/lvarchive)
echo "$DATA_UUID $ARCH_UUID"
sudo tee -a /etc/fstab >/dev/null <<EOF
# linuxlab part2 · Data volume (LVM on loopback device, may not be present at boot → nofail + short timeout)
UUID=$DATA_UUID  /srv/data     ext4  defaults,nofail,noatime,x-systemd.device-timeout=10s  0  2
UUID=$ARCH_UUID  /srv/archive  xfs   defaults,nofail,noatime,x-systemd.device-timeout=10s  0  0
EOF
tail -n 3 /etc/fstab
7c1e5b0a-3f7d-4b8e-9c2a-1d2e3f4a5b6c 0b9f6a12-…
# linuxlab part2 · Data volume (LVM on loopback device, may not be present at boot → nofail + short timeout)
UUID=7c1e5b0a-3f7d-4b8e-9c2a-1d2e3f4a5b6c  /srv/data     ext4  defaults,nofail,noatime,x-systemd.device-timeout=10s  0  2
UUID=0b9f6a12-…  /srv/archive  xfs   defaults,nofail,noatime,x-systemd.device-timeout=10s  0  0
Three-step verification: verify → daemon-reload → mount -a:
sudo findmnt --verify
sudo systemctl daemon-reload
sudo mount -a
findmnt /srv/data; findmnt /srv/archive
systemctl status srv-data.mount --no-pager | head -n 4
Success, no errors or warnings detected
TARGET    SOURCE                    FSTYPE OPTIONS
/srv/data /dev/mapper/vgdata-lvdata ext4   rw,noatime
TARGET       SOURCE                       FSTYPE OPTIONS
/srv/archive /dev/mapper/vgdata-lvarchive xfs    rw,noatime,attr2,inode64,…
● srv-data.mount - /srv/data
     Loaded: loaded (/etc/fstab; generated)
     Active: active (mounted) since Tue 2026-11-17 10:20:31 UTC; 3s ago
      Where: /srv/data

Loaded: … (/etc/fstab; generated) Description The unit is generated by the generator according to fstab. Some versions of findmnt --verify will prompt for nofail entries, which is normal.

Prepare the directory for backup and let the service declare its dependence on the mount point(The backup timer of module 7 will be used):
sudo install -d -o root -g myapp -m 0770 /srv/data/backups
systemctl show srv-data.mount -p Requires,Wants,Before | head

Module 7's myapp-backup.service is written RequiresMountsFor=/srv/data: systemd automatically adds Requires + After to srv-data.mount. The backup fails when the disk is not present, instead of writing to an empty directory on the root file system.

Create a 1 GiB swap file and persist it:
swapon --show; free -h | head -2
sudo fallocate -l 1G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile  none  swap  sw  0  0' | sudo tee -a /etc/fstab
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-linuxlab.conf
sudo sysctl --system | grep swappiness
swapon --show
               total        used        free      shared  buff/cache   available
Mem:           3.8Gi       412Mi       2.9Gi       1.1Mi       690Mi       3.4Gi
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=5d0c…
* Applying /etc/sysctl.d/99-linuxlab.conf ...
vm.swappiness = 10
NAME      TYPE SIZE USED PRIO
/swapfile file   1G   0B   -2

The first line swapon --show has no output, indicating that the cloud image originally has no swap space.

Verify boot safety: observe the behavior when the disk is missing after restarting (The loopback device will not be automatically rebuilt, just simulating "the data disk is not attached"):
sudo systemctl reboot
# After reconnecting:
systemctl is-system-running
systemctl --failed --no-pager
journalctl -b -u srv-data.mount --no-pager | tail -n 3
swapon --show
degraded
  UNIT                 LOAD   ACTIVE SUB    DESCRIPTION
● srv-archive.mount    loaded failed failed /srv/archive
● srv-data.mount       loaded failed failed /srv/data
systemd[1]: Timed out waiting for device dev-disk-by\x2duuid-7c1e….device - /dev/disk/by-uuid/7c1e….
systemd[1]: Dependency failed for srv-data.mount - /srv/data.
NAME      TYPE SIZE USED PRIO
/swapfile file   1G   0B   -2

The system starts normally, can log in via SSH, and only the status is degraded - this is nofail + 10 seconds timeout effect. If there is no nofail, the console will display "You are in emergency mode".

Recover the data volume(required every time after restarting linuxlab, or do the next advanced step):
sudo losetup -fP /var/lib/linuxlab-disks/disk1.img
sudo losetup -f  /var/lib/linuxlab-disks/disk2.img
sudo vgchange -ay vgdata
sudo systemctl reset-failed
sudo mount -a && findmnt /srv/data
(Advanced, optional) Use a oneshot unit to mount the loopback device early in the boot——Exercise at the same time DefaultDependencies=no and Before=:
sudo tee /etc/systemd/system/linuxlab-loops.service >/dev/null <<'EOF'
[Unit]
Description=Attach linuxlab loop disk images
DefaultDependencies=no
After=systemd-udevd.service
Before=local-fs-pre.target
Wants=local-fs-pre.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/sbin/losetup -fP /var/lib/linuxlab-disks/disk1.img
ExecStart=/usr/sbin/losetup -f /var/lib/linuxlab-disks/disk2.img
ExecStop=/bin/sh -c '/usr/sbin/losetup -j /var/lib/linuxlab-disks/disk1.img -O NAME -n | xargs -r /usr/sbin/losetup -d'

[Install]
WantedBy=local-fs-pre.target
EOF
sudo systemctl daemon-reload && sudo systemctl enable linuxlab-loops.service

Principle: DefaultDependencies=no Remove the implicit dependency after sysinit/basic so that it runs before the local file system is mounted; udev triggers LVM after the loopback device appears Automatically activate, srv-data.mount waits until the device can be mounted. /var/lib/linuxlab-disks on the root file system is now available. This unit has not been actually restarted for verification in the courseware generation environment. When it fails, the system still starts normally due to nofail. Just press the previous step to restore it manually. Please use real disks in production.

Case 1: The cloud host cannot be started after upgrading specifications

Problem:fstab writes /dev/sdc1 /data ext4 defaults 0 2. After changing the instance specification, the disk detection order changes, /dev/sdc1 becomes another disk or does not exist, local-fs.target fails, the instance stops in emergency mode, and SSH cannot be connected. Method: Enter the emergency shell through the cloud serial console (lessons 3 and 4), change it to UUID and add nofail, systemctl daemon-reload and continue to start. Prevention: Use UUID + nofail + device-timeout for image and configuration management; practice restarting on the test instance before making changes.

Case 2: NFS jitter caused the entire batch of web servers to be stuck for more than 90 seconds after restarting

Problem:NFS mounts without _netdev/nofail, waiting for network storage when booting. Method: Change to _netdev,nofail,x-systemd.automount,x-systemd.mount-timeout=30s, mount only after the first access; the application unit writes RequiresMountsFor=.

Case 3: The database was killed by the OOM killer, and it was later discovered that the host did not have swap

Problem: The nightly report task temporarily occupied a large amount of memory, and there was no swap buffer. The kernel immediately terminated PostgreSQL, which occupied the most memory. Method: Add an appropriate amount of swap (swappiness is set to low) to buffer spikes; set MemoryMax= separately for report tasks (module 1); monitor memory and si/so. Limitations:swap only buffers spikes, and if it continues to be insufficient, it needs to be expanded or optimized.

Common errors and solutions

You are in emergency mode. After logging in, type "journalctl -xb" to view system logs …

Cause: The hard requirement of local-fs.target failed: the most common reasons are that the device in fstab does not exist, the UUID is written incorrectly, and the type is wrong.

journalctl -xb | grep -iE 'mount|timed out|dependency failed' | head
mount -o remount,rw /        # The root file system may be read-only
vi /etc/fstab                 # Comment out the problem line or add nofail
systemctl daemon-reload && systemctl default

Prevention: Non-system volumes will always nofail; findmnt --verify should be completed first. The cloud host requires a serial console to enter the emergency shell.

mount: (hint) your fstab has been modified, but systemd still uses the old version; use 'systemctl daemon-reload' to reload.

Cause:fstab has been changed but the generated unit is still old. Fixed:sudo systemctl daemon-reload.

umount: /srv/data: target is busy.

Cause: There are processes with current directories or open files on this file system (including your own shell). Repair:sudo fuser -vm /srv/data Find the process, stop the service or cd out; use umount -l as a last resort (delayed uninstallation, not recommended for unplugging the disk).

swapon: /swapfile: insecure permissions 0644, fix with: chmod 0600 /swapfile

Cause: The swap file is readable by other users and may leak memory contents. Fixed:sudo chmod 600 /swapfile.

swapon: /swapfile: swapon failed: Invalid argument

Cause: The file has holes (caused by truncate/fallocate on some file systems), the file system does not support it (such as btrfs CoW files) or there is no mkswap. Fixed:dd if=/dev/zero of=/swapfile bs=1M count=1024 After creating the entity file, mkswap; use btrfs filesystem mkswapfile for btrfs.

findmnt --verify: [W] … unreachable source / [E] unsupported filesystem type

Cause:The device corresponding to the UUID does not currently exist/the type is written incorrectly. Fix:sudo blkid Check UUID and TYPE; devices that do not exist but will appear (such as the loopback device in this experiment) must have nofail.

Command line operation questions
1. Write a line of fstab for an NFS share nas:/exports/reports: mount only when accessed for the first time, unmount after 10 minutes of idle time, and do not prevent booting.
nas:/exports/reports  /mnt/reports  nfs  _netdev,nofail,noauto,x-systemd.automount,x-systemd.idle-timeout=10min  0  0
2. Without restarting, check the newly modified fstab and make all entries take effect.
sudo findmnt --verify && sudo systemctl daemon-reload && sudo mount -a && findmnt --real
Scenario Analysis Question
Myapp’s uploaded file is placed in /srv/data, and this line in fstab contains nofail. When the data disk was not mounted during a certain restart, myapp started as usual and wrote the uploaded files into the empty directory /srv/data on the root file system. These files "disappeared" after the disk was restored and mounted the next day. How to avoid it?

nofail only ensures that the boot is not stuck, and does not prevent services that rely on it from starting. RequiresMountsFor=/srv/data should be written in the myapp unit (automatically add Requires + After to srv-data.mount). When the disk is not there, myapp will fail to start and give an alarm, instead of writing it in the wrong place. You can also make the mount point directory non-writable when it is not mounted (chattr +i /srv/data), or let the application check the mark file when it starts. "Disappeared" files can be retrieved in /srv/data of the root file system after unmounting the data disk.

Verified teaching video

▶
Linux Crash Course - The /etc/fstab file — Learn Linux TV
English · fstab column meaning
▶
Why You NEED UUIDs in fstab (Linux Storage Explained) — Learn Linux TV
English · Why use UUID instead of device name
▶
Linux Crash Course - Understanding Memory and Swap Usage — Learn Linux TV
English · Memory and swap

systemd-fstab-generator, nofail and emergency mode: No verified video found, please refer to the animation and official documentation of this module.

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video/MP3. The following storyboards and explanations can be produced by video tools.

Shot 1 · 0–25s
Screen: fstab Three lines of text enter the generator, become three unit blocks, and connect to local-fs.target.
Narration: fstab is not executed directly, but translated into a systemd mount unit.
Lens 2 · 25–60s
Screen: The data disk icon disappears; when there is no nofail, it is a solid line, local-fs.target turns red, and the screen turns into emergency mode black text; after switching to nofail, the line becomes a dotted line, the boot continues, and the status is degraded.
Narration: Without nofail, the entire machine will stop in emergency mode if a data disk is missing; with nofail, the timeout will be shortened, but the mount will fail.
Lens 3 · 60–90s
Screen: The memory module is full, the anonymous page slides into the swap area; the swappiness knob is turned from 60 to 10.
Narration: Swap space leaves a buffer for memory spikes, and swappiness determines whether the kernel prefers to swap out process memory or discard the file cache.
Or score ≥ 70% on the Quiz

Module 5 · Network: ip, ss, routing and DNS resolution

28:00 – 35:00 · Behind a curl: the name is first resolved by NSS and systemd-resolved into an address, the socket then selects the exit and source address from the routing table, the neighbor table changes the next hop to MAC, and is finally sent out by the network card; troubleshooting network problems is to check station by station along this route
7 minutesiproute2 · systemd-resolved · NetplanCore Animation★★★★★
Learning Objectives
  • Use ip -br link/addr, ip route, ip route get, ip neigh to read the interface, address, default gateway, and exit to a destination.
  • Use ss to distinguish listening (LISTEN) and established (ESTAB) connections, find out the process to which the port belongs, and understand the differences between 0.0.0.0, 127.0.0.1, and [::] listening.
  • Say the full path of domain name resolution: getaddrinfo() → /etc/nsswitch.conf → /etc/hosts → /etc/resolv.conf (127.0.0.53) → systemd-resolved → upstream DNS; know dig and curl Why the results may be different.
  • Understand Ubuntu's Netplan (YAML generated by cloud-init → systemd-networkd) and RHEL's NetworkManager (nmcli), and be able to use netplan try to safely change the network.
Prerequisite knowledge:Basic concepts of IP address, subnet mask, and port. Importance:★★★★★

What: Five "tables" of the Linux network stack

ObjectsQuestions answeredCommandslinuxlab example
Interface (link)What network cards are there? Is it UP? MAC vs. MTU? ip -br linklo, eth0 (usually eth0 under Hyper-V, ens3/enp0s1 under QEMU/KVM)
Address (addr)What IPs are configured on each interface? ip -br addr172.25.112.34/20(DHCP)
Route (route)To reach a certain destination address, which interface should be used, which next hop should be passed, and which source address should be used? ip route, ip route get purposedefault via 172.25.112.1 dev eth0
Neighbor (neigh)What is the MAC of an IP in the same network segment? (IPv4 ARP / IPv6 NDP)ip neighGateway 172.25.112.1 → 00:15:5d:…
Socket (socket)Which processes are listening on which ports? What are the connections? ss -tulpn, ss -tnpgunicorn 0.0.0.0:5000, redis 127.0.0.1:6379

There are two other tables whose names only need to be known in this lesson: netfilter/nftables rules (firewall, ufw, firewalld is its front end; Ubuntu default ufw is not enabled) and conntrack connection tracking table. ifconfig, netstat, and route (net-tools) are obsolete and are not installed by default on new systems.

How ①: An outbound TCP connection (take curl http://archive.ubuntu.com/ as an example)

  1. Name resolution: curl calls glibc's getaddrinfo(), press Check the hosts: lines of /etc/nsswitch.conf in order (Ubuntu Server usually files dns): first /etc/hosts, then press /etc/resolv.conf to send a DNS request.
  2. Ubuntu's /etc/resolv.conf links to /run/systemd/resolve/stub-resolv.conf, only nameserver 127.0.0.53 - the native systemd-resolved stub resolver. resolved: Check the cache first, and if there is no match, query the upstream DNS (delivered by DHCP or configured by Netplan) of the link, and supports split DNS by domain name.
  3. Create the socket and connect(): The kernel does route lookup, selects the route based on the longest prefix match (here is default via gateway dev eth0), and determines the source address (the address of eth0) and the source port (temporary port range net.ipv4.ip_local_port_range).
  4. Neighbor resolution: The next hop is the gateway and its MAC is required. Check the neighbor table. If there is no neighbor table, broadcast ARP "Who is 172.25.112.1?", and cache the reply after receiving it (REACHABLE → STALE...).
  5. Issed: SYN is sent from eth0 via the netfilter OUTPUT/POSTROUTING chain, queue discipline (qdisc), and network card driver; after the three-way handshake, ss can be seen ESTAB.
  6. Return: Network card receives packet → netfilter PREROUTING/INPUT (conntrack recognizes the return packet of the established connection) → Find the socket by four-tuple (source IP, source port, destination IP, destination port) → wake up curl.

When accessing 127.0.0.1 (myapp → Redis), the local routing table is hit, and the packet goes through the loopback interface lo, without going through the network card or ARP - ip route get 127.0.0.1 displays local 127.0.0.1 dev lo.

How ②: The listening address determines who can connect in

Listening addressWho can connectlinuxlab medium
127.0.0.1:6379Native onlyRedis (Ubuntu package defaults to bind 127.0.0.1 -::1) - exactly what we want
0.0.0.0:5000All IPv4 interfacesmyapp (gunicorn --bind ${BIND}, BIND=0.0.0.0:5000 in env file), the host can access
[::]:22 / *:22all IPv6 (usually IPv4 is also accepted, depending on IPV6_V6ONLY)ssh.socket——Note that the process displayed by ss -tlnp is systemd, because PID 1 is listening (socket activation, module 6)

How ③: Who is configuring the network - Netplan, networkd and NetworkManager

Ubuntu Server (including cloud image)Ubuntu DesktopRHEL / Rocky / Alma
Declarative configurationNetplan YAML: /etc/netplan/*.yaml (the cloud image is generated by cloud-init 50-cloud-init.yaml)Netplan(renderer: NetworkManager)NetworkManager keyfile: /etc/NetworkManager/system-connections/ (ifcfg format is deprecated)
Actual executorsystemd-networkd(networkctl)NetworkManagerNetworkManager(nmcli)
DNSsystemd-resolved(resolvectl)systemd-resolvedNetworkManager directly writes /etc/resolv.conf (not enabled by default) resolved)
Security modificationsudo netplan try (automatic rollback if not confirmed within 120 seconds)Graphical interface / nmclinmcli con mod + nmcli con up

ip addr The modifications of add and ip route add are only in memory and disappear after restarting or networkd reconfiguration - suitable for temporary troubleshooting; the persistent configuration is written to Netplan / NetworkManager.

When: troubleshooting order (bottom-up)

  1. Is the local service listening? Is the listening address correct? (ss -tlnp)
  2. The interface is UP. Is there an address? (ip -br addr)
  3. Is the route to the destination correct? (ip route get) Is the next hop available? (ping gateway, ip neigh)
  4. Is the name resolution correct? (getent ahosts name uses the same NSS path; resolvectl query see resolved)
  5. Is the firewall/security group/peer allowed? (nc -vz host port, curl -v)
Common misunderstanding① “dig If it can be parsed, the application can parse it" - dig directly asks the DNS server, bypassing /etc/hosts and nsswitch; the application uses getaddrinfo, should be based on getent ahosts ② "/etc/resolv.conf is 127.0.0.53, so the DNS is broken" - that is the resolved stub of this machine, the real upstream is resolvectl status ③ "Edit directly. /etc/resolv.conf" - it is a symbolic link and will be overwritten; change the Netplan or resolved configuration. ④ "ping unreachable = port unreachable" - ICMP is disabled in many environments; use nc -vz or curl to test the specific port. ⑤ "Service listening 127.0.0.1 That's enough, the host can also access it" - only this machine can connect.

The complete path of an outbound connection

curl / aptgetaddrinfo()NSS(nsswitch.conf)hosts: files dns/etc/hostsIf it hits, it will be returned directlysystemd-resolved127.0.0.53 · Cache · split DNSUpstream DNSDHCP / Netplan specified① Name → Addresssocket + connect()Purpose 91.189.x.x:80Route lookup (longest prefix)default via gateway dev eth0 src …Neighbor table / ARPGateway IP → MACnetfilter → qdisc → drivereth0 issues SYN② address → egressGateway → Internet → ServerSYN-ACK returnconntrack identify return packet → find socket by quadrupless -tnp show ESTAB 172.25.112.34:52814 → 91.189.x.x:80③ BackhaulWhen accessing 127.0.0.1: The route hits the local table → lo interface, does not go through the network card, and does not require ARP
Figure 5-1 Name resolution is completed in user mode (glibc + resolved); routing, neighbor, filtering and sending are all completed in the kernel (the address is an example)

Netplan location

cloud-initFirst boot generation/etc/netplan/*.yamlDeclarative, permissions 600netplan generate→ /run/systemd/network/systemd-networkd (server)NetworkManager (desktop)
Figure 5-2 Netplan is just a "translator", press renderer to generate the configuration of networkd or NetworkManager

Core Animation: The journey of a data packet (socket → routing table → network card, and DNS resolution)

Choose an access, step by step to see which table to check at each layer and what you get. Faults can be switched to see which station the troubleshooting command found the problem.

Process—NSS / hosts—resolved 127.0.0.53—Upstream DNS—Socket—Routing table—Neighbor table—netfilter—Interface—Peer end—ss status seen—
Select the access type and click "Next".
Key points to observeThe log of each step is the check command you can execute on the real machine. When switching "Upstream DNS Unreachable", please note: ping 91.189.91.81 It still works - the network is good, but the bad thing is name resolution; when switching "Default Route Lost", DNS will also fail (the upstream DNS also needs to go through the default route), so repair the route first.

Network commands

CommandsFunctionDescription
ip -br link / ip -br addr / ip -c aInterface/Address (concise/color)Replace ifconfig
ip route / ip -6 routeMain routing tableip route show table local View local routing
ip route get 1.1.1.1The actual selection of the destination by the kernelView the exit, next hop, and source address at once
ip neighARP/NDP neighbor tableFAILED/INCOMPLETE = Layer 2 is blocked
sudo ip addr add 10.99.0.1/24 dev lab0 / ip route add …Temporary modificationRestart fails
ss -tulpnTCP/UDP listening port and processSee the process and you need sudo
ss -tnp state established '( dport = :6379 )'Filter established connectionsss filter syntax
ss -sSocket statisticsTIME-WAIT number
getent ahosts NameResolved by NSS (consistent with application)—
resolvectl status / resolvectl query NameDNS server per link / resolvedresolvectl statistics, flush-caches
dig @1.1.1.1 example.com +shortAsk a DNS server directlybind9-dnsutils package
nc -vz host port / curl -vTest TCP port / HTTPMore descriptive than ping
tracepath host / mtrPath and MTU—
sudo tcpdump -ni eth0 port 53Capture packetFinal judge
netplan get / netplan status / sudo netplan try / applyNetplan configuration/status/application with rollback—
networkctl statussystemd-networkd perspective—
nmcli dev status / nmcli con showNetworkManager (RHEL system)rhellab
sudo ufw status verboseUbuntu firewall front-end statusDefault inactive; firewall will be discussed in depth in subsequent courses
ip -br addr
ip route
ip route get 1.1.1.1
ip route get 127.0.0.1
ls -l /etc/resolv.conf; grep -v '^#' /etc/resolv.conf
grep '^hosts:' /etc/nsswitch.conf
lo               UNKNOWN        127.0.0.1/8 ::1/128
eth0             UP             172.25.112.34/20 fe80::215:5dff:fe01:2a3b/64
default via 172.25.112.1 dev eth0 proto dhcp src 172.25.112.34 metric 100
172.25.112.0/20 dev eth0 proto kernel scope link src 172.25.112.34 metric 100
172.25.112.1 dev eth0 proto dhcp scope link src 172.25.112.34 metric 100
1.1.1.1 via 172.25.112.1 dev eth0 src 172.25.112.34 uid 1000
    cache
local 127.0.0.1 dev lo src 127.0.0.1 uid 1000
    cache <local>
lrwxrwxrwx 1 root root 39 … /etc/resolv.conf -> ../run/systemd/resolve/stub-resolv.conf
nameserver 127.0.0.53
options edns0 trust-ad
search mshome.net
hosts:          files dns

Lab 5: Tracing myapp's connection and a DNS query (about 8 minutes)

Who is listening?
sudo ss -tlnp
State  Recv-Q Send-Q Local Address:Port  Peer Address:Port Process
LISTEN 0      511        127.0.0.1:6379       0.0.0.0:*     users:(("redis-server",pid=812,fd=6))
LISTEN 0      2048         0.0.0.0:5000       0.0.0.0:*     users:(("gunicorn",pid=2433,fd=5),("gunicorn",pid=2432,fd=5),("gunicorn",pid=2402,fd=5))
LISTEN 0      4096   127.0.0.53%lo:53         0.0.0.0:*     users:(("systemd-resolve",pid=540,fd=15))
LISTEN 0      4096      127.0.0.54:53         0.0.0.0:*     users:(("systemd-resolve",pid=540,fd=17))
LISTEN 0      4096               *:22               *:*     users:(("sshd",pid=…),("systemd",pid=1,fd=…))
LISTEN 0      511            [::1]:6379          [::]:*     users:(("redis-server",pid=812,fd=7))

Note three points: the gunicorn main process shares the same listening socket with the two workers; 127.0.0.54 is the resolved "proxy stub" (no local synthesis, forwarded as is); the holder of port 22 contains PID 1 - Ubuntu's ssh is socket activated (module 6).

Which way does the connection between myapp ↔ Redis take? First let myapp access Redis once (if /healthz does not access Redis, use any interface that will access Redis), and then:
for i in 1 2 3; do curl -s -o /dev/null http://127.0.0.1:5000/; done
sudo ss -tnp '( dport = :6379 or sport = :6379 )'
ip route get 127.0.0.1
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
ESTAB 0      0          127.0.0.1:41872    127.0.0.1:6379  users:(("gunicorn",pid=2433,fd=9))
ESTAB 0      0          127.0.0.1:6379     127.0.0.1:41872 users:(("redis-server",pid=812,fd=9))
local 127.0.0.1 dev lo src 127.0.0.1 uid 1000
    cache <local>

The same connection appears twice on this machine (both ends are on this machine). If there is no ESTAB line, it means that the application creates and closes connections for each request, or the interface does not access Redis - you can use redis-cli monitor to observe.

An external network access: DNS → Routing → Neighbors:
getent ahosts archive.ubuntu.com | head -3
resolvectl query archive.ubuntu.com
resolvectl status | sed -n '/Link 2/,/^$/p'
ip route get "$(getent ahostsv4 archive.ubuntu.com | awk 'NR==1{print $1}')"
ip neigh show dev eth0
91.189.91.81    STREAM archive.ubuntu.com
91.189.91.81    DGRAM
91.189.91.81    RAW
archive.ubuntu.com: 91.189.91.81                 -- link: eth0
                    185.125.190.83               -- link: eth0
                    …
-- Information acquired via protocol DNS in 23.4ms.
-- Data is authenticated: no; Data was acquired via local or encrypted transport: no
Link 2 (eth0)
    Current Scopes: DNS
         Protocols: +DefaultRoute -LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
Current DNS Server: 172.25.112.1
       DNS Servers: 172.25.112.1
        DNS Domain: mshome.net
91.189.91.81 via 172.25.112.1 dev eth0 src 172.25.112.34 uid 1000
    cache
172.25.112.1 lladdr 00:15:5d:01:22:aa REACHABLE

The upstream DNS is issued by DHCP (here is the gateway of the Hyper-V default switch). The address, interface name, and link number are examples.

Local name: Give Redis an alias and verify hosts first:
echo '127.0.0.1 redis.lab' | sudo tee -a /etc/hosts
getent hosts redis.lab
resolvectl query redis.lab
dig +short @1.1.1.1 redis.lab; echo "dig directly asks public DNS: no output"
127.0.0.1       redis.lab
redis.lab: 127.0.0.1                             -- link: lo
-- Information acquired via protocol DNS in …
dig directly asks public DNS: no output

dig does not read /etc/hosts and only sends DNS requests. However, systemd-resolved defaults to ReadEtcHosts=yes and will synthesize hosts entries into the answer, so dig redis.lab (Ask 127.0.0.53) on Ubuntu may also have results; specify @1.1.1.1 or it will not be found on RHEL systems that are not resolved. Conclusion: To determine what the application will parse into, use getent.

Temporary network objects: dummy interfaces and routes (disappeared after restarting):
sudo ip link add lab0 type dummy
sudo ip addr add 10.99.0.1/24 dev lab0
sudo ip link set lab0 up
ip route get 10.99.0.5
sudo ip link del lab0
10.99.0.5 dev lab0 src 10.99.0.1 uid 1000
    cache
Understand (but do not change) Netplan configuration:
sudo ls -l /etc/netplan/
sudo netplan get
sudo netplan status --all 2>/dev/null | head -n 15
-rw------- 1 root root 191 … 50-cloud-init.yaml
network:
  version: 2
  ethernets:
    default:
      match:
        macaddress: "00:15:5d:01:2a:3b"
      dhcp4: true
      dhcp-identifier: "mac"
      set-name: "eth0"
…

When changing the static address, create a new file (such as 90-static.yaml, permission 600), and then sudo netplan try: Automatic rollback within 120 seconds without pressing Enter to confirm - the only safe way to change the network remotely. Please maintain DHCP for Multipass instances, otherwise multipass may not be able to find the instance IP.

Case 1: "The service is up, but cannot be accessed from the outside"

Problem: The new service systemctl status is active, curl localhost:8080 is normal, but the load balancing health check failed. Diagnosis:ss -tlnp shows listening at 127.0.0.1:8080. How to do it: Change to monitor 0.0.0.0 (or a specific intranet address), and confirm that the firewall/cloud security group allows it (Lessons 3 and 4). Conversely: Backends such as Redis and databases should only listen to loopback or intranet addresses.

Case 2: Intermittent DNS timeout causes interface P99 to spike

Problem: The application resolves the external API domain name for each request, upstream DNS occasionally loses packets, and glibc defaults to a 5-second timeout to retry. Diagnosis:resolvectl statistics looks at cache hits and failures, tcpdump port 53 looks at retransmissions. Method: Rely on resolved local cache (do not bypass 127.0.0.53 to directly connect to the upstream); configure multiple upstream DNS; reuse connections on the application side.

Case 3: After adding the second network card, the return traffic went to the wrong interface

Problem: After adding the management network card, both network cards obtained the default route through DHCP, and the return packet accessing the management address was sent from the business network card and was discarded by the upstream firewall (asymmetric routing). Diagnosis:ip route has two defaults. ip route get client IP from management address chooses the wrong exit. Method: Set dhcp4-overrides: {use-routes: false} for the management network card in Netplan, or configure policy routing (routing-policy + independent routing table).

Common errors and solutions

curl: (6) Could not resolve host: archive.ubuntu.com
getent ahosts archive.ubuntu.com; resolvectl status; resolvectl query archive.ubuntu.com
ping -c1 "$(resolvectl status | awk '/Current DNS Server/{print $4; exit}')"

Cause: The upstream DNS is unreachable or not configured, resolved is not running, /etc/resolv.conf is modified. Fixed:systemctl status systemd-resolved; confirm link has DNS servers (Netplan nameservers:); restore link sudo ln -sf ../run/systemd/resolve/stub-resolv.conf /etc/resolv.conf.

connect: Network is unreachable

Cause: The routing table does not have a route matching the destination (usually due to the default route being lost or the interface DOWN). Fix:ip route, ip -br link; sudo networkctl reconfigure eth0 or sudo netplan apply to restore DHCP configuration.

curl: (7) Failed to connect to 127.0.0.1 port 5000: Connection refused

Cause: There is no process listening on this address port (the service is not up, or it is listening on another address/port). refused means that the peer (here, the local kernel) responded RST, indicating that the network is connected. Fixed:sudo ss -tlnp | grep 5000, systemctl status myapp.

curl: (28) Connection timed out after 10001 milliseconds

Reason: SYN has no response: the firewall dropped it, the security group did not allow it, the route is unreachable, and the peer is not available - different from refused, it means "no one answered". Fix: Bottom-up: ip route get → ip neigh → sudo tcpdump -ni eth0 tcp port 5000 (whether SYN is sent/arrived) → check firewall rules.

** (generate:1234): WARNING **: Permissions for /etc/netplan/90-static.yaml are too open. Netplan configuration should NOT be accessible by others.

Reason:Netplan files may contain sensitive information such as Wi-Fi passwords and must be readable only by root. Fixed:sudo chmod 600 /etc/netplan/*.yaml.

bind: Address already in use(gunicorn: Connection in use: ('0.0.0.0', 5000))

Cause: The port is occupied by another process (such as gunicorn started manually in Lesson 1). Fixed:sudo ss -tlnp 'sport = :5000' found and stopped the process.

Command line operation questions
1. A command to find out: When accessing 10.20.30.40 from this machine, which interface, which next hop and which source address will be used by the kernel.
ip route get 10.20.30.40
2. List all established TCP connections to port 5000 and their processes.
sudo ss -tnp state established '( sport = :5000 )'
Scenario analysis question
The developer said: "dig api.partner.com returns the correct address, but the application keeps connecting to an old IP." What are the possible reasons? How to verify?

① /etc/hosts has old hard-coded entries - dig does not read hosts, the application does; verify with getent ahosts api.partner.com. ② The application or runtime caches DNS (JVM's networkaddress.cache.ttl, long connection pool uses the old connection); ss -tnp Check the peer address and restart the connection pool. ③ Resolved cache or split DNS: The domain name has gone to the DNS of another link (resolvectl query displays the link), resolvectl flush-caches and then check again. ④ The server asked by dig is different from the system (default is 127.0.0.53, it will be different if @ is specified).

Verified instructional video

▶
How to Use the ip Command in Linux: A Beginner’s Guide — Learn Linux TV
English · ip addr / link / route
▶
How to Use the ss Command (Linux Crash Course Series) — Learn Linux TV
English · Sockets and ports
▶
Why does /etc/resolv.conf point at 127.0.0.53 in Linux? — Slap Ya Administrator
English · systemd-resolved Stub parser
▶
How to Set a Static IP on Ubuntu Server 26.04 | Netplan Tutorial — KeepItTechie
English · Netplan static addresses on 26.04

Official documentation

Video storyboard script (about 100 seconds)

This courseware cannot directly generate videos/MP3s. The following storyboards and explanations can be produced by video tools.

Shot 1 · 0–30s
Screen: curl holds the sign of archive.ubuntu.com, knocks on the door of nsswitch, hosts, 127.0.0.53 in sequence, resolved and gets the IP back from the cache or upstream.
Narration: The application uses getaddrinfo to resolve the name. On Ubuntu, it first checks the hosts, then asks the local machine for resolution, which then asks the upstream DNS.
Shot 2 · 30–60s
Screen: SYN packet enters the kernel, routing table highlights default via gateway dev eth0; neighbor table replaces gateway IP with MAC; packet flies out from eth0.
Narration: The kernel selects routes based on the longest prefix match and determines the source address, and then uses the neighbor table to find the next hop MAC.
Lens 3 · 60–100s
Screen: The return packet finds the socket through conntrack, ss displays ESTAB; cut to 127.0.0.1, the packet goes around lo and comes back directly.
Narration: The return packet finds the socket according to the four-tuple; the loopback traffic does not pass through the network card and does not require ARP. The investigation is carried out along this road station by station.
Or score ≥ 70% on the Quiz

Module 6 · SSH: Keys, Configuration and Hardening

35:00 – 42:00 · SSH is the door to the server: use keys instead of passwords, use client configuration to reduce errors, use sshd_config.d Snippets harden the server - and never lock yourself out in the process
7 minutesOpenSSH 10.2★★★★★
Learning objectives
  • Name the stages of an SSH connection: TCP → Version Exchange → Key Exchange (KEX) → Host Key Verification (known_hosts) → User authentication (publickey) → session channel.
  • Generate Ed25519 key (with password), use ssh-agent, install the public key to ~/.ssh/authorized_keys, and set permissions correctly.
  • Write ~/.ssh/config (Host Alias, User, IdentityFile, IdentitiesOnly, ProxyJump).
  • Understand the relationship between sshd configuration "Each keyword is subject to the value that appears for the first time" and Include /etc/ssh/sshd_config.d/*.conf, write hardening fragments and verify with sshd -t / sshd -T; know Ubuntu ssh.socket How to correctly change the port under socket activation.
Prerequisite knowledge:Users, permissions and sudo in Lesson 1; socket unit in Module 1; ports and monitoring in Module 5. Importance:★★★★★

What: Two pairs of keys in SSH

Host keyUser key
What to prove"It is indeed that server you are connected to""It is indeed you who is logging in"
Private key locationServer /etc/ssh/ssh_host_ed25519_key etc.Client ~/.ssh/id_ed25519 (should be password protected)
Who remembers the public keyClient ~/.ssh/known_hosts (TOFU: Trust On First Use when connecting for the first time)Server ~/.ssh/authorized_keys
When changedClient reports REMOTE HOST IDENTIFICATION HAS CHANGED!——It may be a reinstallation or a man-in-the-middle attackServer refused: Permission denied (publickey)

How: A connection process

  1. TCP connection to 22 Port (first accepted by ssh.socket with PID 1 on Ubuntu, and ssh.service started if necessary).
  2. Version exchange: Both parties send SSH-2.0-OpenSSH_10.2….
  3. Key Exchange (KEX): Negotiation algorithm to calculate the shared session key. OpenSSH 10.0 uses the post-quantum hybrid algorithm mlkem768x25519-sha256 by default, and completely removes DSA key support.
  4. Host authentication: The server signs with the host's private key, and the client verifies with the public key recorded in known_hosts.
  5. User authentication: The client proposes the public key → the server checks authorized_keys → the client signs the session data with the private key → the server verifies the signature. The private key never leaves the client. There are also password, keyboard-interactive (PAM, MFA can be connected) and other methods.
  6. Session: After authentication, sshd derives a session process with downgraded rights (sshd-session is removed from OpenSSH 9.8 and authenticated in sshd-auth from 10.0), and a login session is established through PAM (created by systemd-logind) user-1000.slice), start the shell.

Why: Why disable password login

  • Port 22 exposed to the public network receives a large number of automated password blasts every day; key authentication makes such attacks completely ineffective.
  • Ed25519 Private key + password + ssh-agent: safe and convenient; even if the private key is stolen, a password is required to use it.
  • Advanced: SSH certificate (issued by CA, with validity period), cloud vendor identity integrated login (Azure Entra ID login, AWS EC2 Instance Connect / Session Manager, Lessons 3 and 4), bastion host / ProxyJump.

How: Validation rules for sshd configuration (easiest to step on pitfalls)

  • sshd_config(5): Most keywords are subject to the value obtained for the first time, and subsequent settings with the same name are ignored (contrary to many software "the latter overrides the former").
  • Ubuntu's /etc/ssh/sshd_config The beginning is Include /etc/ssh/sshd_config.d/*.conf, so the fragment settings take precedence over the main file; fragments are read in file name dictionary order, and the smaller number takes effect first.
  • Cloud images (including Multipass) often have /etc/ssh/sshd_config.d/50-cloud-init.conf written by cloud-init (such as PasswordAuthentication). If the hardening file is named 99-hardening.conf, the keyword with the same name will be preempted by 50-cloud-init - it should be named 10-….
  • Match block (such as Match User deploy) can only be placed at the end of the file or in a fragment, and all lines after it belong to the block until the next Match.
  • The final effective value is subject to the output of sudo sshd -T (you can add -C user=…,host=…,addr=… to simulate a certain connection to evaluate the Match block).

Ubuntu's ssh.socket (socket activation)

Ubuntu 22.10 and up openssh-server defaults to ssh.socket socket activation: PID 1 listens on port 22, starts when the first connection arrives ssh.service; The listening port and address are generated by the systemd generator according to the Port/ListenAddress of sshd_config. Therefore:

  • Modify the authentication class settings: sudo sshd -t && sudo systemctl reload ssh (or restart ssh).
  • Change Port / ListenAddress: Must sudo systemctl daemon-reload (rerun the generator) after sudo systemctl restart ssh.socket - only restarting ssh.service will not take effect (see Launchpad bug 2069041, Ubuntu's sshd_config Also stated in the notes).
  • RHEL system: service name sshd.service, no socket activation by default; changing the port also requires SELinux (semanage port -a -t ssh_port_t -p tcp 2222) and firewalld.

When: Reinforcement list (sorted by revenue)

SettingsFunctionNote
PasswordAuthentication no, KbdInteractiveAuthentication noOnly keys allowedConfirm that the key login is successful first
PermitRootLogin noProhibit root direct loginUse ordinary user + sudo, the audit can be traced back to the person
AllowUsers / AllowGroupsWhitelistMultipass instance must be retained ubuntu (used by multipass shell)
MaxAuthTries 3, LoginGraceTime 30Reduce the blast windowWhen there are too many keys in the agent, the number of times may be used up → Use IdentitiesOnly
X11Forwarding no, AllowAgentForwarding no, AllowTcpForwarding noReduce the attack surfaceRequires port forwarding / Use Match to open by user during springboard
ClientAliveInterval 300, ClientAliveCountMax 2Clean up zombie sessions—
Network layerFirewall/security group is only open to the management network segment 22; fail2ban or sshd's own PerSourcePenalties (OpenSSH 9.8+) Suppressing blastsChanging ports can only reduce log noise, not a security measure
Common misunderstandings① "Add a line at the end of sshd_config PasswordAuthentication no It will take effect" - if the previous (including Include) already appears, the last line is ignored. ② "Restarting ssh will disconnect my current connection" - the established sessions are hosted by their respective session processes, and restarting/reloading the listening process will not disconnect them; but if the new configuration is wrong and cannot be started, you will not be able to establish a new connection - so be sure to do it first sshd -t, and keep a logged-in session for testing. ③ "authorized_keys permissions don't matter" - StrictModes yes(default), when the home directory or ~/.ssh is writable by the group/others, sshd refuses to use the keys in it. ④ "Just delete the known_hosts warning" - first check the new fingerprint through out-of-band methods.

SSH connection timing

Client (your computer)ssh.socket / sshdSession (sshd-session → shell)① TCP SYN → :22 (PID 1 accepted, started ssh.service)② SSH-2.0-OpenSSH_10.2 version exchange③ KEX: mlkem768x25519-sha256 → Session key④ Host key signatureCheck ~/.ssh/known_hosts⑤ I want to use this public key to log in to labadminCheck ~labadmin/.ssh/authorized_keys⑥ Private key signature (ssh-agent signature)⑦ Authentication passed → PAM → logind → shell⑧ Encrypted session channel (shell, scp, port forwarding)
Figure 6-1 Host authentication precedes user authentication: first confirm "who the other party is", and then prove "who I am"

Configuration reading order and "the first value takes effect"

Sshd_config line 1: Include …d/*.conf10-linuxlab-hardening.conf ✓ Read first50-cloud-init.conf (the entry with the same name is ignored)99-xxx.conf: The entry with the same name is too late and is invalidThe rest of sshd_config (read last)
Figure 6-2 For the same keyword, the first read value takes effect; use sshd -T to confirm the final result

Animation: SSH connection and authentication - which error report corresponds to each failure point

Select the scenario and execute it step by step to observe at which stage the connection succeeds or fails, and what is recorded by the client/server respectively.

Clientssh linuxlabknown_hosts—ssh.socket :22listeningKEX + host authentication—sshd effective configuration—authorized_keys—Session—
Click "Next" after selecting the scenario.

SSH client and server commands

CommandFunctionInstructions
ssh-keygen -t ed25519 -a 100 -C "labadmin@laptop" -f ~/.ssh/linuxlab_ed25519Generate Ed25519 key-a Increase the number of KDF rounds for the password
ssh-copy-id -i ~/.ssh/linuxlab_ed25519.pub labadmin@HOSTInstall the public keyWindows None ssh-copy-id, see experiment
eval "$(ssh-agent -s)"; ssh-add ~/.ssh/linuxlab_ed25519Start the agent and load the private keyWindows: Start-Service ssh-agent
ssh -v linuxlab / -vvvDebug outputSee which keys are provided and which steps failed
ssh -J bastion targetConnect via springboardProxyJump in config
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pubServer host key fingerprintComparison with client display when first connected
ssh-keygen -R HOSTRemove old entries from known_hostsCheck the new fingerprint before doing it
sudo sshd -tCheck the configuration syntaxPass if there is no output
sudo sshd -T / sudo sshd -T -C user=labadmin,host=h,addr=10.0.0.5Output the final effective configuration/simulate a certain connectionKeywords are output in lowercase
sudo systemctl reload sshRe-read the configurationRHEL: sshd
sudo systemctl daemon-reload && sudo systemctl restart ssh.socketAfter Ubuntu changes Port/ListenAddress—
journalctl -u ssh -f / journalctl -t sshd-sessionAuthentication logWrite also when there is rsyslog /var/log/auth.log
who / last -n 5 / loginctl list-sessionsCurrent and historical login—
ls /etc/ssh/sshd_config.d/
grep -n -E '^(Include|#?Port)' /etc/ssh/sshd_config | head
systemctl is-enabled ssh.socket ssh.service
50-cloud-init.conf
12:Include /etc/ssh/sshd_config.d/*.conf
14:#Port 22
enabled
disabled

ssh.socket enabled, ssh.service disabled are typical states of socket activation: the service is pulled up on demand by the socket. The line number depends on your version.

Experiment 6: Key login, client configuration and server hardening (about 10 minutes)

Security tipsKeep one throughout this experiment multipass shell linuxlab The session does not exit; if any step fails, you can roll back from this session (delete the reinforcement fragment and reload).
Generate the key on the host machine(Windows PowerShell, macOS, Linux commands are the same):
ssh-keygen -t ed25519 -a 100 -C "labadmin@linuxlab-course" -f ~/.ssh/linuxlab_ed25519
# Set a password when prompted for a password
Install the public key to the labadmin account of linuxlab:
# macOS/Linux host (when you need to be able to log in first through other methods):
#   ssh-copy-id -i ~/.ssh/linuxlab_ed25519.pub labadmin@<IP>
# General method (including Windows): pass in the public key via multipass
multipass transfer ~/.ssh/linuxlab_ed25519.pub linuxlab:/tmp/linuxlab_ed25519.pub
multipass exec linuxlab -- sudo bash -c '
  install -d -o labadmin -g labadmin -m 700 ~labadmin/.ssh
  cat /tmp/linuxlab_ed25519.pub >> ~labadmin/.ssh/authorized_keys
  chown labadmin:labadmin ~labadmin/.ssh/authorized_keys
  chmod 600 ~labadmin/.ssh/authorized_keys
  rm /tmp/linuxlab_ed25519.pub
  ls -la ~labadmin/.ssh'
multipass info linuxlab | grep IPv4
drwx------ 2 labadmin labadmin 4096 Nov 17 10:40 .
drwxr-x--- 5 labadmin labadmin 4096 Nov 17 10:40 ..
-rw------- 1 labadmin labadmin  105 Nov 17 10:40 authorized_keys
IPv4:           172.25.112.34

Windows ~ in the multipass parameter in PowerShell may not be expanded and can be written as $HOME\.ssh\linuxlab_ed25519.pub.

Write client configuration ~/.ssh/config(Host):
Host linuxlab
    HostName 172.25.112.34
    User labadmin
    IdentityFile ~/.ssh/linuxlab_ed25519
    IdentitiesOnly yes
    ServerAliveInterval 60
ssh linuxlab 'hostname; whoami'
The authenticity of host '172.25.112.34 (172.25.112.34)' can't be established.
ED25519 key fingerprint is SHA256:Qm3…k9c.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '172.25.112.34' (ED25519) to the list of known hosts.
Enter passphrase for key '/home/you/.ssh/linuxlab_ed25519':
linuxlab
labadmin

Before answering yes, execute ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub Compare fingerprints – that is, “out-of-band verification.” The IP may change after the Multipass instance is restarted. If it changes, update the HostName.

View the effective configuration before hardening(in linuxlab):
cat /etc/ssh/sshd_config.d/*.conf
sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication|maxauthtries|x11forwarding|allowusers) '
PasswordAuthentication no
permitrootlogin without-password
pubkeyauthentication yes
passwordauthentication no
kbdinteractiveauthentication no
maxauthtries 6
x11forwarding yes
Write the hardening fragment (note that the file name ends with 10- , ranked before 50-cloud-init):
sudo tee /etc/ssh/sshd_config.d/10-linuxlab-hardening.conf >/dev/null <<'EOF'
# linuxlab part2 · SSH hardening (the value that appears for the first time takes effect, so the file name is 10-)
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
# Multipass's multipass shell logs in via SSH as the ubuntu user and must be retained
AllowUsers labadmin ubuntu
MaxAuthTries 3
LoginGraceTime 30
X11Forwarding no
AllowAgentForwarding no
AllowTcpForwarding no
ClientAliveInterval 300
ClientAliveCountMax 2
EOF
sudo chmod 644 /etc/ssh/sshd_config.d/10-linuxlab-hardening.conf
sudo sshd -t && echo "syntax ok"
sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|maxauthtries|x11forwarding|allowusers|authenticationmethods) '
syntax ok
permitrootlogin no
passwordauthentication no
maxauthtries 3
x11forwarding no
allowusers labadmin
allowusers ubuntu
authenticationmethods publickey
Apply and verify innewterminal (old session remains intact):
sudo systemctl reload ssh || sudo systemctl restart ssh
# New terminal of the host:
ssh linuxlab 'echo key-login-ok'
ssh -o PubkeyAuthentication=no -o PreferredAuthentications=password linuxlab true
multipass shell linuxlab   # Confirm that multipass can still be entered, and then exit
key-login-ok
labadmin@172.25.112.34: Permission denied (publickey).

The second command is rejected as expected: the server only accepts public keys. If systemctl reload ssh prompts that the service is not running (there is no connection under socket activation), restart directly; the established session will not be affected.

View the authentication log:
journalctl -u ssh --since "10 min ago" --no-pager | grep -E 'Accepted|Failed|Invalid|Connection closed' | tail -n 5
… sshd-session[3120]: Accepted publickey for labadmin from 172.25.112.1 port 50512 ssh2: ED25519 SHA256:Qm3…
… sshd-session[3188]: Connection closed by authenticating user labadmin 172.25.112.1 port 50530 [preauth]
(Read only, not execute) the correct steps to change the port:
# 1. First release the new port in the firewall/security group
# 2. Write the snippet: echo 'Port 2222' | sudo tee /etc/ssh/sshd_config.d/05-port.conf
# 3. sudo sshd -t
# 4. sudo systemctl daemon-reload && sudo systemctl restart ssh.socket
# 5. New terminal: ssh -p 2222 After the linuxlab test is successful, close the old session and old port
#    Multipass relies on port 22, do not really modify this experiment

Case 1: The entire team cannot log in after hardening

Problem: Configuration management handle AllowUsers admin Pushed to all servers, the deployment account deploy was missed, and all releases failed; the sshd of several servers could not be started due to spelling errors in the fragments. Method: Verify the template in CI before pushing by sshd -t -f; publish in batches; use AllowGroups ssh-users to replace the user name list; retain the out-of-band channel (Cloud Serial Console/Session Manager).

Case 2: "PasswordAuthentication no is clearly written, but the scanner still reports that password login is possible"

Problem: The settings are written at the end of the main file, and cloud-init writes PasswordAuthentication yes in 50-cloud-init.conf, after Include Read first. Practice: Compliance check is based on sshd -T, do not grep the configuration file; use small numbers for reinforcement fragments.

Case 3: Private key leaked to public code repository

Problem: The developer submitted the deployment private key without a password to Git. What to do: Immediately remove the corresponding public key from all authorized_keys (so know the annotation/source of each public key); rotate keys; replace long-term static keys with expired SSH certificates or cloud identities; enable key scanning on the repository (see GitHub Lesson).

Common errors and solutions

Permission denied (publickey).
ssh -v linuxlab 2>&1 | grep -E 'Offering|Authentications that can continue|Server accepts'
# Server side:
journalctl -u ssh -n 20 --no-pager

Cause: The client did not provide the correct private key (the IdentityFile was written incorrectly and was not included in the agent); the public key is not in authorized_keys; the user name is wrong; StrictModes is rejected (permission issue); AllowUsers does not contain the user. Fix: Press ssh -v with server log itemized exclusions.

WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! … Host key verification failed.

Cause:The server host key is different from the known_hosts record: server reinstallation/IP reused by another machine/man-in-the-middle attack. Fix: After out-of-band verification of the new fingerprint, ssh-keygen -R host and reconnect; do not continue if unsure.

Authentication refused: bad ownership or modes for directory /home/labadmin/.ssh

Cause: StrictModes check failed: the home directory or .ssh is writable by group/others, or the owner is wrong. Fixed:chmod 755 ~ (or stricter), chmod 700 ~/.ssh, chmod 600 ~/.ssh/authorized_keys, chown -R labadmin: ~/.ssh.

Received disconnect from … : Too many authentication failures

Cause: There are many ssh-agent keys. The client tries one by one and exceeds the server MaxAuthTries. Fix: Set IdentityFile + IdentitiesOnly yes in ~/.ssh/config for this host. / Removed (ChallengeResponseAuthentication has been replaced by KbdInteractiveAuthentication). Fixed: Subject to man sshd_config; sshd -t after each change.

/etc/ssh/sshd_config.d/10-linuxlab-hardening.conf line 3: unsupported option "ChallengeResponseAuthentication" (or Bad configuration option)

Cause: Keyword is misspelled or deprecated/removed (ChallengeResponseAuthentication has been replaced by KbdInteractiveAuthentication). Fixed: Subject to man sshd_config; sshd -t after each change.

Changed Port 2222. After reload, only port 22 is still listening

Reason: When Ubuntu socket is activated, the port is controlled by ssh.socket. Fixed:sudo systemctl daemon-reload && sudo systemctl restart ssh.socket, then ss -tlnp | grep 2222.

Command line operation questions
1. Without logging in, view the final PasswordAuthentication value of sshd for "user deploy connecting from 10.1.2.3" (consider the Match block).
sudo sshd -T -C user=deploy,host=10.1.2.3,addr=10.1.2.3 | grep -i '^passwordauthentication'
2. Configure in ~/.ssh/config: access the intranet host db1 (10.0.2.15, user labadmin) through the springboard machine bastion (user ops).
Host bastion
    HostName bastion.example.com
    User ops
Host db1
    HostName 10.0.2.15
    User labadmin
    ProxyJump bastion
Scenario analysis question
The security team requires that "all servers prohibit password login, but operation and maintenance personnel need to still be able to enter in an emergency." Please give a plan.

① Only public keys (or SSH certificates), PasswordAuthentication no, PermitRootLogin no, and group whitelist are allowed. ② Do not use SSH password for emergency channels: Cloud Serial Console / Azure Bastion / AWS Session Manager (Lessons 3 and 4), each has an independent identity and audit. ③ When a break-glass account is required: the Match block only allows keyboard-interactive + MFA for this account and only from the bastion machine network segment, and generates a login alarm. ④ Use sshd -T to do automated compliance checks.

Verified teaching video

▶
Linux Crash Course - Public Key Authentication — Learn Linux TV
English · Public key authentication principle and configuration
▶
Getting Started with OpenSSH Key Management — Learn Linux TV
English · Key, agent and ~/.ssh/config
▶
5 Must Have Tweaks to Secure OpenSSH — Learn Linux TV
English · sshd Reinforcement points (recorded earlier, Ubuntu socket activation is subject to this lesson)

Official Document

Video storyboard script (approx. 90 seconds)

This courseware cannot directly generate video/MP3. The following storyboards and explanations can be produced by video tools.

Shot 1 · 0–30s
Screen: The client and the server each take a key; the server first presents the host key, and the client checks known_hosts.
Narration: SSH first confirms who the server is, and then confirms who you are. The client will loudly warn if the host key has changed.
Shot 2 · 30–55s
Screen: The client presents the public key, and the server turns over authorized_keys; the client signs with the private key, and the private key remains locally.
Narration: In public key authentication, the private key never leaves your computer, and the server only verifies the signature.
Lens 3 · 55–90s
Screen: Configuration files are queued into sshd according to 10, 50, and 99. Only the first stamp of the keyword with the same name is "valid"; sshd -T prints the final result.
Narration: sshd takes the first occurrence of most keywords. The hardening fragments are numbered with a small number, whichever is used is sshd -T.
Or score ≥ 70% on the Quiz

Module 7 · Scheduled tasks: cron and systemd timer, time synchronization

42:00 – 50:00 · Timed tasks need to answer four questions: when to run, what to do if missed, in what environment to run, who knows whether the run is successful; and all of this depends on a correct clock
8 minutessystemd.timer · cron · chrony 4.8★★★★☆
Learning objectives
  • Read and write the five crontab time fields, know cron There are few environment variables, % is a special character, and the output is sent to email by default (without MTA, it will be lost).
  • Use .service + .timer Write scheduled tasks: OnCalendar=, Persistent=, RandomizedDelaySec=, AccuracySec=, OnBootSec=/OnUnitActiveSec=, use systemd-analyze calendar to verify.
  • Compare cron and timer: logs, dependencies, sandbox, resource control, missed catch-up, and anti-overlap.
  • Confirm time synchronization: Ubuntu 26.04's chrony (default NTS), timedatectl, chronyc tracking/sources; 24.04 default is systemd-timesyncd.
Prerequisite knowledge:Oneshot service of module 1, RequiresMountsFor of module 4. Importance:★★★★☆

What: two schedulers

cronsystemd timer
DefinitionOne line: Minute Hour Day Month Week [User] CommandTwo units: x.timer (when) + x.service (what to do)
Wherecrontab -e (user), /etc/crontab and /etc/cron.d/* (with user fields), /etc/cron.daily/ and other directories/etc/systemd/system/
Missed tasks during shutdownNo catch-up (anacron only makes up for daily/weekly/monthly directories)Persistent=true Run once after booting
LogSend the output to an email, or redirect it to the file yourselfAutomatically enter journal: journalctl -u x.service
Failure visibilityNeed to handle it yourselfsystemctl --failed, OnFailure= trigger alarm unit
EnvironmentMinimalist environment (short PATH, no login shell configuration)Clear and repeatable: Environment=, EnvironmentFile=
Anti-overlapRequires flockWhen the same service is running, the timer will not start the second instance
Sandbox/Resources/DependenciesNoneModule All options of 1, RequiresMountsFor=, MemoryMax=, Nice=
Multi-machine peak staggeringManual staggeringRandomizedDelaySec= (available FixedRandomDelay=yes Let the offset of each machine be fixed)
Learning costLow, done in one lineTwo files, but more operational and maintainable

Ubuntu Most of its own periodic tasks are timers: logrotate.timer, apt-daily.timer, apt-daily-upgrade.timer (unattended-upgrades), fstrim.timer, man-db.timer, systemd-tmpfiles-clean.timer, systemctl list-timers List.

How ①: cron syntax and traps

# ┌ Minutes (0-59) ┌ Hours (0-23) ┌ Days (1-31) ┌ Months (1-12) ┌ Weeks (0-7, 0 and 7 are both Sundays)
# │            │            │            │            │
  30           2            *            *            *     /usr/local/bin/backup.sh
  */15         *            *            *            1-5   command       # Every 15 minutes on weekdays
# The file in /etc/cron.d/ has one more "user" field:
  30 2 * * *  myapp  /usr/local/bin/backup.sh >>/var/log/myapp/backup.log 2>&1
  • Environment: PATH usually only has /usr/bin:/bin, and does not read ~/.bashrc. Write an absolute path to the script or set PATH= at the top of the crontab.
  • %: The crontab command means line break (the subsequent content is used as standard input), date +%F must be written as date +\%F.
  • Day and week: When neither is *, it is an "or" relationship (it will run if either one is met), not "and".
  • Output: If there is output, try to send it to MAILTO via the local MTA; the server usually does not have an MTA, and the output is lost silently - explicit redirection or use of timer instead.

How ②: time expression of timer

OptionsMeaningExample
OnCalendar=Calendar time (real-time clock)*-*-* 02:30:00, Mon..Fri 09:00, hourly, *:0/15 (every 15 minutes)
OnBootSec= / OnStartupSec=How long after bootingOnBootSec=5min
OnUnitActiveSec= / OnUnitInactiveSec=How long since the last run started/ended (monotonic clock)OnUnitActiveSec=1h
Persistent=trueRecord the last trigger time (/var/lib/systemd/timers/), if you miss it when booting, run it immediatelyOnly valid for OnCalendar
RandomizedDelaySec=Add a random delay between 0 and this value for each triggerMultiple machines to avoid filling up the backup server at the same time
AccuracySec=Allow the precision window of merged wake-ups, the default is 1 minuteSet to when second-level punctuality is required 1s
Unit=The unit to be activated, the default name is .service—
WakeSystem=Wake up from suspend (laptop/desktop)The server is rarely used

Use systemd-analyze calendar --iterations=3 'Mon..Fri 02:30' Verify when an expression fires - more reliable than any cron expression site.

How ③: Time synchronization

  • Why is it important: TLS certificate validity check, Kerberos/cloud API signature (fails if the deviation is a few minutes), cross-machine log correlation, distributed locks and database replication, and the scheduled task itself.
  • Ubuntu 26.04: New installations default to chrony 4.8 (replacing systemd-timesyncd since 25.10), which uses Ubuntu's NTS (Network Time Security, NTP with authentication) server by default; the time source is in /etc/chrony/sources.d/ (such as ubuntu-ntp-pools.sources). Systems upgraded from older versions need to be migrated manually: sudo apt-mark auto systemd-timesyncd && sudo apt install chrony.
  • Ubuntu 24.04: Default systemd-timesyncd (only SNTP client), use timedatectl timesync-status to view.
  • RHEL system: chronyd, configure /etc/chrony.conf.
  • Cloud and Virtualization: Azure recommends Hyper-V's PTP clock source (/dev/ptp_hyperv), and AWS has the Amazon Time Sync Service (169.254.169.123) - see Lessons 3 and 4 for details.
  • It is recommended to use UTC (timedatectl set-timezone UTC) for the server time zone, and then convert it at the display layer; OnCalendar interprets the local time zone by default, which can be explicitly specified by writing OnCalendar=*-*-* 02:30:00 UTC.

When: Which one to choose

  • Newly written system-level tasks (backup, cleanup, reports): timer, especially when logs, failure alarms, make-up runs, and sandboxes are needed.
  • User's own small tasks, existing large cron assets, cross-distribution scripts: cron is still available.
  • Tasks that require a fixed running interval (such as running 10 minutes after the last time): use timer's OnUnitInactiveSec=, cron cannot do this.
Common misunderstandings① "If the command in cron can run in the terminal, it will definitely run" - the environment is different (PATH, HOME, locale, no tty). ② "Timer changes will take effect" - daemon-reload is required, and enable/start is .timer instead of .service. ③ "Persistent=true will make up for every miss" - only make up for once. ④ "Time synchronization is to check when booting up" - chrony continues to be calibrated in a fine-tuning (slew) manner; large jumps (steps) only occur under permitted conditions. ⑤ "NTP will definitely be able to pass through UDP 123" - NTS also needs TCP 4460 for key establishment, and must be allowed in restricted networks. makestep Occurs under permitted conditions. ⑤ "NTP will definitely be able to pass through UDP 123" - NTS also needs TCP 4460 for key establishment, and must be allowed in restricted networks.

Relationship between timer and service

myapp-backup.timerOnCalendar=*-*-* 02:30RandomizedDelaySec=15minPersistent=trueWantedBy=timers.targetmyapp-backup.serviceType=oneshot · User=myappRequiresMountsFor=/srv/dataProtectSystem=strictReadWritePaths=/srv/data/backupsTo startsrv-data.mountAutomatic Requires + Afterjournaldstdout/stderr → LogOnFailure=(optional)Start alarm unit on failure/var/lib/systemd/timers/stamp-myapp-backup.timer: record the last trigger time (Persistent basis)systemctl list-timers display NEXT / LEFT / LAST / PASSED
Figure 7-1 timer is only responsible for "when", service is responsible for "what to do, in what capacity, and under what restrictions"

Time synchronization link

Atomic clock / GPSstratum 0Ubuntu NTS ServerNTS-KE TCP 4460 + NTP UDP 123chronyd(linuxlab)Filtering, source selection, slew adjustmentKernel system clockTLS · Log · timer
Fig. 7-2 NTS uses TLS to establish keys and authenticate NTP messages to prevent time forgery

Interaction: tasks missed during shutdown - cron vs timer

On the weekly timeline, a backup should be run at 02:30 every day. Select the shutdown window and timer options, and click "Simulate one week". The 10 servers below show the peak staggering effect of RandomizedDelaySec.

Click "Simulate a week".

Scheduled tasks and time commands

CommandFunctionDescription
crontab -e / -l / sudo crontab -u myapp -lEdit/View user crontabStored in /var/spool/cron/crontabs/
journalctl -u croncron execution recordOnly records "run", no output
flock -n /run/lock/job.lock commandPrevent cron task overlap—
systemctl list-timers --allNext/last firing of all timers—
systemd-analyze calendar --iterations=5 'Mon..Fri 02:30'Validate calendar expressionShow normalized form and next time
systemd-analyze verify x.timer x.serviceStatic check—
sudo systemctl enable --now x.timerEnable timerDo not enable .service
sudo systemctl start x.serviceManually run the task immediatelyFor testing
systemd-run --on-calendar='*-*-* 03:00' --unit=once-job commandTemporary timer (transient)Disappears after restart
systemd-run --on-active=30s commandRun once after 30 secondsReplacement at
timedatectl / timedatectl set-timezone UTCClock, time zone, synchronization status—
chronyc trackingCurrent deviation, frequency, reference sourceSystem time line is the most critical
chronyc sources -v / chronyc sourcestatsTime source list and statistics* For the currently selected source
sudo chronyc -N authdataNTS certification statusMode is listed as NTS
sudo chronyc makestepImmediate jump correctionWhen the deviation is large; it may affect applications that rely on monotonic time
timedatectl timesync-statussystemd-timesyncd status24.04 default
systemctl list-timers --no-pager | head -n 8
systemd-analyze calendar --iterations=2 '*-*-* 02:30:00'
NEXT                        LEFT       LAST                        PASSED  UNIT                         ACTIVATES
Tue 2026-11-17 11:20:00 UTC 18min      Tue 2026-11-17 11:10:02 UTC 1min ago sysstat-collect.timer       sysstat-collect.service
Tue 2026-11-17 12:47:13 UTC 1h 45min   Tue 2026-11-17 06:12:40 UTC 4h ago   apt-daily.timer              apt-daily.service
Wed 2026-11-18 00:00:00 UTC 12h        Tue 2026-11-17 00:00:01 UTC 11h ago  logrotate.timer              logrotate.service
…
  Original form: *-*-* 02:30:00
Normalized form: *-*-* 02:30:00
    Next elapse: Wed 2026-11-18 02:30:00 UTC
       (in UTC): Wed 2026-11-18 02:30:00 UTC
       From now: 15h left
       Iteration #2: Thu 2026-11-19 02:30:00 UTC
…

Experiment 7: myapp's Redis backup timer, and time synchronization check (about 9 minutes)

Use cron first Write a version and experience its pitfalls:
systemctl is-active cron || sudo apt-get install -y cron
sudo tee /etc/cron.d/myapp-backup-cron >/dev/null <<'EOF'
# m h dom mon dow user command (note % must be escaped as \%)
*/2 * * * *  myapp  redis-cli --rdb /srv/data/backups/cron-$(date +\%H\%M).rdb >/dev/null 2>&1
EOF
sleep 125; ls -l /srv/data/backups/
journalctl -u cron --since "3 min ago" --no-pager | tail -n 2
sudo rm /etc/cron.d/myapp-backup-cron /srv/data/backups/cron-*.rdb
-rw-r--r-- 1 myapp myapp 1024 Nov 17 11:02 cron-1102.rdb
… CRON[3501]: (myapp) CMD (redis-cli --rdb /srv/data/backups/cron-$(date +%H%M).rdb >/dev/null 2>&1)

It "works", but no one knows when it fails (the output is discarded); when /srv/data is not mounted, the backup is written to the empty directory of the root file system; there is no sandbox. Use timer instead. If /srv/data is currently not mounted (after restarting), first press module 4 to restore the data volume.

Write service (what to do):
sudo tee /etc/systemd/system/myapp-backup.service >/dev/null <<'EOF'
[Unit]
Description=Back up myapp Redis data to /srv/data/backups
RequiresMountsFor=/srv/data
Wants=redis-server.service
After=redis-server.service

[Service]
Type=oneshot
User=myapp
Group=myapp
# In the unit file, % is the specifier prefix, and the literal % should be written as %%
ExecStart=/bin/sh -c 'redis-cli --rdb /srv/data/backups/redis-$(date +%%F-%%H%%M).rdb'
ExecStartPost=/usr/bin/find /srv/data/backups -name 'redis-*.rdb' -mtime +7 -delete
Nice=10
IOSchedulingClass=idle
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
ReadWritePaths=/srv/data/backups
EOF
sudo systemd-analyze verify /etc/systemd/system/myapp-backup.service && echo verify-ok
Write timer (when) and enable it:
sudo tee /etc/systemd/system/myapp-backup.timer >/dev/null <<'EOF'
[Unit]
Description=Daily myapp Redis backup

[Timer]
OnCalendar=*-*-* 02:30:00 UTC
RandomizedDelaySec=15min
Persistent=true

[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now myapp-backup.timer
systemctl list-timers myapp-backup.timer --no-pager
Created symlink '/etc/systemd/system/timers.target.wants/myapp-backup.timer' → '/etc/systemd/system/myapp-backup.timer'.
NEXT                        LEFT     LAST PASSED UNIT               ACTIVATES
Wed 2026-11-18 02:41:37 UTC 15h      -    -      myapp-backup.timer myapp-backup.service

NEXT is not 02:30 on the hour, but a random delay is added.

Run the task manually once and check the results immediately:
sudo systemctl start myapp-backup.service
systemctl status myapp-backup.service --no-pager | head -n 6
ls -l /srv/data/backups/
journalctl -u myapp-backup.service -n 5 --no-pager -o cat
○ myapp-backup.service - Back up myapp Redis data to /srv/data/backups
     Loaded: loaded (/etc/systemd/system/myapp-backup.service; static)
     Active: inactive (dead) since Tue 2026-11-17 11:12:09 UTC; 1s ago
TriggeredBy: ● myapp-backup.timer
    Process: 3622 ExecStart=/bin/sh -c redis-cli --rdb /srv/data/backups/redis-$(date +%F-%H%M).rdb (code=exited, status=0/SUCCESS)
-rw-r--r-- 1 myapp myapp 1024 Nov 17 11:12 redis-2026-11-17-1112.rdb
sending REPLCONF capa eof
SYNC sent to master, writing 1024 bytes to '/srv/data/backups/redis-2026-11-17-1112.rdb'
Transfer finished with success.
Starting myapp-backup.service - Back up myapp Redis data to /srv/data/backups...
Finished myapp-backup.service - Back up myapp Redis data to /srv/data/backups.

The oneshot service will be inactive (dead) after success, which is normal; static means there is no [Install] segment and can only be pulled up by timer, etc. redis-cli output wording varies between versions.

Verification protection: Unmount the data volume before running:
sudo umount /srv/data
sudo systemctl start myapp-backup.service; echo "exit=$?"
systemctl show myapp-backup.service -p Result
findmnt -n -o TARGET,SOURCE /srv/data
exit=0
Result=success
/srv/data /dev/mapper/vgdata-lvdata

RequiresMountsFor= Let systemd try to mount first before starting the task /srv/data - if the volume is present, it will be automatically mounted and backed up to the correct location; the task will only start when the volume does not exist (the situation after the module 4 restart) dependency failed. This is exactly what is wanted: never write the backup to the root file system.

Check time synchronization:
timedatectl
systemctl is-active chrony || systemctl is-active systemd-timesyncd
chronyc tracking | grep -E 'Reference ID|System time|Leap status'
chronyc sources
sudo chronyc -N authdata 2>/dev/null | head -n 4
               Local time: Tue 2026-11-17 11:14:20 UTC
           Universal time: Tue 2026-11-17 11:14:20 UTC
                 RTC time: Tue 2026-11-17 11:14:20
                Time zone: Etc/UTC (UTC, +0000)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: no
active
Reference ID    : B97DBE3A (ntp-x.ubuntu.com)
System time     : 0.000012843 seconds fast of NTP time
Leap status     : Normal
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^* 1.ntp.ubuntu.com              2   8   377    41   -103us[ -120us] +/-   18ms
^+ 2.ntp.ubuntu.com              2   8   377    40   +215us[ +198us] +/-   22ms
…
Name/IP address             Mode KeyID Type KLen Last Atmp  NAK Cook CLen
=========================================================================
1.ntp.ubuntu.com             NTS     1   15  256   41    0    0    8  100

The server name and value are examples. Mode NTS indicates that the source is NTS certified. When the network blocks TCP 4460, the NTS source is unavailable (Reach is 0), and the internal NTP source needs to be configured according to the organization's policy. Use timedatectl timesync-status instead on 24.04.

Case 1: The database backup for half a year is all empty files

Problem: The cron backup script uses pg_dump, which cannot be found in cron's PATH. The output is redirected to /dev/null, and 0-byte files are generated every day. Method: Change to timer + service (failed means failed, alert systemctl --failed); verify the size after backup/do recovery drill; OnFailure= triggers notification.

Case 2: All servers backed up at the same time at 00:00, bringing down the storage

Problem: The cron of 300 machines is 0 0 * * *. Method: timer's RandomizedDelaySec=1h + FixedRandomDelay=yes (each offset is fixed and predictable); storage side speed limit.

Case 3: Clock deviation is 6 minutes, cloud API all 403

Problem: After the virtual machine is restored from the snapshot, the time returns to the snapshot time, and the time synchronization service is accidentally disabled; the cloud SDK request signature is rejected due to the time deviation, and the TLS handshake report certificate is "not yet valid". How to do it: Enable chrony, chronyc makestep correct immediately; check the ready list System clock synchronized: yes; monitor chrony deviation.

Common errors and solutions

The cron task can be run in the terminal, but not in cron / "command not found"

Reason: PATH is different, depending on the environment variable of the login shell, % Not escaped, the /etc/cron.d file lacks user fields or the file name contains dots (files with . in /etc/cron.d under the run-parts rule will be ignored). Fixed: Use absolute paths; set -euo pipefail in the script and redirect the output to the log; check journalctl -u cron.

Failed to start myapp-backup.timer: Unit myapp-backup.timer has a bad unit file setting. / Failed to parse calendar specification

Cause:OnCalendar is written incorrectly (such as copying cron's 30 2 * * *). Fix: Verify with systemd-analyze calendar 'expression' and change it to *-*-* 02:30:00.

Timer is enabled, but the task never runs (NEXT in list-timers is n/a)

Reason: Only .service is enabled instead of .timer; or timer is only enabled without start (--now is missing, you have to wait for the next boot); or not daemon-reload. Fixed:sudo systemctl daemon-reload && sudo systemctl enable --now x.timer.

sh: 1: cannot create /srv/data/backups/redis-….rdb: Read-only file system

Reason: ProtectSystem=strict is not used under ReadWritePaths= to open the write directory. Fix:Add ReadWritePaths=/srv/data/backups.

System clock synchronized: no / chronyc sources All Reach 0

Cause: Outbound UDP 123 or TCP 4460 (NTS-KE) is blocked by the firewall; DNS cannot resolve the time server; the virtual machine clock source is abnormal. Fix:chronyc sources -v, chronyc -N authdata; release port or configure internal NTP server; journalctl -u chrony.

Command line operation questions
1. Verify how "06:00 on the first Monday of every month" should be written, and check the next three trigger times.
systemd-analyze calendar --iterations=3 'Mon *-*-01..07 06:00:00'
2. Without writing any files, let /usr/local/bin/cleanup.sh run once in a transient unit after 10 minutes and view its logs.
sudo systemd-run --on-active=10min --unit=cleanup-once /usr/local/bin/cleanup.sh
systemctl list-timers cleanup-once.timer
journalctl -u cleanup-once.service
Scenario analysis question
A synchronization task that runs every 5 minutes, sometimes running for more than 5 minutes. What happens when using cron and timer? How would you write it?

Cron will start another one regardless of whether it ends last time, resulting in concurrency and mutual coverage - flock -n packaging is required. The timer activates the same service and will not start it repeatedly while it is still running (oneshot of activating). What is more appropriate is OnUnitInactiveSec=5min: run again 5 minutes after each end, so that the interval is stable; then set TimeoutStartSec= for the service to prevent stuck and alert on failure.

Verified teaching video

▶
Automate Your Tasks with systemd Timers: A Step-by-Step Guide — Learn Linux TV
English · writing of timer and service
▶
Linux Crash Course - Scheduling Tasks with Cron — Learn Linux TV
English · crontab syntax
▶
Introduction to systemd timers — tutoriaLinux
English · timer introduction (recorded earlier)

chrony + NTS's topic: No verified high-quality video found, please refer to official documents.

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate videos/MP3s. The following storyboards and explanations can be produced by video tools.

Lens 1 · 0–30s
Screen: Weekly calendar, a green dot at 02:30 every day; Tuesday is gray all day (power off), and the Tuesday dot of cron becomes a hollow red circle.
Narration: cron only checks when it reaches the end, and misses it when it is shut down.
Shot 2 · 30–60s
Screen: In the timer version, at 08:00 on Wednesday, a green dot is added immediately after powering on, marked Persistent. The points for ten servers are spread out from the same moment.
Narration: Persistent allows missed tasks to be rerun after startup; random delays allow a group of machines to stagger execution.
Shot 3 · 60–90s
Screen: A lock between the server clock and the NTS server, the deviation of chronyc tracking approaches zero.
Narration: Scheduled tasks, certificates, and logs all rely on accurate time. Ubuntu 26.04 uses chrony and certified NTS synchronization by default.
Or score ≥ 70% on the Quiz

Module 8 · Production readiness review and common mistakes

50:00 – 60:00 · Turn the first 7 modules into a checklist that can be ticked one by one and a check script that can be run repeatedly, and then confirm it through fault injection: when something goes wrong, you can find the cause within 5 minutes
10 minutesReview + Troubleshooting★★★★★
Learning Objectives
  • Review the server according to seven dimensions (service, log, storage, network, access, time and scheduling, patch and baseline), and tell the "why" and "how to verify" of each item.
  • Write and run a read-only readiness check script that outputs PASS / WARN / FAIL.
  • Practice the most common production problems through fault injection: service failure, disk fullness, name resolution failure, SSH configuration error.
  • Use the interactive troubleshooting tree to locate specific commands and fixes based on the phenomenon.
Prerequisite knowledge:Modules 1–7. Importance:★★★★★

What: "Production ready" means

Production readiness does not mean "the service can be accessed now", but: predictably starts (automatically recovers after restart), observable (has logs and status can be checked), Bounded (disk, memory, permissions, and network exposure have upper limits), accessible and secure (operations and maintenance can come in, but attackers cannot come in), maintainable (time is correct, patches can be applied, and backups can be restored).

Ready list (linuxlab version)

DimensionCheck itemVerification commandModule
Servicemyapp is managed by systemd and starts automatically at bootsystemctl is-enabled myappM1
Run as a non-root usersystemctl show myapp -p UserM1
Crash automatically restarts with back-offsystemctl show myapp -p Restart,RestartStepsM1
Sandbox exposure ≤ 4 (heuristic)systemd-analyze security myappM1
Logjournal persistencejournalctl --list-boots | wc -l > 1M2
journal has a clear upper limitsystemd-analyze cat-config systemd/journald.conf | grep SystemMaxUseM2
All text logs have rotation ruleslogrotate -d /etc/logrotate.confM2
StorageAll file system usage < 80%, inode < 80%df -h, df -iM3
Data is separated from the system, VG has marginvgsM3
fstab uses UUID, non-system volume nofail, verify Throughfindmnt --verifyM4
NetworkOnly expose the required ports; the backend only listens for loopbackss -tlnpM5
DNS resolution is normal and there is an upstreamresolvectl status, getent hostsM5
Firewall is enabled on demand (ufw / Cloud Security Group)ufw statusM5 / Lessons 3 and 4
AccessKey login only, root ban, whitelistsshd -TM6
Minimized sudo permissions, no shared accountgetent group sudoLesson 1
Time and SchedulingClocks synchronizedtimedatectl show -p NTPSynchronizedM7
Backup timer enabled and recently successfulsystemctl list-timers myapp-backup.timerM7
Backup can be restored (rehearsed)Restore to test instanceM7
Patch and baselineNo failed unitssystemctl --failedAll
Automatic security updates enabled; whether to wait for restartsystemctl is-enabled unattended-upgrades, ls /var/run/reboot-requiredLesson 1
Configuring Rebuildable (Ansible/cloud-init)Code RepositoryAnsible Lesson

Why: Why should it be written as a script

  • Manual inspection will miss it. The script is the same every time and can be put into CI or run regularly.
  • The inspection results can be used as review records and comparison before and after the change.
  • The script must be read-only: the review tool itself cannot change the system state.
  • Advanced: Use Ansible to write inspection and repair as idempotent tasks; use node_exporter + Prometheus for continuous monitoring (node_systemd_unit_state, node_filesystem_avail_bytes, node_timex_sync_status).

How: General sequence for troubleshooting

  1. Phenomena: Accurate description (which command, what error is reported, where to access, when to start).
  2. Status: systemctl --failed, systemctl status service, df -h, free -h, ss -tlnp.
  3. Log: journalctl -u service -b, journalctl -p err -b, journalctl -k.
  4. Recent changes: /var/log/apt/history.log, configuration file modification time, last.
  5. Assumption → Minimal Validation → Fix → Confirm → Record.

When: When to review

  • Before going online; after every major change; after restoring from mirroring/snapshots; regularly (quarterly).
  • Any problem that is "discovered only after restarting" should be converted into a checklist item.
Common misunderstandings① "The service is now accessible = ready" - the behavior when restarting, disk full, or dependency failure has not been verified. ② "Systemd-analyze security means it is safe if the score is low" - it is a heuristic score that does not understand the vulnerabilities and data permissions of the application itself. ③ "As long as you have a backup" - a backup that has not been restored is not considered a backup. ④ "The review is a one-time thing" - the configuration will drift and the check must run continuously.

Ready map: system components corresponding to seven dimensions

linuxlabmyapp + redisService · systemdRestart · User · SandboxLog · journald/logrotatePersistence · Cap · RotationStorage · LVM/fstabMargin · UUID · nofailNetwork · ip/ss/resolvedMinimal exposure · DNSAccess · sshdKey · Whitelist · sshd -TTime and Scheduling · chrony/timerSynchronization · Backup · Recovery DrillPatch and Baselineunattended-upgrades · No failed unitsMonitoring and Alarming (Follow-up Course)node_exporter · Prometheus
Figure 8-1 Each dimension has "configuration items + verification commands"; monitoring turns one-time inspection into continuous inspection

Layering of fault location

Application layer: /healthz, application log, dependency (Redis)Service layer: systemctl status, journalctl -u, Restart / StartLimitResource layer: df / df -i, free / OOM (journalctl -k), ulimit / TasksMaxNetwork layer: ss, ip route get, resolvectl, firewallSystem layer: startup (systemctl --failed, emergency), time, kernel
Fig. 8-2 Start with the layer closest to the phenomenon and eliminate it layer by layer

Interaction: Readiness Scorecard

Select according to the actual situation of linuxlab (you can run the inspection script of the "Experiment" page first). Scored by weight, unmet high-weighted items are listed below.

Score: —

Review and troubleshooting "first minute" command

CommandWhat to look at
systemctl is-system-runningrunning / degraded / maintenance
systemctl --failedWhich units failed
journalctl -p err -b --no-pager | tail -n 30Errors in this startup
uptime / free -h / df -h / df -iLoad, memory, disk, inode
journalctl -k -b | grep -iE 'oom|i/o error|ext4-fs error|xfs'OOM and disk errors
sudo ss -tlnpListening port
ip -br a; ip route; resolvectl status | head -20Network fundamentals
timedatectl show -p NTPSynchronized --valueyes / no
sudo sshd -T | grep -E '^(passwordauthentication|permitrootlogin)'SSH strategy
systemctl list-timers --allScheduled tasks
apt list --upgradable 2>/dev/null | wc -l, cat /var/run/reboot-required 2>/dev/nullPatch and pending restart
tail -n 20 /var/log/apt/history.log, last -n 10Recent changes and login

Experiment 8: Readiness check script + four fault injections (about 12 minutes)

Write a read-only readiness check script:
cat > ~/linuxlab/readiness.sh <<'EOF'
#!/usr/bin/env bash
# linuxlab readiness check (read-only). Usage: sudo bash ~/linuxlab/readiness.sh
set -u
pass=0; warn=0; fail=0
ok()   { printf '  \033[32mPASS\033[0m %s\n' "$1"; pass=$((pass+1)); }
wn()   { printf '  \033[33mWARN\033[0m %s\n' "$1"; warn=$((warn+1)); }
bad()  { printf '  \033[31mFAIL\033[0m %s\n' "$1"; fail=$((fail+1)); }
chk()  { if eval "$2" >/dev/null 2>&1; then ok "$1"; else bad "$1"; fi; }

echo "[Service]"
chk "myapp is enabled"                 "systemctl is-enabled --quiet myapp"
chk "myapp is running"                 "systemctl is-active --quiet myapp"
chk "myapp is running as myapp user"      "[ \"\$(systemctl show -p User --value myapp)\" = myapp ]"
chk "myapp Restart=on-failure"      "[ \"\$(systemctl show -p Restart --value myapp)\" = on-failure ]"
chk "/healthz returns 200"             "curl -fsS -m 3 http://127.0.0.1:5000/healthz"
score=$(systemd-analyze security myapp 2>/dev/null | awk '/Overall exposure/{print $(NF-2)}')
if [ -n "$score" ] && awk "BEGIN{exit !($score <= 4.0)}"; then ok "Sandbox exposure $score"Sandbox exposure ${score:-unknown}{score:-unknown}"; fi
echo "[Log]"
chk "journal Persisted"              "[ -d /var/log/journal ] && [ \$(journalctl --list-boots -q | wc -l) -ge 1 ]"
chk "journald Set SystemMaxUse"  "systemd-analyze cat-config systemd/journald.conf | grep -q '^SystemMaxUse='"
chk "logrotate configuration resolvable"          "logrotate -d /etc/logrotate.conf"
echo "[Storage]"
while read -r use target; do
  u=${use%\%}; if [ "$u" -ge 90 ]; then bad "$target usage $use"; elif [ "$u" -ge 80 ]; then wn$target usage $usese"; else $target usage $use$use"; fi
done < <(df --output=pcent,target -x tmpfs -x devtmpfs -x squashfs -x overlay -x efivarfs | tail -n +2)
chk "fstab verification passed"                "findmnt --verify"
chk "Swap space exists"                  "[ -n \"\$(swapon --noheadings)\" ]"
echo "[Network]"
chk "Redis only listens to loopback"              "! ss -tlnH 'sport = :6379' | awk '{print \$4}' | grep -vqE '^(127\\.0\\.0\\.1|\\[::1\\]):'"
chk "DNS resolvable archive.ubuntu.com" "getent hosts archive.ubuntu.com"
echo "[Access]"
chk "SSH prohibits password login"              "sshd -T | grep -qx 'passwordauthentication no'"
chk "SSH prohibits root Login"            "sshd -T | grep -qx 'permitrootlogin no'"
echo "[Time and Scheduling]"
chk "Clock synchronized"                    "[ \"\$(timedatectl show -p NTPSynchronized --value)\" = yes ]"
chk "Backup timer enabled"             "systemctl is-enabled --quiet myapp-backup.timer"
chk "There are backup files in the last 2 days"           "find /srv/data/backups -name 'redis-*.rdb' -mtime -2 | grep -q ."
echo "[Baseline]"
chk "No failed units"                "[ -z \"\$(systemctl --failed --no-legend)\" ]"
if [ -f /var/run/reboot-required ]; then wn "System awaiting reNo reboot required"; else ok "No reboot required"; fi
echo; echo "PASS=$pass WARN=$warn FAIL=$fail"; [ "$fail" -eq 0 ]
EOF
sudo bash ~/linuxlab/readiness.sh
[Service]
PASS myapp enabled
PASS myapp running
PASS myapp running as myapp user
  PASS myapp Restart=on-failure
PASS /healthz Return 200
PASS sandbox exposure 2.4
[Log]
PASS journal persisted
PASS journald has SystemMaxUse set
PASS logrotate configuration can be parsed
[Storage]
PASS / Usage 18%
PASS /boot Usage 12%
PASS /boot/efi usage rate 6%
PASS /srv/data usage rate 3%
PASS /srv/archive usage rate 8%
PASS fstab verification passed
PASS has swap space
[Network]
PASS Redis only listens for loopback
PASS DNS can resolve archive.ubuntu.com
[Access]
PASS SSH prohibits password login
PASS SSH prohibits root login
[Time and Scheduling]
PASS The clock has been synchronized
PASS backup timer has been enabled
PASS has backup files in the last 2 days
[Baseline]
PASS no failed units
PASS no restart required

PASS=25 WARN=0 FAIL=0

If the data volume is not restored after restarting, the /srv/data related items and "no failed units" will FAIL - this is what the check script should find.

Fault 1: The service cannot be started——Simulate "someone moved the venv" once:
sudo mv /opt/myapp/venv /opt/myapp/venv.bak
sudo systemctl restart myapp; sleep 3
systemctl status myapp --no-pager | sed -n '1,6p'
# Repair after diagnosis:
sudo mv /opt/myapp/venv.bak /opt/myapp/venv
sudo systemctl reset-failed myapp; sudo systemctl restart myapp && systemctl is-active myapp
× myapp.service - myapp Flask API (gunicorn)
     Loaded: loaded (/etc/systemd/system/myapp.service; enabled; preset: enabled)
    Drop-In: /etc/systemd/system/myapp.service.d
             └─10-hardening.conf, 20-logging.conf
     Active: failed (Result: exit-code) since …
    Process: 4102 ExecStart=/opt/myapp/venv/bin/gunicorn … (code=exited, status=203/EXEC)
active

Because it is Type=exec, restart itself will report an error (Job failed), and will not "pretend that the startup is successful" like simple.

Fault 2: Disk full:
sudo fallocate -l 3G /srv/data/fill.bin 2>&1 || sudo dd if=/dev/zero of=/srv/data/fill.bin bs=1M status=none
df -h /srv/data | tail -1
sudo systemctl start myapp-backup.service; systemctl show myapp-backup.service -p Result
journalctl -u myapp-backup.service -n 3 --no-pager -o cat
# Fix:
sudo rm /srv/data/fill.bin; sudo systemctl reset-failed myapp-backup.service
fallocate: fallocate failed: No space left on device
/dev/mapper/vgdata-lvdata  2.0G  1.9G     0 100% /srv/data
Result=exit-code
… Error writing to file: No space left on device …
myapp-backup.service: Main process exited, code=exited, status=1/FAILURE

redis-cli error wording varies depending on the version. Correct fixes for production: expansion (module 3's lvextend -r), cleanup strategy, warning at 80% instead of detecting at 100%.

Fault 3: Name resolution failure (only affects DNS, not IP connectivity):
sudo resolvectl dns eth0 192.0.2.53          # Temporarily replace the DNS of the link with a non-existent address (RFC 5737 document address)
sudo resolvectl flush-caches
getent hosts archive.ubuntu.com || echo "Resolution failed"
ping -c1 -W2 91.189.91.81 >/dev/null && echo "IP connectivity is normal"
resolvectl status eth0 | grep -E 'DNS Servers|Current DNS'
# Fix: Let networkd re-apply the DNS issued by DHCP
sudo networkctl reconfigure eth0; sleep 3; getent hosts archive.ubuntu.com
Parsing failed
IP connectivity is normal
Current DNS Server: 192.0.2.53
       DNS Servers: 192.0.2.53
91.189.91.81    archive.ubuntu.com

Replace the interface name according to your machine. Modifications to resolvectl dns are only performed at runtime and are restored after networkd reconfigures the link. Some networks prohibit ICMP. If ping fails, use curl -sI http://91.189.91.81 instead.

Fault 4: SSH configuration misspelling (Keep current session!):
echo 'PasswordAuthentcation no' | sudo tee /etc/ssh/sshd_config.d/20-typo.conf
sudo sshd -t; echo "sshd -t exit=$?"
# If restarted at this time, sshd will not be able to start and all new connections will fail. Fix:
sudo rm /etc/ssh/sshd_config.d/20-typo.conf && sudo sshd -t && echo "syntax ok"
/etc/ssh/sshd_config.d/20-typo.conf: line 1: Bad configuration option: PasswordAuthentcation
/etc/ssh/sshd_config.d/20-typo.conf: terminating, 1 bad configuration options
sshd -t exit=255
syntax ok
Run the check script againConfirm that all are restored to PASS: sudo bash ~/linuxlab/readiness.sh.

Case 1: After routine kernel update, three servers "did not come back"

Problem: unattended-upgrades installed a new kernel, and the maintenance window was restarted uniformly. Three servers were stuck in emergency mode (fstab left the removed data disk, no nofail), and one myapp did not start (the service was not enabled, and it was started manually before). Method: Add "restart verification" to the ready list (systemctl is-enabled, findmnt --verify), and restart the test instance before going online; the cloud host opens the serial console.

Case 2: A "looking healthy" server, backup has failed for 40 days

Problem: Monitoring only looks at CPU, memory and HTTP health checks. Method: Alert systemctl --failed non-null (systemd collector of node_exporter); send notification for backup OnFailure=; readiness script checks "there are backup files in the last N days"; perform quarterly recovery drills.

Case 3: After being handed over to the on-duty team, no one knows where the logs are

Problem: The service writes the logs to /opt/app/logs/, without rotation or documentation. How to do it:Unified agreement: the service log is in journald (journalctl -u service name), the text log is in /var/log/service name/ and configured with logrotate; the runbook states "first minute command".

Interactive troubleshooting tree

Start from the phenomenon you observed, answer questions step by step, and get diagnostic commands and repair suggestions.

A quick overview of the ten most common errors in this lesson

Error reports/phenomenonThe most likely reasonsModule
status=203/EXECExecStart Path/permission/interpreter issuesM1
start-limit-hitRepeated failures within a short period of timeM1
Read-only file system (within service)ProtectSystem=strict Missing ReadWritePathsM1/M7
No space left on deviceSpace or inode Used up; unreleased files have been deletedM2/M3
You are in emergency modefstab hard mount failedM4
Could not resolve hostDNS upstream / resolved / hostsM5
Connection refused / timed outNo one is listening / dropped in the middleM5
Permission denied (publickey)Keys, permissions, AllowUsersM6
Bad configuration optionsshd configuration misspellingM6
System clock synchronized: noNTP/NTS port blockedM7
Command line operation questions
1. One command lists all failed units since this startup and displays the last 5 log lines of each failed unit.
for u in $(systemctl --failed --no-legend --plain | awk '{print $1}'); do echo "== $u"; journalctl -u "$u" -b -n 5 --no-pager; done
2. Find files on the / file system that have been deleted but are still occupied by processes.
sudo lsof -nP +L1 / 2>/dev/null | head
Scenario analysis question
You want to promote the configuration of linuxlab to 50 servers. Which content should be written into the image/cloud-init, which should be left to configuration management, and which should be left to monitoring?

Image/cloud-init (first boot): base software package, user and SSH public key, sshd hardening fragment, journald quota, chrony configuration, time zone. Configuration management (Ansible, consistent, idempotent): myapp.service and drop-in, logrotate rules, fstab and data volumes, backup timer, sysctl. Monitoring (continuous checking): failed units, file system usage, clock synchronization, backup freshness, /healthz. Readiness scripts serve as a verification step after configuration management. For details, see Ansible Course and Prometheus & Grafana Course.

Verified instructional video

▶
First Things To Do On Every New Linux Server — Learn Linux TV
English · Baseline settings before new server goes online
▶
10 Tips for Hardening your Linux Servers — Learn Linux TV
English · Server hardening checklist (recorded earlier)

Official document

Video storyboard script (approx. 90 seconds)

This courseware cannot directly generate video/MP3. The following storyboards and explanation scripts can be produced by video tools.

Lens 1 · 0–30s
Screen: seven-grid list. When each grid lights up, the corresponding command is displayed: systemctl, journalctl, df, ss, sshd -T, timedatectl, systemctl --failed.
Narration: Production readiness is not only accessible, but also predictable behavior when restarting, filling up, disconnecting from the network, and correcting configuration errors.
Shot 2 · 30–65s
Screen: Four faults are injected in sequence: venv disappears, disk 100%, DNS points to an invalid address, sshd spelling error; the first command to locate each fault appears next to it.
Narration: Each type of fault has the fastest locating command. Look at the status first, then the logs, and then verify the hypothesis.
Shot 3 · 65–90s
Screen: Ready script all PASS; arrows pointing to Ansible and Prometheus icons.
Narration: Write the list into a script and hand it over to configuration management and monitoring. The review will change from a one-time inspection to continuous assurance.
Or score ≥ 70% on the Quiz

Command Cheat Sheet

Systemd, log, storage, mount, network, SSH, scheduled tasks and time commands used in this lesson
myapp.service template (M1)
[Unit]
Description=myapp Flask API (gunicorn)
Wants=redis-server.service
After=network.target redis-server.service
StartLimitIntervalSec=60
StartLimitBurst=5

[Service]
Type=exec
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp/app
EnvironmentFile=/etc/myapp/myapp.env
ExecStart=/opt/myapp/venv/bin/gunicorn --chdir /opt/myapp/app --bind ${BIND} --workers ${WORKERS} --access-logfile - app:app
SyslogIdentifier=myapp
Restart=on-failure
RestartSec=2s
RestartSteps=5
RestartMaxDelaySec=30s
StateDirectory=myapp
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
CapabilityBoundingSet=
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
SystemCallFilter=@system-service
MemoryMax=512M

[Install]
WantedBy=multi-user.target
systemctl / systemd-analyze(M1)
systemctl status|start|stop|restart|reload XRuntime operation
systemctl enable --now XAuto + startup
systemctl daemon-reloadAfter changing unit / fstab
systemctl edit X / cat Xdrop-in / view merge results
systemctl show X -p PropAttributes
systemctl list-dependencies X [--reverse]Dependency tree
systemctl --failed / reset-failed XFailed unit
systemd-analyze verify|security|critical-chain|blameInspection and analysis
systemd-run --pty -p Prop=… cmdTransient unit
Log (M2)
journalctl -u X -b -p warning -fUnit / This startup / level / follow
journalctl -b -1 · --list-bootsLast startup
journalctl --since "1 hour ago" -g 'regex'Time + regular
journalctl -k · -o json-pretty · -F FIELDKernel / all fields / field values
journalctl --disk-usage · --vacuum-size=200MOccupy / cleanup
/etc/systemd/journald.conf.d/*.confStorage= · SystemMaxUse= · MaxRetentionSec=
logrotate -d FILE / -f FILEDebug/Force
rsyslogd -N1rsyslog syntax check
Storage and LVM (M3)
lsblk -f · blkid · df -hT · df -iPanorama
losetup -fP --show IMGLoopback device
parted -s DEV mklabel gpt mkpart data 1MiB 100% set 1 lvm onPartition
pvcreate → vgcreate VG PV → lvcreate -n LV -L 1G VGVolume creation
vgextend VG PV → lvextend -r -L +1G VG/LVExpansion
resize2fs DEV · xfs_growfs MOUNTPOINTIndividual file system expansion
growpart DISK N · pvresize PVAfter cloud disk expansion
Mount and swap (M4)
UUID=…  /srv/data  ext4  defaults,nofail,noatime,x-systemd.device-timeout=10s  0  2
nas:/x  /mnt/x     nfs   _netdev,nofail,noauto,x-systemd.automount         0  0
/swapfile  none    swap  sw                                                0  0
findmnt --verify → daemon-reload → mount -aChange fstab three steps
fuser -vm MNTtarget is busy
fallocate -l 1G /swapfile; chmod 600; mkswap; swaponSwap file
/etc/sysctl.d/99-x.conf: vm.swappiness=10sysctl --system
Network (M5)
ip -br a · ip route · ip route get IP · ip neighInterface/Routing/Actual Exit/ARP
ss -tulpn · ss -tnp state establishedListen/Connect
getent ahosts NAMEAnalysis consistent with application
resolvectl status|query|flush-caches|statisticsresolved
netplan get|status|try|apply · networkctlUbuntu
nmcli dev status · nmcli con showRHEL system
nc -vz HOST PORT · tcpdump -ni IF port NPort/packet capture
SSH(M6)
ssh-keygen -t ed25519 -a 100 -f ~/.ssh/KEYGenerate key
~/.ssh/config: Host · HostName · User · IdentityFile · IdentitiesOnly · ProxyJumpClient configuration
/etc/ssh/sshd_config.d/10-*.confThe first value takes effect → small number
sshd -t · sshd -T [-C user=,host=,addr=]Syntax / Valid value
systemctl reload sshAuthentication class settings
daemon-reload + restart ssh.socketPort / ListenAddress(Ubuntu)
ssh -v · ssh-keygen -R HOST · ssh-keygen -lf PUBDebug / delete old host key / fingerprint
Timing tasks and time (M7)
[Timer]
OnCalendar=*-*-* 02:30:00 UTC
RandomizedDelaySec=15min
Persistent=true
[Install]
WantedBy=timers.target
systemd-analyze calendar --iterations=3 'EXPR'Validation expression
systemctl list-timers --allAll timers
systemd-run --on-active=10min CMDOne-time delayed tasks
crontab: hour day month week [user] Command, % → \%cron
timedatectl · chronyc tracking|sources -v · chronyc -N authdataTime synchronization
First minute (M8)
systemctl is-system-running; systemctl --failedOverall status
journalctl -p err -b | tailError
uptime; free -h; df -h; df -iResources
sudo ss -tlnp; ip route; resolvectl statusNetwork
timedatectl show -p NTPSynchronizedTime
sudo bash ~/linuxlab/readiness.shReady script
Ubuntu ↔ RHEL system comparison
ProjectUbuntu 26.04Rocky / Alma 10
SSH Servicessh.service + ssh.socketsshd.service
NetworkNetplan → networkdNetworkManager
DNSsystemd-resolvedNetworkManager writes resolv.conf
Timechrony.servicechronyd.service
Default file systemext4xfs
croncron.servicecrond.service(cronie)
syslog file/var/log/syslog, auth.log (rsyslog required)/var/log/messages, secure

Comprehensive experiment + final exam

Independently deliver the second service myapp-worker to a production-ready state and pass the verification of a real restart
About 40 minutesLocal · No cost

Scenario

The team wants to add a background process myapp-worker on linuxlab: reuse myapp's code and virtual environment (/opt/myapp/app, /opt/myapp/venv), write a heartbeat to Redis every 10 seconds (the minimum implementation is given below), require independent logs, a reinforced sandbox, its own data directory, and run automatically on boot. Requirements not to impact myapp and prove it "handover ready" with a ready script and a reboot.

Preparing the program(root-owned, myapp read-only):
sudo tee /opt/myapp/app/worker.py >/dev/null <<'EOF'
import os, time, socket, redis
r = redis.Redis(host=os.environ.get("REDIS_HOST", "127.0.0.1"), port=6379)
state = os.environ.get("STATE_DIRECTORY", "/tmp")
while True:
    try:
        r.set("worker:heartbeat", int(time.time()))
        print(f"heartbeat ok from {socket.gethostname()}", flush=True)
    except Exception as e:
        print(f"redis error: {e}", flush=True)
    with open(os.path.join(state, "last"), "w") as f:
        f.write(str(int(time.time())))
    time.sleep(10)
EOF
sudo chown root:myapp /opt/myapp/app/worker.py && sudo chmod 0640 /opt/myapp/app/worker.py
sudo -u myapp /opt/myapp/venv/bin/python -c 'import redis; print(redis.__version__)'

The last command confirms that the redis client library is in the venv (lesson 1's requirements.txt already contains redis==5.*).

Write myapp-worker.service: Requirements Type=exec, User=myapp, WorkingDirectory=/opt/myapp/app, ExecStart=/opt/myapp/venv/bin/python /opt/myapp/app/worker.py, EnvironmentFile=/etc/myapp/myapp.env (reuse the REDIS_HOST), StateDirectory=myapp-worker, Restart=on-failure + exponential backoff, Wants=/After=redis-server.service, SyslogIdentifier=myapp-worker, and with myapp Same sandbox; it doesn't require a listening port, so can be tightened further RestrictAddressFamilies=AF_INET AF_UNIX. systemd-analyze verify After passing enable --now, systemd-analyze security ≤ 3.0.
log: journalctl -u myapp-worker -f see heartbeat; deliberately systemctl stop redis-server 30 seconds, confirm worker logs redis error butNo Exit (Wants semantics + in-app retry), the heartbeat continues after restoring Redis
Storage: Create another 256 MiB ext4 in the volume group vgdata. Volume lvworker, use UUID + nofail,x-systemd.device-timeout=10s to mount to /srv/worker; change the worker's status directory to the volume (tip: ReadWritePaths=/srv/worker + RequiresMountsFor=/srv/worker + environment variable STATE_DIRECTORY=/srv/worker, and chown myapp:myapp /srv/worker).
Scheduled task: write myapp-worker-report.timer, run the oneshot service at the 5th minute of every hour, and use redis-cli get worker:heartbeat to output the latest heartbeat time. journal; use systemd-analyze calendar to verify the expression;Persistent=true.
Network and Access: Confirm that there is no new listening port in ss -tlnp ; confirm that sshd -T is still a key-only login.
Restart verification: Execute sudo systemctl reboot. After returning, press module 4 to restore the loopback data volume (or enable linuxlab-loops.service), confirm that myapp, myapp-worker, and both timers are in the expected state, and run sudo bash ~/linuxlab/readiness.sh all PASS (you can add worker check items to the script first).
Cleaning (subsequent courses still require myapp and myapp.service; only clean up the experimental resources of this lesson):
sudo systemctl disable --now myapp-worker.service myapp-worker-report.timer 2>/dev/null
sudo rm -f /etc/systemd/system/myapp-worker*.service /etc/systemd/system/myapp-worker*.timer /opt/myapp/app/worker.py
# If you need to completely remove the LVM experiment (the backup in /srv/data will be deleted):
#   sudo systemctl disable --now myapp-backup.timer
#   sudo umount /srv/worker /srv/data /srv/archive
#   Edit /etc/fstab and delete the three-line data volume entry of linuxlab part2 (you can also keep /swapfile)
#   sudo vgremove -y vgdata && sudo pvremove /dev/loopXp1 /dev/loopY
#   sudo losetup -D && sudo rm -rf /var/lib/linuxlab-disks
#   sudo systemctl disable linuxlab-loops.service; sudo rm -f /etc/systemd/system/linuxlab-loops.service
sudo systemctl daemon-reload
# You can also go back to the pre-class snapshot directly: multipass stop linuxlab && multipass restore linuxlab.before-part2

Retain myapp.service (and its drop-in), SSH reinforcement and journald configuration, Chapters 3 and 4 The class will move the same deployment to the cloud.

Acceptance Checklist

Open self-test (6 questions)

1. Why is it a bug that Requires=redis-server.service does not write After=?

Requirements and order are independent of each other: without After, the two are started in parallel in the same transaction, and myapp may initialize the connection before Redis listens; when Redis fails to start, myapp that has been started will not fail. It is officially recommended that demand dependencies should always be used in conjunction with sorting dependencies.

2. How long will the logs of a service be retained in journald? Determined by what?

Determined by the capacity and time limit of journald: the oldest archive is deleted when SystemMaxUse=/SystemKeepFree= (default 10%/15%, upper limit 4G) is reached; if MaxRetentionSec= is set, it is deleted based on time; when Storage is volatile, it will be lost upon restart. Rate limiting also discards excess logs on writes.

3. What commands are needed to expand the ext4 data volume from 10G to 20G online? How is xfs different?

When VG has surplus, lvextend -r -L 20G VG/LV can be completed in one step (or lvextend followed by resize2fs); if VG is not enough, add disk first pvcreate + vgextend, or growpart + pvresize after expanding the cloud disk. xfs can also grow online (xfs_growfs mount point), but cannot shrink.

4. Explain how nofail and RequiresMountsFor= work together.

nofail allows mounting failure to not block booting (local-fs.target only wants it); RequiresMountsFor= allows services that rely on this path to generate Requires+After for the mounting unit. The service will not start when the mounting is not available, and avoid writing to empty directories on the root file system. The former protects "the machine can be started", and the latter protects "the data is written to the right place".

5. A user reports that "curl your service times out." How can you tell within two minutes whether the problem is local or network?

Local machine: ss -tlnp Confirm the listening address; curl 127.0.0.1:port local test; systemctl status. Network: tcpdump -ni network card tcp port port Check whether the SYN arrives - if it does not arrive, it means the upstream firewall/security group/routing; if it does not respond, it means the local firewall; if it returns RST, it means a listening problem (refused).

6. Why should the fragment file be named 10- instead of 99- when hardening SSH? How to prove that the configuration actually takes effect?

sshd takes the first obtained value for most keywords. Include is located at the beginning of the main file and reads fragments in file name order, so the settings with the same name in 50-cloud-init.conf take effect before 99-. Use sudo sshd -T (-C to simulate the connection if necessary) to see the final value, and actually verify the password in the new terminal. Login is rejected.

Source and Imprint

Basis for verification of technical facts in this lesson (Verification date: 2026-11-17)
TopicVerification conclusionSource (Access date: 2026-11-17)
Ubuntu 26.04 LTS componentssystemd 259 (259.5), systemd 258 no longer supports cgroup v1, 26.04 is the last version to support SysV service script compatibility (systemd 260 has been removed); Linux 7.0; OpenSSH 10.2; chrony 4.8; sudo-rs enables password echo by default; rust-coreutils has known ACL inheritance issues; Apache defaults to MemoryDenyWriteExecute=yesUbuntu 26.04 LTS release notes · Changes since 25.10
Ubuntu 25.10 changeschrony replaces systemd-timesyncd as the default. NTS; upgrade system migration command apt-mark auto systemd-timesyncd && apt install chrony; sudo-rs and rust-coreutils become default; OpenSSH 10.0; systemd 257.9; Server still uses initramfs-toolsUbuntu 25.10 release notes
Dependency and orderingWants/Requires/Requisite/BindsTo/PartOf semantics; requirement dependencies do not imply order; Wants+After is recommended; implicit dependencies of DefaultDependenciessystemd.unit(5) · bootup(7) · systemd.special(7)
Service type and restartRestart= value (default no), on-failure Trigger conditions (non-zero exit, exception signal, timeout, watchdog, OOM); RestartSec default 100ms; RestartSteps/RestartMaxDelaySec (default 0 / infinity); RestartMode; "Startup completed" moment of Type=simple/exec/forking/oneshot/dbus/notify/notify-reload/idlesystemd.service(5)
Sandbox optionsProtectSystem=strict/full, ProtectHome, PrivateTmp, PrivateDevices, NoNewPrivileges, CapabilityBoundingSet, RestrictAddressFamilies, SystemCallFilter=@system-service, StateDirectory, ReadWritePathssystemd.exec(5) · systemd-analyze(1)
systemctl options--kill-whom=; edit --stdin(systemd 256+); --drop-in=systemctl(1)
journaldStorage= value, the current upstream default is persistent (determined at compile time); SystemMaxUse defaults to 10%, KeepFree 15% (upper limit 4G); MaxRetentionSec defaults to 0; rate limit defaults to 30 seconds 10,000 entries; by default only wall is forwardedjournald.conf(5) (page version systemd 262~devel)
rsyslog Whether it is pre-installedNo official Ubuntu statement; multiple community information shows that some installation methods of the new version are no longer pre-installed, and the lesson is changed to "check with dpkg -l, install if missing"rsyslog installation documentation
logrotatecreate / copytruncate / su / postrotate / maxsize semanticslogrotate(8)
LVM and file systemlvextend -r (--resizefs); Requires), x-systemd.device-timeout, automount, _netdev, generatorlvextend(8) · xfs_growfs(8)
fstab and mount unitnofail (Wants instead of Requires), x-systemd.device-timeout, automount, _netdev, generatorsystemd.mount(5) · systemd-fstab-generator(8) · fstab(5)
Network and DNSresolved stub 127.0.0.53 and proxy stub 127.0.0.54, ReadEtcHosts; iproute2 usage; Netplan trysystemd-resolved(8) · ip-route(8) · Netplan
SSHsshd_config.d fragment, Ubuntu default Include at the beginning, the first value takes effect, sshd -t after systemctl restart ssh.service; Ubuntu socket activation requires daemon-reload + restart ssh.socketUbuntu Server: OpenSSH server · LP #2069041 · sshd_config(5)
OpenSSH 10.x10.0 defaults to mlkem768x25519-sha256 and removes DSA; 9.8 introduces sshd-session and PerSourcePenaltiesOpenSSH Release Notes
timer and cronOnCalendar, Persistent, RandomizedDelaySec, FixedRandomDelay, AccuracySec default 1min; the meaning of % in crontabsystemd.timer(5) · systemd.time(7) · crontab(5)

Video verification instructions

All 23 videos in the "Video" page of each module of this lesson (Learn Linux TV, tutoriaLinux, DevConf, Better Stack, Slap Ya Administrator, KeepItTechie) has verified the title and channel through the YouTube oEmbed interface on 2026-11-17. The title and link can be found in each video card. I only verified the title and channel, but did not review the content one by one; some details in the earlier recorded video (such as Ubuntu's ssh.socket, chrony default) are subject to this lesson. No verified special videos were found for the three topics: journald and rsyslog collaboration, fstab generator and emergency mode, and chrony + NTS. Storyboards have been provided.

Voice explanation instructions

"Voice" page uses the browser Web Speech API (en-US) to read the explanation script. English terms are pronounced in en-US. The effect depends on the system voice package. MP3 is not embedded. If offline audio is required, the transcript can be generated by the TTS service.

Known limitations

  • The experimental command is not actually executed in the courseware generation environment; the PID, UID, IP address, interface name, loop number, UUID, time, version patch number, systemd-analyze security score in "Expected Output" are all examples, and the wording is subject to your system version.
  • This lesson is written according to the final layout of the comprehensive experiment in Lesson 1: myapp user (home directory /opt/myapp), code /opt/myapp/app/, virtual environment /opt/myapp/venv, startup script /opt/myapp/run.sh, /etc/myapp/myapp.env (root:myapp 0640), port 5000, redis-server. ExecStart directly references ${BIND} and ${WORKERS}. These two variables must be retained when modifying the env file.
  • As of the verification date, Multipass does not have a command to add a second disk to an existing instance (no official support has been found), so a loopback device is used; the loopback device needs to be rebuilt after restarting, and the advanced linuxlab-loops.service has not been verified by actual restart.
  • There is no official statement whether rsyslog is installed by default in Ubuntu 26.04 Server. Install it as needed after checking in class; /usr/lib/rsyslog/rsyslog-rotate is a script provided by the Debian/Ubuntu rsyslog package. If it is missing, use systemctl kill -s HUP rsyslog instead.
  • The Storage= of journald in the current upstream document defaults to persistent (the old version is auto). The actual compilation default value packaged by Ubuntu 26.04 has not been independently verified; because Ubuntu pre-built /var/log/journal, the two default behaviors are consistent and are still explicitly set in the lesson.
  • The sandbox option may conflict with specific Python extensions (especially SystemCallFilter and MemoryDenyWriteExecute). This lesson conservatively does not enable MemoryDenyWriteExecute and provides an item-by-item troubleshooting method. Type=exec is a conservative choice (does not rely on gunicorn's sd_notify behavior).
  • Chrony's NTS server name, chronyc output format, and whether cron is pre-installed are subject to the actual system.
  • The animation simplifies the real mechanism: the startup animation omits initrd and a large number of parallel units; the packet animation omits qdisc, GRO/GSO, policy routing and IPv6; the SSH animation omits algorithm negotiation details.