Linux Hour 2: System Management and Production Readiness
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- Read and write systemd units: distinguish between sort (
After=/Before=) and requirements (Wants=/Requires=/BindsTo=), understandmulti-user.targetstartup transaction, restart strategy and startup frequency limit; write and strengthenmyapp.servicefor myapp (User=myapp,EnvironmentFile=,Restart=on-failure,ProtectSystem=strict,NoNewPrivileges=yes, etc.), usesystemd-analyze securityquantification. - Use
journalctlto accurately check logs, configure journald persistence and capacity limit; understand the relationship between rsyslog and journald; write the correct logrotate rules (createvscopytruncate,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/fstabto prevent the server from being stuck in emergency mode: UUID,nofail,x-systemd.device-timeout=,x-systemd.automount,_netdev, and swap files andswappiness. - Use
ip,ss,resolvectlto 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
| # | Time | Module | Core content | Animation/Interaction | Experiment (linuxlab · ~/linuxlab) |
|---|---|---|---|---|---|
| 0 | Before class | Connection and warm-up | Start 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 image | Environment self-check list | Self-check script |
| 1 | 00–06 | systemd: unit, service and dependency | Unit type and search path, drop-in, startup transaction and target, After/Wants/Requires/BindsTo, Type=, Restart= and StartLimit, sandbox | Core animation: startup dependency graph + Failure and restart strategy | Write and strengthen myapp.service, systemd-analyze security scoring |
| 2 | 06–13 | Log: journald, rsyslog and log rotation | journald Fields and queries, persistence and capacity, rate limits, rsyslog forwarding, logrotate rules and triggers | Log flow animation (stdout → journald → rsyslog → file → logrotate) | journald quota + myapp text log + logrotate walkthrough |
| 3 | 13–21 | Storage: disk, partition, LVM and file system | Block device, GPT partition, PV/VG/LV, PE, ext4 vs xfs, online expansion, snapshot, df vs du | LVM layer builder (add disk → expand VG → Expand LV → Expand file system) | Build vgdata and expand lvdata on the loopback device |
| 4 | 21–28 | Mount, fstab and swap space | mount and systemd .mount unit, fstab Six columns, UUID, nofail, x-systemd.*, _netdev, swap file, swappiness | Start the mount simulator: will it enter emergency mode when the disk is missing | Persistent mounting /srv/data, 1 GiB swap file |
| 5 | 28–35 | Network: ip, ss, routing and DNS resolution | Interfaces and addresses, route tables and ip route get, neighbor tables, socket status, systemd-resolved stubs, Netplan / networkd vs NetworkManager | Core Animation: A packet's journey (socket → route → Network card + DNS) | Tracking myapp → redis and apt → Internet connection |
| 6 | 35–42 | SSH: keys, configuration and reinforcement | Key types and agent, ~/.ssh/config, known_hosts, sshd_config.d fragment and "first value takes effect", ssh.socket, sshd -T | SSH connection and authentication process + configuration validity determiner | Ed25519 keys, hardened fragments, secure verification |
| 7 | 42–50 | Scheduled tasks: cron and systemd timer, time synchronization | crontab syntax and environment, timer unit, OnCalendar, Persistent, random delay, chrony and NTS, timedatectl | Missed tasks during shutdown: cron vs Persistent timer timeline | myapp data backup timer + chrony check |
| 8 | 50–60 | Production readiness review and common mistakes | Readiness list (service, log, storage, network, access, time, patch), common errors, interactive troubleshooting tree | Readiness scorecard + troubleshooting tree | Fault injection and repair |
| — | After class | Cheat sheet · Comprehensive lab | Independently deliver the second service myapp-worker to a production-ready state | Final test (12 questions) | Comprehensive experiment |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands/configuration | Experiment |
|---|---|---|---|---|---|---|---|---|---|---|
| systemd Units and dependencies | ✓ | ✓ | · | ✓ | · | ✓ | ✓ | ✓ | systemctl, systemd-analyze, After=/Wants= | myapp.service |
| Service reinforcement | ✓ | · | · | · | · | ✓ | · | ✓ | ProtectSystem=strict, NoNewPrivileges=, systemd-analyze security | M1 scoring |
| Log query and retention | ✓ | ✓ | · | · | · | ✓ | ✓ | ✓ | journalctl -u -p -b --since, logrotate -d | M2 |
| Disk, partition, LVM | · | · | ✓ | ✓ | · | · | · | ✓ | lsblk, parted, pvcreate/vgextend/lvextend -r | Loopback equipment LVM |
| Mount and fstab, swap | ✓ | · | ✓ | ✓ | · | · | · | ✓ | findmnt --verify, nofail, swapon | /srv/data + /swapfile |
| Network and DNS troubleshooting | · | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ip route get, ss -tlnp, resolvectl query | M5 tracking |
| SSH access and reinforcement | · | ✓ | · | · | ✓ | ✓ | · | ✓ | ssh-keygen -t ed25519, sshd -T, sshd_config.d | M6 reinforcement |
| Scheduled tasks and time | ✓ | ✓ | · | · | · | · | ✓ | ✓ | OnCalendar=, systemctl list-timers, chronyc tracking | Backup timer |
| Production readiness review and troubleshooting | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | systemctl --failed, df -h, troubleshooting tree | M8 fault injection |
What is not covered in this lesson (and where to learn it)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
| Shell, files and permissions, users and groups, processes and signals, apt software packages, manual running of myapp | Lesson 1 has been taught | Lesson 1 |
| Linux on the cloud: cloud-init, metadata service, cloud disk and hosting identity, cloud logs and patches | Belongs to "Towards a cloud platform" | Lesson 3 (Azure), Lesson 4 (AWS) |
| Firewall (nftables/ufw/firewalld) in-depth, SELinux/AppArmor, auditing, patch automation | Belongs to security and automated operation and maintenance | No. 5 Subsequent courses from the course |
| Performance analysis (CPU/memory/IO/network), kernel parameter tuning, in-depth troubleshooting | You need to master the system components of this course first | Lesson 7 · Lesson 9 (Questions and Interviews) |
| Application of namespaces / cgroups in containers | Docker lesson explained from the container perspective | Docker 8 hours |
| Complete the configuration of this lesson in batches with Ansible | Configuration management tool | Ansible 8 hours |
| Indicator monitoring and alarm (node_exporter, Grafana) | Monitoring system | Prometheus & Grafana 8 hours |
How to use this courseware
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.
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).
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.
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)
- Local VM
linuxlab: Ubuntu Server 26.04 LTS, 2 vCPU / 4 GiB / 20 GiB (created withmultipass launch --name linuxlab --cpus 2 --memory 4G --disk 20Gin Lesson 1); administratorlabadmin(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/(inapp.pyapp,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 createsmyapp.servicefor it. - Redis comes from the distribution package
redis-server, the service name isredis-server.service, and the listener is127.0.0.1:6379.
/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% /
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.
Module 1 · systemd: units, services and dependencies
- 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, andenableturnsWantedBy=into a symbolic link. - Write out for myapp Use Sandbox hardening such as
ProtectSystem=strict,NoNewPrivileges=yes,PrivateTmp=yes, etc., and verified withsystemd-analyze security.
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:
| Type | Object described | Example of this lesson |
|---|---|---|
.service | One or a group of processes | myapp.service, redis-server.service, ssh.service |
.target | Synchronization point/unit grouping (equivalent to the modern version of "run level") | multi-user.target, network-online.target |
.socket | Listen to the socket and start the service when the connection comes (socket activation) | ssh.socket (module 6) |
.mount / .automount / .swap | Mount point/mount on demand/swap space, usually automatically generated by /etc/fstab | srv-data.mount (module 4) |
.timer | Activate another unit regularly | myapp-backup.timer (Module 7) |
.path | Activate unit when file/directory changes | — |
.slice / .scope | cgroup resource group/externally created process group | system.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 stopcan 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.
| Command | Dimension | Meaning | When the dependent unit fails to start | When the dependent unit is stopped later |
|---|---|---|---|---|
Wants= | Demand (weak) | When you start me, start it by the way | I start it as usual | Doesn’t affect me |
Requires= | Demand (strong) | It must be started when I start it | Only 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= | Requirements | It must be already running, not starting it | I failed immediately | Same as Requires |
BindsTo= | Requirements (strongest) | Same as Requires, and it enters inactive in any way (including crashing itself, the device disappears) I will also stop | Same as Requires | I will definitely be stopped |
PartOf= | One-way propagation | Only propagates stop/restart, not pulling it up | — | When I stop/restart it, I also stop/restart |
After= / Before= | Sort | Bothare 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
- Firmware → GRUB → Kernel + initramfs → Switch to the real root file system → Execute
/sbin/init(i.e. systemd, PID 1). - systemd runs generators (generators): For example,
systemd-fstab-generatortranslates each line of/etc/fstabinto.mount/.swapunits (sodaemon-reloadis required after changing fstab, module 4). - Load all units, starting from
default.target(linked tomulti-user.targeton the server) alongWants=/Requires=to recursively collect the units to be started to form a transaction (transaction), check for conflicts and sorting loops. - 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. - 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 completed | Applicable |
|---|---|---|
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 |
exec | After 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-reload | The process sends READY=1 | True "ready" is considered startup (requires program support) |
forking | The parent process exits | Traditional daemon process, officially discouraged |
oneshot | The main process exits | One-time tasks (backup scripts, initialization), often combined with timer |
How ④: Failure, restart and startup frequency limit
Restart=: Defaultno, optionalon-success,on-failure,on-abnormal,on-watchdog,on-abort,always.on-failureRestarts 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 bysystemctl stopnever triggers a restart.RestartSec=: Waiting time before restarting, default 100ms. Systemd ≥ 254'sRestartSteps=andRestartMaxDelaySec=let the interval increase exponentially from RestartSec to the upper limit to avoid crazy restarts.- Start frequency limit (
[Unit]section): After more thanStartLimitBurst=starts withinStartLimitIntervalSec=, the unit enters failed (start-limit-hit) and no longer automatically restarts (default from system.conf, usually 5 times in 10 seconds). After repairing, usesystemctl reset-failed myappto 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
| Options | Effect | Is myapp applicable |
|---|---|---|
User=myapp / Group=myapp | Run as an unprivileged user | ✓ Required |
NoNewPrivileges=yes | Processes and child processes cannot obtain new permissions through setuid and file capabilities (kernel no_new_privs flag) | ✓ |
ProtectSystem=strict | The 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=yes | Independent /tmp and /var/tmp | ✓ (gunicorn's worker heartbeat file is written in the temporary directory) |
PrivateDevices=yes | Private /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_UNIX | Only allow these socket types | ✓ |
SystemCallFilter=@system-service | Only allow the set of system calls required by general services | ✓ (the process is terminated by SIGSYS when violated) |
MemoryDenyWriteExecute=yes | Prohibit 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
.serviceand 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 service | SysV init script | supervisord | Container (Docker restart policy) | |
|---|---|---|---|---|
| Dependencies and order | Declarative, transactional computing, parallel | Script number sequential execution | priority number | compose depends_on |
| Process tracking | cgroup, child process will not escape | PID file | Child process | Container cgroup |
| Sandbox | Dozens of options in unit files | None | None | namespaces + seccomp are enabled by default |
| Status | Ubuntu/RHEL Default | Ubuntu 26.04 is the last LTS to retain a compatibility layer | Third Party | See Docker course |
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
State machine and restart strategy of a single service
Unit file anatomy: myapp.service
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
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
| Command | Function | Description |
|---|---|---|
systemctl status myapp | Status, main PID, cgroup process tree, last 10 Line log | First debugging command |
systemctl start|stop|restart|reload myapp | Runtime operation | reload requires unit definition ExecReload= |
systemctl enable --now myapp | Autostart and start immediately after booting | enable only creates symbolic links, --now and start |
systemctl daemon-reload | Reload all unit files and re-run the generator | Must be executed after modifying unit files or fstab |
systemctl cat myapp | Display unit files and all drop-in | Look at the source of "final effect" |
systemctl show myapp -p Restart,User,NRestarts,Result | Query the parsed attributes | NRestarts = number of automatic restarts |
sudo systemctl edit myapp | Create/edit drop-in /etc/systemd/system/myapp.service.d/override.conf | Automatically daemon-reload after saving; --full Edit the entire copy |
systemctl list-dependencies myapp / --reverse | Dependency tree/reverse dependency | Who pulls it up, who it pulls up |
systemctl --failed | List failed units | Readiness review first item |
sudo systemctl reset-failed myapp | Clear failed status and start count | hit start-limit Then use |
systemctl get-default | Default target | The server is multi-user.target |
systemd-analyze verify /etc/systemd/system/myapp.service | Static check unit file | Spelling errors, unknown instructions, paths do not exist |
systemd-analyze security myapp | Sandbox exposure score (0 safe – 10 unsafe) | It is a heuristic score, not a vulnerability scan |
systemd-analyze critical-chain myapp.service | Time-consuming to start the critical path | "@" is the start time, "+" is the time spent on this unit |
systemd-analyze blame / plot > boot.svg | Startup time-consuming ranking/timeline chart | The blame numbers cannot be added directly when starting in parallel |
systemd-run --pty -p ProtectSystem=strict bash | Run commands in transient units and apply attributes | Quickly 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)
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.
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 😨
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).
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.
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.
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.
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.
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
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
Official Document
- systemd.unit(5) (dependency and ordering)
- systemd.service(5)(Type=, Restart=)
- systemd.exec(5) (sandbox option)
- bootup(7) (startup flow chart)
- systemd.special(7) (special target)
- systemd-analyze(1)
Video storyboard script (about 100 seconds)
This courseware cannot directly generate video/MP3. The following storyboards and explanations can be produced by video tools.
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.
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.
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.
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.
Module 2 · Log: journald, rsyslog and log rotation
- 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
journalctlfiltering:-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).
What: Three-layer logs on Linux
| Components | What to do | Storage | Ubuntu 26.04 status |
|---|---|---|---|
| systemd-journald | Collect almost all logs, plus metadata fields, indexed | Binary log files: persistence in /var/log/journal/, volatile in /run/log/journal/ | Run by default, sysinit phase starts |
| rsyslog | Traditional 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 files | Use 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 |
| logrotate | Cut text logs by time/size, compress, retain N copies, execute postrotate | Configuration /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]) | Meaning | Default 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)/ none | Current 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 reserved | 10% / 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 time | 0 (not delete by time) |
RateLimitIntervalSec= / RateLimitBurst= | Rate limits per service | 10,000 messages in 30 seconds; excess ones are discarded and "Suppressed N messages" are logged |
ForwardToSyslog= | Forward messages to syslog socket | Upstream 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
| Method | Process | Premise | Risk |
|---|---|---|---|
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 postrotate | The 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 |
copytruncate | Copy app.log to app.log.1, and then truncate the original file to 0 | The application does not support reopening and is opened with O_APPEND | Logs 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.logaccording 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
| journald | rsyslog | Cloud Logging Agent (Lesson 3/4) | |
|---|---|---|---|
| Format | Binary, structured fields, index | Text lines / Template | Structured, sent to cloud |
| Query | journalctl, by field | grep / awk | KQL(Azure)/ Logs Insights(AWS) |
| Remote forwarding | systemd-journal-upload (less used) | Mature: TCP, RELP, TLS, queue | Native |
| Reserved | By size / Time automatically | Depends on logrotate | By workspace/log group policy |
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
logrotate's create and copytruncate
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.
journalctl / journald / rsyslog / logrotate common commands
| Command | Function | Description |
|---|---|---|
journalctl -u myapp -f | Follow the log of a certain unit | Can write multiple -u |
journalctl -u myapp -b -p warning | This startup, warning and more serious | -p err..alert Specified range |
journalctl -b -1 -e | The last startup log, jump to the end | Troubleshoot "Why restarted"; persistence required |
journalctl --list-boots | List saved startup records | Only 1 description is not persisted |
journalctl --since "10 min ago" --until now | Time slice | You 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=gunicorn | Match by field | Multiple values in the same field are OR, different fields are AND |
journalctl -k | Kernel log (equivalent to dmesg) | OOM killer, disk error |
journalctl -u myapp -o json-pretty -n 1 | Show all fields | -o cat Only display messages |
journalctl -F _SYSTEMD_UNIT | List all values of a field | Which units have written logs |
journalctl --disk-usage | Journal occupation | — |
sudo journalctl --vacuum-size=200M / --vacuum-time=2weeks | Clean the archive files at one time | Only delete archived (inactive) files |
sudo journalctl --verify | Check log file integrity | — |
systemd-cat -t myjob echo hi | Write command output to journal | Use in script; logger -t myjob hi Use syslog interface |
systemd-analyze cat-config systemd/journald.conf | journald final configuration (including drop-in) | — |
sudo logrotate -d /etc/logrotate.d/myapp | Debug run (without any modification) | First -d and then -f |
sudo logrotate -f /etc/logrotate.d/myapp | Force rotation once | Verification postrotate |
systemctl list-timers logrotate.timer | Logrotate next run time | Status file /var/lib/logrotate/status |
rsyslogd -N1 | Check rsyslog configuration syntax | Modify 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)
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.
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
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" …
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).
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.
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/ 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/ 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.
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
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
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.
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.
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.
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.
Module 3 · Storage: Disks, Partitions, LVM and File Systems
- Use
lsblk,blkid,dfUnderstand the storage layout and distinguish between block devices, partitions, device-mapper and file systems. - Know the difference between GPT and MBR, use
partedto 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 -rexpands two layers at a time.
/dev. Importance:★★★★★ ("The disk is full and needs to be expanded" is the most common work order for operation and maintenance)What: Storage tiers
| Layer | What is it | linuxlab Examples on | View commands |
|---|---|---|---|
| Block devices | Devices exposed by the kernel and read and written randomly by blocks: virtual disks, cloud disks, NVMe, loopback devices | /dev/sda, /dev/loop10 | lsblk |
| Partition table/partition | Cut 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/loop10p1 | parted -l, fdisk -l |
| LVM physical volume PV | Partition or entire disk managed by LVM, the header is written to LVM Metadata | /dev/loop10p1 | pvs |
| Volume Group VG | A storage pool composed of one or more PVs, split by PE (default 4 MiB) | vgdata | vgs |
| Logical volume LV | Allocate 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 system | Organize files, directories, inodes, journals (journal) on block devices | ext4, xfs | blkid, df -hT |
| Mount points | Connect the file system to the directory tree (module 4) | /srv/data | findmnt |
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:
pvmoveMove 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
- 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.
- Partition and PV: When the PV is on the partition, first expand the partition (
growpart /dev/sda 3) and thenpvresize; the new disk ispvcreate+vgextend. - LV:
lvextend -L +10Gor-l +100%FREE. - File system: ext4 uses
resize2fs device, xfs usesxfs_growfs mount point; or add-r(--resizefs) in step 3 to complete it together with lvextend.
ext4 vs xfs
| ext4 | xfs | |
|---|---|---|
| Defaults to | Ubuntu, Debian | RHEL / 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 |
| inode | Fixed number during formatting ("space available, inode exhausted" may occur) | Dynamic allocation |
| Good at | General purpose, small files, mature tools | Large files, parallelism I/O, very large file system |
| Minimum size | Very small | The new version of xfsprogs requires about 300 MB or more |
| Check for repairs | e2fsck (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.
-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
device-mapper: How LV becomes a block device
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.
Storage and LVM commands
| Command | Function | Description |
|---|---|---|
lsblk -f / lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTS | Block device tree + file system | The most commonly used "panorama" |
sudo blkid | UUID, LABEL, TYPE | Write fstab using |
df -hT / df -i | File system space / inode usage | "No space left" may also be inode full |
sudo du -xhd1 /var | sort -h | Find large directories (not across file systems) | -x is very important |
sudo losetup -fP --show files / losetup -a / losetup -d | Create/list/delete loopback devices | -P Scan partitions |
sudo parted -s DEV mklabel gpt mkpart data 1MiB 100% set 1 lvm on | GPT + one LVM partition | 1MiB starting guaranteed alignment |
sudo growpart /dev/sda 1 | Expand the partition to the end of the disk | cloud-guest-utils package; use after cloud disk expansion |
pvcreate / pvs / pvdisplay / pvresize / pvmove | Physical volume | — |
vgcreate / vgextend / vgreduce / vgs | Volume group | VFree List to see remaining |
lvcreate -n NAME -L 1G VG / -l 100%FREE | Create logical volume | -L absolute size, -l by PE or percentage |
lvextend -r -L +1G VG/LV | Expand LV and expand file system at the same time | -r = --resizefs |
lvcreate -s -n snap -L 200M VG/LV | CoW snapshot | Invalid when the snapshot space is full |
mkfs.ext4 -L LABEL DEV / mkfs.xfs -L LABEL DEV | Create a file system | The xfs label can be up to 12 characters |
resize2fs DEV / xfs_growfs MOUNTPOINT | Expand the file system | Note that one parameter is the device and the other is the mount point |
sudo dmsetup ls / dmsetup table | device-mapper mapping | LV's bottom layer |
wipefs -a DEV | Clear 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)
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
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
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%.
sudo fallocate -l 800M /srv/data/blob.bin df -h /srv/data | tail -1
/dev/mapper/vgdata-lvdata 974M 801M 107M 89% /srv/data
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
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.
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.
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.
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
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
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.
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.
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.
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.
Module 4 · Mounts, fstab and swap space
- 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; understandnofail,noauto,x-systemd.device-timeout=,x-systemd.automount,x-systemd.requires=,_netdev. - Know how systemd-fstab-generator translates fstab to
srv-data.mountand mounts it tolocal-fs.target, and why it enters emergency mode when a disk is missing. - Create and persist swap files, understand
vm.swappinessand "swap space is not a substitute for memory".
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:
| Columns | Meaning | Example | Key points |
|---|---|---|---|
| 1 device | File system to be mounted | UUID=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 point | Directory | /srv/data; replace with none | Directory must exist |
| 3 Type | File system type | ext4, xfs, swap, nfs | — |
| 4 options | Mount options, comma separated | defaults,nofail,noatime | See table below |
| 5 dump | Whether to be dumped backup | 0 | almost always 0 |
| 6 pass | boot fsck order | root is 1, other ext4 is 2, xfs/network/swap is 0 | xfs does not fsck at boot |
Key options
| Option | Effect |
|---|---|
defaults | rw, suid, dev, exec, auto, nouser, async |
nofail | This 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 |
noauto | It does not mount when booting. Manually when needed mount |
x-systemd.device-timeout=10s | Time to wait for device to appear (default 90 seconds, from DefaultDeviceTimeoutSec) |
x-systemd.mount-timeout= | Timeout for the mount command itself |
x-systemd.automount | Generate .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 |
_netdev | Declare 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,noexec | Does not update access time (reduces writing)/security hardening (such as /tmp, data disk) |
How: How to deal with systemd fstab
- 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. - 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. - Local mounts without
nofailarelocal-fs.targetRequires; either fails → local-fs.target fails → itsOnFailure=emergency.targettakes effect → enters emergency mode (console only, SSH not yet started). - 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 availableRequiresMountsFor=/srv/datato 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 withfallocateon ext4/xfs; btrfs requires special processing (btrfs filesystem mkswapfile).
When: Which writing method to choose
| Scenario | Recommended writing method |
|---|---|
| Root, /boot and other necessary volumes for the system | UUID, 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 device | nofail 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 |
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
Relationship between memory and exchange
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.
Mount and swap command
| Command | Function | Description |
|---|---|---|
findmnt / findmnt /srv/data / findmnt -t ext4,xfs | Mount tree/certain mount point/by type | Clearer than mount | grep |
sudo findmnt --verify --verbose | Static check fstab | The first step after changing fstab |
sudo mount -a | Mount all unmounted, non-noauto entries in fstab | Second step (daemon-reload first) |
sudo mount -o remount,ro /srv/data | Remount as read-only | Use during maintenance |
sudo umount /srv/data / umount -l | Uninstall/delay uninstall | Check who is using it first |
sudo fuser -vm /srv/data / sudo lsof +f -- /srv/data | Who is using this mount point | When target is busy |
systemd-escape -p --suffix=mount /srv/data | Get unit name from path | Output srv-data.mount |
systemctl status srv-data.mount | Mount unit status | Failure reason |
systemctl list-units --type=mount,automount,swap | All mount related units | — |
swapon --show / free -h | Swap space/memory overview | — |
sudo mkswap /swapfile / swapon / swapoff | Create/enable/close swap | — |
sysctl vm.swappiness / /etc/sysctl.d/*.conf | View/persistent settings | sudo sysctl --system Reload |
vmstat 1 5 | Look 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)
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
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.
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.
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.
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".
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
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.
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
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
systemd-fstab-generator, nofail and emergency mode: No verified video found, please refer to the animation and official documentation of this module.
Official documentation
- fstab(5)
- systemd.mount(5) (x-systemd.* options, nofail)
- systemd-fstab-generator(8)
- findmnt(8) · swapon(8)
- Kernel documentation: vm.swappiness
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video/MP3. The following storyboards and explanations can be produced by video tools.
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.
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.
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.
Module 5 · Network: ip, ss, routing and DNS resolution
- Use
ip -br link/addr,ip route,ip route get,ip neighto read the interface, address, default gateway, and exit to a destination. - Use
ssto distinguish listening (LISTEN) and established (ESTAB) connections, find out the process to which the port belongs, and understand the differences between0.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; knowdigandcurlWhy 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 usenetplan tryto safely change the network.
What: Five "tables" of the Linux network stack
| Objects | Questions answered | Commands | linuxlab example |
|---|---|---|---|
| Interface (link) | What network cards are there? Is it UP? MAC vs. MTU? | ip -br link | lo, eth0 (usually eth0 under Hyper-V, ens3/enp0s1 under QEMU/KVM) |
| Address (addr) | What IPs are configured on each interface? | ip -br addr | 172.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 purpose | default 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 neigh | Gateway 172.25.112.1 → 00:15:5d:… |
| Socket (socket) | Which processes are listening on which ports? What are the connections? | ss -tulpn, ss -tnp | gunicorn 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)
- Name resolution: curl calls glibc's
getaddrinfo(), press Check thehosts:lines of/etc/nsswitch.confin order (Ubuntu Server usuallyfiles dns): first/etc/hosts, then press/etc/resolv.confto send a DNS request. - Ubuntu's
/etc/resolv.conflinks to/run/systemd/resolve/stub-resolv.conf, onlynameserver 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. - 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 rangenet.ipv4.ip_local_port_range). - 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...).
- Issed: SYN is sent from eth0 via the netfilter OUTPUT/POSTROUTING chain, queue discipline (qdisc), and network card driver; after the three-way handshake,
sscan be seenESTAB. - 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 address | Who can connect | linuxlab medium |
|---|---|---|
127.0.0.1:6379 | Native only | Redis (Ubuntu package defaults to bind 127.0.0.1 -::1) - exactly what we want |
0.0.0.0:5000 | All IPv4 interfaces | myapp (gunicorn --bind ${BIND}, BIND=0.0.0.0:5000 in env file), the host can access |
[::]:22 / *:22 | all 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 Desktop | RHEL / Rocky / Alma | |
|---|---|---|---|
| Declarative configuration | Netplan 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 executor | systemd-networkd(networkctl) | NetworkManager | NetworkManager(nmcli) |
| DNS | systemd-resolved(resolvectl) | systemd-resolved | NetworkManager directly writes /etc/resolv.conf (not enabled by default) resolved) |
| Security modification | sudo netplan try (automatic rollback if not confirmed within 120 seconds) | Graphical interface / nmcli | nmcli 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)
- Is the local service listening? Is the listening address correct? (
ss -tlnp) - The interface is UP. Is there an address? (
ip -br addr) - Is the route to the destination correct? (
ip route get) Is the next hop available? (ping gateway,ip neigh) - Is the name resolution correct? (
getent ahosts nameuses the same NSS path;resolvectl querysee resolved) - Is the firewall/security group/peer allowed? (
nc -vz host port,curl -v)
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
Netplan location
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.
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
| Commands | Function | Description |
|---|---|---|
ip -br link / ip -br addr / ip -c a | Interface/Address (concise/color) | Replace ifconfig |
ip route / ip -6 route | Main routing table | ip route show table local View local routing |
ip route get 1.1.1.1 | The actual selection of the destination by the kernel | View the exit, next hop, and source address at once |
ip neigh | ARP/NDP neighbor table | FAILED/INCOMPLETE = Layer 2 is blocked |
sudo ip addr add 10.99.0.1/24 dev lab0 / ip route add … | Temporary modification | Restart fails |
ss -tulpn | TCP/UDP listening port and process | See the process and you need sudo |
ss -tnp state established '( dport = :6379 )' | Filter established connections | ss filter syntax |
ss -s | Socket statistics | TIME-WAIT number |
getent ahosts Name | Resolved by NSS (consistent with application) | — |
resolvectl status / resolvectl query Name | DNS server per link / resolved | resolvectl statistics, flush-caches |
dig @1.1.1.1 example.com +short | Ask a DNS server directly | bind9-dnsutils package |
nc -vz host port / curl -v | Test TCP port / HTTP | More descriptive than ping |
tracepath host / mtr | Path and MTU | — |
sudo tcpdump -ni eth0 port 53 | Capture packet | Final judge |
netplan get / netplan status / sudo netplan try / apply | Netplan configuration/status/application with rollback | — |
networkctl status | systemd-networkd perspective | — |
nmcli dev status / nmcli con show | NetworkManager (RHEL system) | rhellab |
sudo ufw status verbose | Ubuntu firewall front-end status | Default 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)
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).
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.
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.
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.
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
cachesudo 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.
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 )'
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
Official documentation
- ip-route(8) · ss(8)
- systemd-resolved.service(8) · resolvectl(1)
- nsswitch.conf(5)
- Netplan documentation
- RHEL Documentation (NetworkManager)
Video storyboard script (about 100 seconds)
This courseware cannot directly generate videos/MP3s. The following storyboards and explanations can be produced by video tools.
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.
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.
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.
Module 6 · SSH: Keys, Configuration and Hardening
- 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 withsshd -t/sshd -T; know Ubuntussh.socketHow to correctly change the port under socket activation.
What: Two pairs of keys in SSH
| Host key | User key | |
|---|---|---|
| What to prove | "It is indeed that server you are connected to" | "It is indeed you who is logging in" |
| Private key location | Server /etc/ssh/ssh_host_ed25519_key etc. | Client ~/.ssh/id_ed25519 (should be password protected) |
| Who remembers the public key | Client ~/.ssh/known_hosts (TOFU: Trust On First Use when connecting for the first time) | Server ~/.ssh/authorized_keys |
| When changed | Client reports REMOTE HOST IDENTIFICATION HAS CHANGED!——It may be a reinstallation or a man-in-the-middle attack | Server refused: Permission denied (publickey) |
How: A connection process
- TCP connection to 22 Port (first accepted by
ssh.socketwith PID 1 on Ubuntu, andssh.servicestarted if necessary). - Version exchange: Both parties send
SSH-2.0-OpenSSH_10.2…. - Key Exchange (KEX): Negotiation algorithm to calculate the shared session key. OpenSSH 10.0 uses the post-quantum hybrid algorithm
mlkem768x25519-sha256by default, and completely removes DSA key support. - Host authentication: The server signs with the host's private key, and the client verifies with the public key recorded in known_hosts.
- 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.
- Session: After authentication, sshd derives a session process with downgraded rights (
sshd-sessionis removed from OpenSSH 9.8 and authenticated insshd-authfrom 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_configThe beginning isInclude /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.confwritten by cloud-init (such asPasswordAuthentication). If the hardening file is named99-hardening.conf, the keyword with the same name will be preempted by 50-cloud-init - it should be named10-…. Matchblock (such asMatch 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: Mustsudo systemctl daemon-reload(rerun the generator) aftersudo 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)
| Settings | Function | Note |
|---|---|---|
PasswordAuthentication no, KbdInteractiveAuthentication no | Only keys allowed | Confirm that the key login is successful first |
PermitRootLogin no | Prohibit root direct login | Use ordinary user + sudo, the audit can be traced back to the person |
AllowUsers / AllowGroups | Whitelist | Multipass instance must be retained ubuntu (used by multipass shell) |
MaxAuthTries 3, LoginGraceTime 30 | Reduce the blast window | When there are too many keys in the agent, the number of times may be used up → Use IdentitiesOnly |
X11Forwarding no, AllowAgentForwarding no, AllowTcpForwarding no | Reduce the attack surface | Requires port forwarding / Use Match to open by user during springboard |
ClientAliveInterval 300, ClientAliveCountMax 2 | Clean up zombie sessions | — |
| Network layer | Firewall/security group is only open to the management network segment 22; fail2ban or sshd's own PerSourcePenalties (OpenSSH 9.8+) Suppressing blasts | Changing ports can only reduce log noise, not a security measure |
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
Configuration reading order and "the first value takes effect"
sshd -T to confirm the final resultAnimation: 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.
SSH client and server commands
| Command | Function | Instructions |
|---|---|---|
ssh-keygen -t ed25519 -a 100 -C "labadmin@laptop" -f ~/.ssh/linuxlab_ed25519 | Generate Ed25519 key | -a Increase the number of KDF rounds for the password |
ssh-copy-id -i ~/.ssh/linuxlab_ed25519.pub labadmin@HOST | Install the public key | Windows None ssh-copy-id, see experiment |
eval "$(ssh-agent -s)"; ssh-add ~/.ssh/linuxlab_ed25519 | Start the agent and load the private key | Windows: Start-Service ssh-agent |
ssh -v linuxlab / -vvv | Debug output | See which keys are provided and which steps failed |
ssh -J bastion target | Connect via springboard | ProxyJump in config |
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub | Server host key fingerprint | Comparison with client display when first connected |
ssh-keygen -R HOST | Remove old entries from known_hosts | Check the new fingerprint before doing it |
sudo sshd -t | Check the configuration syntax | Pass if there is no output |
sudo sshd -T / sudo sshd -T -C user=labadmin,host=h,addr=10.0.0.5 | Output the final effective configuration/simulate a certain connection | Keywords are output in lowercase |
sudo systemctl reload ssh | Re-read the configuration | RHEL: sshd |
sudo systemctl daemon-reload && sudo systemctl restart ssh.socket | After Ubuntu changes Port/ListenAddress | — |
journalctl -u ssh -f / journalctl -t sshd-session | Authentication log | Write also when there is rsyslog /var/log/auth.log |
who / last -n 5 / loginctl list-sessions | Current 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)
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). ssh-keygen -t ed25519 -a 100 -C "labadmin@linuxlab-course" -f ~/.ssh/linuxlab_ed25519 # Set a password when prompted for a password
# 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.
~/.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.
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
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
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.
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]
# 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.
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 bastionThe 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
Official Document
- sshd_config(5) · ssh_config(5)
- ssh-keygen(1)
- OpenSSH Release Notes (10.0: mlkem768x25519 Default, removed DSA; 9.8: sshd-session)
- Ubuntu Server: OpenSSH server
- Launchpad #2069041 (daemon-reload is required to change the port)
Video storyboard script (approx. 90 seconds)
This courseware cannot directly generate video/MP3. The following storyboards and explanations can be produced by video tools.
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.
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.
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.
Module 7 · Scheduled tasks: cron and systemd timer, time synchronization
- 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+.timerWrite scheduled tasks:OnCalendar=,Persistent=,RandomizedDelaySec=,AccuracySec=,OnBootSec=/OnUnitActiveSec=, usesystemd-analyze calendarto 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.
What: two schedulers
| cron | systemd timer | |
|---|---|---|
| Definition | One line: Minute Hour Day Month Week [User] Command | Two units: x.timer (when) + x.service (what to do) |
| Where | crontab -e (user), /etc/crontab and /etc/cron.d/* (with user fields), /etc/cron.daily/ and other directories | /etc/systemd/system/ |
| Missed tasks during shutdown | No catch-up (anacron only makes up for daily/weekly/monthly directories) | Persistent=true Run once after booting |
| Log | Send the output to an email, or redirect it to the file yourself | Automatically enter journal: journalctl -u x.service |
| Failure visibility | Need to handle it yourself | systemctl --failed, OnFailure= trigger alarm unit |
| Environment | Minimalist environment (short PATH, no login shell configuration) | Clear and repeatable: Environment=, EnvironmentFile= |
| Anti-overlap | Requires flock | When the same service is running, the timer will not start the second instance |
| Sandbox/Resources/Dependencies | None | Module All options of 1, RequiresMountsFor=, MemoryMax=, Nice= |
| Multi-machine peak staggering | Manual staggering | RandomizedDelaySec= (available FixedRandomDelay=yes Let the offset of each machine be fixed) |
| Learning cost | Low, done in one line | Two 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 setPATH=at the top of the crontab. %: The crontab command means line break (the subsequent content is used as standard input),date +%Fmust be written asdate +\%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
MAILTOvia 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
| Options | Meaning | Example |
|---|---|---|
OnCalendar= | Calendar time (real-time clock) | *-*-* 02:30:00, Mon..Fri 09:00, hourly, *:0/15 (every 15 minutes) |
OnBootSec= / OnStartupSec= | How long after booting | OnBootSec=5min |
OnUnitActiveSec= / OnUnitInactiveSec= | How long since the last run started/ended (monotonic clock) | OnUnitActiveSec=1h |
Persistent=true | Record the last trigger time (/var/lib/systemd/timers/), if you miss it when booting, run it immediately | Only valid for OnCalendar |
RandomizedDelaySec= | Add a random delay between 0 and this value for each trigger | Multiple 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 minute | Set 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 asubuntu-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-statusto 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 writingOnCalendar=*-*-* 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.
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
Time synchronization link
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.
Scheduled tasks and time commands
| Command | Function | Description |
|---|---|---|
crontab -e / -l / sudo crontab -u myapp -l | Edit/View user crontab | Stored in /var/spool/cron/crontabs/ |
journalctl -u cron | cron execution record | Only records "run", no output |
flock -n /run/lock/job.lock command | Prevent cron task overlap | — |
systemctl list-timers --all | Next/last firing of all timers | — |
systemd-analyze calendar --iterations=5 'Mon..Fri 02:30' | Validate calendar expression | Show normalized form and next time |
systemd-analyze verify x.timer x.service | Static check | — |
sudo systemctl enable --now x.timer | Enable timer | Do not enable .service |
sudo systemctl start x.service | Manually run the task immediately | For testing |
systemd-run --on-calendar='*-*-* 03:00' --unit=once-job command | Temporary timer (transient) | Disappears after restart |
systemd-run --on-active=30s command | Run once after 30 seconds | Replacement at |
timedatectl / timedatectl set-timezone UTC | Clock, time zone, synchronization status | — |
chronyc tracking | Current deviation, frequency, reference source | System time line is the most critical |
chronyc sources -v / chronyc sourcestats | Time source list and statistics | * For the currently selected source |
sudo chronyc -N authdata | NTS certification status | Mode is listed as NTS |
sudo chronyc makestep | Immediate jump correction | When the deviation is large; it may affect applications that rely on monotonic time |
timedatectl timesync-status | systemd-timesyncd status | 24.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)
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.
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
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.
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.
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.
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.
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
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
chrony + NTS's topic: No verified high-quality video found, please refer to official documents.
Official documentation
- systemd.timer(5) · systemd.time(7) (calendar expression)
- crontab(5)
- chrony documentation
- Ubuntu 25.10 release notes (chrony becomes default, NTS)
- timedatectl(1)
Video storyboard script (about 90 seconds)
This courseware cannot directly generate videos/MP3s. The following storyboards and explanations can be produced by video tools.
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.
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.
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.
Module 8 · Production readiness review and common mistakes
- 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.
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)
| Dimension | Check item | Verification command | Module |
|---|---|---|---|
| Service | myapp is managed by systemd and starts automatically at boot | systemctl is-enabled myapp | M1 |
| Run as a non-root user | systemctl show myapp -p User | M1 | |
| Crash automatically restarts with back-off | systemctl show myapp -p Restart,RestartSteps | M1 | |
| Sandbox exposure ≤ 4 (heuristic) | systemd-analyze security myapp | M1 | |
| Log | journal persistence | journalctl --list-boots | wc -l > 1 | M2 |
| journal has a clear upper limit | systemd-analyze cat-config systemd/journald.conf | grep SystemMaxUse | M2 | |
| All text logs have rotation rules | logrotate -d /etc/logrotate.conf | M2 | |
| Storage | All file system usage < 80%, inode < 80% | df -h, df -i | M3 |
| Data is separated from the system, VG has margin | vgs | M3 | |
| fstab uses UUID, non-system volume nofail, verify Through | findmnt --verify | M4 | |
| Network | Only expose the required ports; the backend only listens for loopback | ss -tlnp | M5 |
| DNS resolution is normal and there is an upstream | resolvectl status, getent hosts | M5 | |
| Firewall is enabled on demand (ufw / Cloud Security Group) | ufw status | M5 / Lessons 3 and 4 | |
| Access | Key login only, root ban, whitelist | sshd -T | M6 |
| Minimized sudo permissions, no shared account | getent group sudo | Lesson 1 | |
| Time and Scheduling | Clocks synchronized | timedatectl show -p NTPSynchronized | M7 |
| Backup timer enabled and recently successful | systemctl list-timers myapp-backup.timer | M7 | |
| Backup can be restored (rehearsed) | Restore to test instance | M7 | |
| Patch and baseline | No failed units | systemctl --failed | All |
| Automatic security updates enabled; whether to wait for restart | systemctl is-enabled unattended-upgrades, ls /var/run/reboot-required | Lesson 1 | |
| Configuring Rebuildable (Ansible/cloud-init) | Code Repository | Ansible 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
- Phenomena: Accurate description (which command, what error is reported, where to access, when to start).
- Status:
systemctl --failed,systemctl status service,df -h,free -h,ss -tlnp. - Log:
journalctl -u service -b,journalctl -p err -b,journalctl -k. - Recent changes:
/var/log/apt/history.log, configuration file modification time,last. - 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.
Ready map: system components corresponding to seven dimensions
Layering of fault location
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.
Review and troubleshooting "first minute" command
| Command | What to look at |
|---|---|
systemctl is-system-running | running / degraded / maintenance |
systemctl --failed | Which units failed |
journalctl -p err -b --no-pager | tail -n 30 | Errors in this startup |
uptime / free -h / df -h / df -i | Load, memory, disk, inode |
journalctl -k -b | grep -iE 'oom|i/o error|ext4-fs error|xfs' | OOM and disk errors |
sudo ss -tlnp | Listening port |
ip -br a; ip route; resolvectl status | head -20 | Network fundamentals |
timedatectl show -p NTPSynchronized --value | yes / no |
sudo sshd -T | grep -E '^(passwordauthentication|permitrootlogin)' | SSH strategy |
systemctl list-timers --all | Scheduled tasks |
apt list --upgradable 2>/dev/null | wc -l, cat /var/run/reboot-required 2>/dev/null | Patch and pending restart |
tail -n 20 /var/log/apt/history.log, last -n 10 | Recent changes and login |
Experiment 8: Readiness check script + four fault injections (about 12 minutes)
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.
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.
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%.
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.
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
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/phenomenon | The most likely reasons | Module |
|---|---|---|
status=203/EXEC | ExecStart Path/permission/interpreter issues | M1 |
start-limit-hit | Repeated failures within a short period of time | M1 |
Read-only file system (within service) | ProtectSystem=strict Missing ReadWritePaths | M1/M7 |
No space left on device | Space or inode Used up; unreleased files have been deleted | M2/M3 |
You are in emergency mode | fstab hard mount failed | M4 |
Could not resolve host | DNS upstream / resolved / hosts | M5 |
Connection refused / timed out | No one is listening / dropped in the middle | M5 |
Permission denied (publickey) | Keys, permissions, AllowUsers | M6 |
Bad configuration option | sshd configuration misspelling | M6 |
System clock synchronized: no | NTP/NTS port blocked | M7 |
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; done2. Find files on the / file system that have been deleted but are still occupied by processes.
sudo lsof -nP +L1 / 2>/dev/null | head
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
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.
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.
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.
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.
Command Cheat Sheet
[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.targetsystemctl status|start|stop|restart|reload X | Runtime operation |
systemctl enable --now X | Auto + startup |
systemctl daemon-reload | After changing unit / fstab |
systemctl edit X / cat X | drop-in / view merge results |
systemctl show X -p Prop | Attributes |
systemctl list-dependencies X [--reverse] | Dependency tree |
systemctl --failed / reset-failed X | Failed unit |
systemd-analyze verify|security|critical-chain|blame | Inspection and analysis |
systemd-run --pty -p Prop=… cmd | Transient unit |
journalctl -u X -b -p warning -f | Unit / This startup / level / follow |
journalctl -b -1 · --list-boots | Last startup |
journalctl --since "1 hour ago" -g 'regex' | Time + regular |
journalctl -k · -o json-pretty · -F FIELD | Kernel / all fields / field values |
journalctl --disk-usage · --vacuum-size=200M | Occupy / cleanup |
/etc/systemd/journald.conf.d/*.conf | Storage= · SystemMaxUse= · MaxRetentionSec= |
logrotate -d FILE / -f FILE | Debug/Force |
rsyslogd -N1 | rsyslog syntax check |
lsblk -f · blkid · df -hT · df -i | Panorama |
losetup -fP --show IMG | Loopback device |
parted -s DEV mklabel gpt mkpart data 1MiB 100% set 1 lvm on | Partition |
pvcreate → vgcreate VG PV → lvcreate -n LV -L 1G VG | Volume creation |
vgextend VG PV → lvextend -r -L +1G VG/LV | Expansion |
resize2fs DEV · xfs_growfs MOUNTPOINT | Individual file system expansion |
growpart DISK N · pvresize PV | After cloud disk expansion |
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 -a | Change fstab three steps |
fuser -vm MNT | target is busy |
fallocate -l 1G /swapfile; chmod 600; mkswap; swapon | Swap file |
/etc/sysctl.d/99-x.conf: vm.swappiness=10 | sysctl --system |
ip -br a · ip route · ip route get IP · ip neigh | Interface/Routing/Actual Exit/ARP |
ss -tulpn · ss -tnp state established | Listen/Connect |
getent ahosts NAME | Analysis consistent with application |
resolvectl status|query|flush-caches|statistics | resolved |
netplan get|status|try|apply · networkctl | Ubuntu |
nmcli dev status · nmcli con show | RHEL system |
nc -vz HOST PORT · tcpdump -ni IF port N | Port/packet capture |
ssh-keygen -t ed25519 -a 100 -f ~/.ssh/KEY | Generate key |
~/.ssh/config: Host · HostName · User · IdentityFile · IdentitiesOnly · ProxyJump | Client configuration |
/etc/ssh/sshd_config.d/10-*.conf | The first value takes effect → small number |
sshd -t · sshd -T [-C user=,host=,addr=] | Syntax / Valid value |
systemctl reload ssh | Authentication class settings |
daemon-reload + restart ssh.socket | Port / ListenAddress(Ubuntu) |
ssh -v · ssh-keygen -R HOST · ssh-keygen -lf PUB | Debug / delete old host key / fingerprint |
[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 --all | All timers |
systemd-run --on-active=10min CMD | One-time delayed tasks |
crontab: hour day month week [user] Command, % → \% | cron |
timedatectl · chronyc tracking|sources -v · chronyc -N authdata | Time synchronization |
systemctl is-system-running; systemctl --failed | Overall status |
journalctl -p err -b | tail | Error |
uptime; free -h; df -h; df -i | Resources |
sudo ss -tlnp; ip route; resolvectl status | Network |
timedatectl show -p NTPSynchronized | Time |
sudo bash ~/linuxlab/readiness.sh | Ready script |
| Project | Ubuntu 26.04 | Rocky / Alma 10 |
|---|---|---|
| SSH Service | ssh.service + ssh.socket | sshd.service |
| Network | Netplan → networkd | NetworkManager |
| DNS | systemd-resolved | NetworkManager writes resolv.conf |
| Time | chrony.service | chronyd.service |
| Default file system | ext4 | xfs |
| cron | cron.service | crond.service(cronie) |
| syslog file | /var/log/syslog, auth.log (rsyslog required) | /var/log/messages, secure |
Comprehensive experiment + final exam
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.
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.*).
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. 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 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). 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. ss -tlnp ; confirm that sshd -T is still a key-only login. 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). 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.
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
| Topic | Verification conclusion | Source (Access date: 2026-11-17) |
|---|---|---|
| Ubuntu 26.04 LTS components | systemd 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=yes | Ubuntu 26.04 LTS release notes · Changes since 25.10 |
| Ubuntu 25.10 changes | chrony 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-tools | Ubuntu 25.10 release notes |
| Dependency and ordering | Wants/Requires/Requisite/BindsTo/PartOf semantics; requirement dependencies do not imply order; Wants+After is recommended; implicit dependencies of DefaultDependencies | systemd.unit(5) · bootup(7) · systemd.special(7) |
| Service type and restart | Restart= 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/idle | systemd.service(5) |
| Sandbox options | ProtectSystem=strict/full, ProtectHome, PrivateTmp, PrivateDevices, NoNewPrivileges, CapabilityBoundingSet, RestrictAddressFamilies, SystemCallFilter=@system-service, StateDirectory, ReadWritePaths | systemd.exec(5) · systemd-analyze(1) |
| systemctl options | --kill-whom=; edit --stdin(systemd 256+); --drop-in= | systemctl(1) |
| journald | Storage= 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 forwarded | journald.conf(5) (page version systemd 262~devel) |
| rsyslog Whether it is pre-installed | No 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 |
| logrotate | create / copytruncate / su / postrotate / maxsize semantics | logrotate(8) |
| LVM and file system | lvextend -r (--resizefs); Requires), x-systemd.device-timeout, automount, _netdev, generator | lvextend(8) · xfs_growfs(8) |
| fstab and mount unit | nofail (Wants instead of Requires), x-systemd.device-timeout, automount, _netdev, generator | systemd.mount(5) · systemd-fstab-generator(8) · fstab(5) |
| Network and DNS | resolved stub 127.0.0.53 and proxy stub 127.0.0.54, ReadEtcHosts; iproute2 usage; Netplan try | systemd-resolved(8) · ip-route(8) · Netplan |
| SSH | sshd_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.socket | Ubuntu Server: OpenSSH server · LP #2069041 · sshd_config(5) |
| OpenSSH 10.x | 10.0 defaults to mlkem768x25519-sha256 and removes DSA; 9.8 introduces sshd-session and PerSourcePenalties | OpenSSH Release Notes |
| timer and cron | OnCalendar, Persistent, RandomizedDelaySec, FixedRandomDelay, AccuracySec default 1min; the meaning of % in crontab | systemd.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 securityscore 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.servicehas 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-rotateis a script provided by the Debian/Ubuntu rsyslog package. If it is missing, usesystemctl kill -s HUP rsysloginstead. - 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=execis a conservative choice (does not rely on gunicorn's sd_notify behavior). - Chrony's NTS server name,
chronycoutput 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.