Platform Engineering · Lesson 21

The Boot Process and Recovery

Between pressing power and a login prompt, a Linux server runs a relay: firmware finds a bootloader, GRUB loads a kernel and an initramfs, the initramfs finds and mounts the real root file system, and systemd starts every service up to the default target. When a host does not come back after a kernel update or a config change, knowing which runner dropped the baton tells you which recovery tool to use. This lesson boots one server, then breaks it twice.

Difficulty: Advanced · Know this first: Lesson 05, Lesson 15

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes from power on to a usable server. It is a worked example, not a measurement. The initramfs and systemd hops are where a boot fails, and the recovery kit decides how long it stays failed.

Try it: which recovery do you need?

Pick where the boot stops and what you have prepared. See the fastest way back.

GRUB: init=/bin/bashfastest way in
55minutes, roughly

Emergency mode refuses a locked root: edit the kernel line in GRUB to get a shell

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Boot and recovery grow in four levels: reading the boot, changing it safely, recovering by hand, and making recovery routine across a fleet.

Basic — Read how the system booted

At the basic level you can tell how the last boot went.

  • uname -r, cat /proc/cmdline, systemctl get-default.
  • systemd-analyze, systemd-analyze blame, systemctl --failed.
  • journalctl -b (this boot) and journalctl -b -1 (the previous one).

Where it breaks: looking at the current boot's log for an error that happened in the boot before.

Try it: Basic

A server rebooted overnight unexpectedly. Where are the last messages before the reboot?

Now do it: Run journalctl --list-boots and read the last lines of boot -1.

Intermediate — Change the boot safely

At the intermediate level you change kernels and boot settings without risk.

  • /etc/default/grub, then update-grub or grub2-mkconfig -o /boot/grub2/grub.cfg.
  • update-initramfs -u -k all or dracut -f after storage or driver changes.
  • Keep two kernels and space in /boot; grub-reboot to try a kernel once.

Try it: Intermediate

You want to try a new kernel once, falling back to the old default if it fails. What helps?

Now do it: List boot entries with grubby --info=ALL or awk on grub.cfg.

Advanced — Recover by hand

At the advanced level you can get into a broken system.

  • GRUB edit: e, then systemd.unit=rescue.target, or init=/bin/bash and mount -o remount,rw /.
  • initramfs and dracut shells: find the root device with blkid, lvm vgchange -ay.
  • Rescue image and chroot: mount root, bind /dev /proc /sys, chroot, rebuild initramfs or reinstall GRUB.

Try it: Advanced

You booted with init=/bin/bash and edited fstab, but after reboot the change is gone. Why?

Now do it: Practise the init=/bin/bash recovery on a VM until it takes under five minutes.

Master — Recovery as routine

At the master level a failed boot is a short, rehearsed event.

  • Console access for every host, tested; GRUB passwords so console access is the only way to edit boot entries.
  • Kernel rollouts in rings with automatic fallback; immutable images so a bad host is replaced, not repaired.
  • Game days that break fstab, the initramfs, and GRUB on staging.

Trade-off: repairing hosts by hand keeps their state and costs skilled time under pressure; replacing them from images is fast and needs state to live elsewhere.

Try it: Master

A cloud VM will not boot after a change. What is often the fastest recovery when the root volume holds no unique data?

Now do it: For one service, write down whether you would repair or replace a host that will not boot.

Go deeper

Inspect the boot, rebuild the pieces that usually break, and the recovery moves to practise on a VM.

Inspect

systemd-analyze                     # firmware, loader, kernel, initrd, userspace times
systemd-analyze blame | head
cat /proc/cmdline; uname -r
ls /boot; df -h /boot               # kernels kept, space left
journalctl --list-boots; journalctl -b -1 -p err
efibootmgr -v 2>/dev/null | head

Rebuild after a kernel or storage change

# Debian and Ubuntu
sudo update-initramfs -u -k all && sudo update-grub
# Red Hat family
sudo dracut -f --regenerate-all && sudo grub2-mkconfig -o /boot/grub2/grub.cfg
# boot a given entry once only
sudo grub-reboot "Advanced options for Ubuntu>Ubuntu, with Linux 6.8.0-49-generic"

Get a shell when emergency mode refuses one (practise on a VM)

# at the GRUB menu: highlight the entry, press e
# on the line starting with "linux", append:   init=/bin/bash
# press Ctrl+X to boot, then:
mount -o remount,rw /
vi /etc/fstab            # fix the broken line, or add nofail
sync
exec /sbin/reboot -f

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A routine kernel update left a host down for a morning.

Timeline

  • 02:00Automatic updates install a new kernel. /boot is 97% full; the initramfs is written incomplete, without warnings anyone reads.
  • 02:10The scheduled reboot panics: unable to mount root. GRUB's timeout is 0 and the menu is hidden.
  • 08:30An engineer gets the serial console working, interrupts GRUB, boots the old kernel, frees /boot, rebuilds the initramfs, and reboots into the new kernel.

What changed after

/boot usage is monitored, old kernels are removed automatically except the last two, GRUB shows the menu for 5 seconds on the serial console, and kernel updates roll out to a canary ring first with a one-time boot.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. How the last boot went: time per stage and the slowest units.

    systemd-analyze; systemd-analyze blame --no-pager | head -5
  2. The running kernel, its command line, and the kernels you can fall back to.

    uname -r; cat /proc/cmdline; ls /boot/vmlinuz-* 2>/dev/null; df -h /boot
  3. Past boots and the errors of the previous one.

    journalctl --list-boots --no-pager | tail -3; journalctl -b -1 -p err --no-pager 2>/dev/null | tail -5
  4. Is the storage driver in the initramfs for this kernel?

    lsinitramfs /boot/initrd.img-$(uname -r) 2>/dev/null | grep -E "nvme|virtio_blk|ahci" | head -3 || sudo lsinitrd 2>/dev/null | grep -E "nvme|virtio" | head -3

2. Python: boot_chain.py

This program walks the boot relay and reports the first stage that fails, with the recovery tool for it, for three broken machines. Save it as boot_chain.py, then run it.

# boot_chain.py
STAGES = [
    ("firmware", lambda m: m["efi_entry"], "boot a rescue image and run efibootmgr / grub-install"),
    ("grub", lambda m: m["grub_cfg"], "rescue image, then grub-install and update-grub"),
    ("kernel+initramfs", lambda m: m["storage_driver_in_initramfs"], "pick the previous kernel in GRUB, then update-initramfs -u"),
    ("root mount", lambda m: m["root_uuid_found"], "initramfs shell: blkid, then fix root= on the kernel line"),
    ("fstab mounts", lambda m: m["fstab_ok"], "emergency shell, or GRUB: init=/bin/bash, fix fstab, add nofail"),
    ("default target", lambda m: True, ""),
]

machines = {
    "healthy": dict(efi_entry=True, grub_cfg=True, storage_driver_in_initramfs=True, root_uuid_found=True, fstab_ok=True),
    "after kernel update": dict(efi_entry=True, grub_cfg=True, storage_driver_in_initramfs=False, root_uuid_found=True, fstab_ok=True),
    "after adding a disk": dict(efi_entry=True, grub_cfg=True, storage_driver_in_initramfs=True, root_uuid_found=True, fstab_ok=False),
}
for name, m in machines.items():
    for stage, ok, fix in STAGES:
        if not ok(m):
            print(f"{name:<20} stops at {stage:<17} -> {fix}")
            break
    else:
        print(f"{name:<20} reaches the login prompt")

Run it, and you should see this output:

$ python3 boot_chain.py
healthy              reaches the login prompt
after kernel update  stops at kernel+initramfs  -> pick the previous kernel in GRUB, then update-initramfs -u
after adding a disk  stops at fstab mounts      -> emergency shell, or GRUB: init=/bin/bash, fix fstab, add nofail

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/linux-boot-process-and-recovery && cd ~/labs/linux-boot-process-and-recovery) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "The Boot Process and Recovery", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'How the last boot went: time per stage and the slowest units.'
  'The running kernel, its command line, and the kernels you can fall back to.'
  'Past boots and the errors of the previous one.'
  'Is the storage driver in the initramfs for this kernel?'
)

step_1() {
systemd-analyze; systemd-analyze blame --no-pager | head -5
}

step_2() {
uname -r; cat /proc/cmdline; ls /boot/vmlinuz-* 2>/dev/null; df -h /boot
}

step_3() {
journalctl --list-boots --no-pager | tail -3; journalctl -b -1 -p err --no-pager 2>/dev/null | tail -5
}

step_4() {
lsinitramfs /boot/initrd.img-$(uname -r) 2>/dev/null | grep -E "nvme|virtio_blk|ahci" | head -3 || sudo lsinitrd 2>/dev/null | grep -E "nvme|virtio" | head -3
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Write the boot and recovery runbook for 100 Linux servers in a cloud and 10 physical database servers.

Clarifying questions to ask

How does an engineer reach the console of each kind? How are kernels rolled out and rolled back? What is the recovery when emergency mode refuses a shell? When do you repair a host and when do you replace it?

Rough sizing

Say monthly kernel updates, a 30-minute target to recover a failed boot, and two engineers on call.

Shape of the answer

Cloud: serial console access tested quarterly, immutable images, replace failed hosts. Physical: iLO or IPMI with tested credentials, a GRUB password, a 5-second menu on serial, two kernels kept, /boot monitored, a rescue image on the management network. Kernels in rings with grub-reboot for the first boot. A practised init=/bin/bash procedure in the runbook.

Trade-offs to name

A visible GRUB menu and console access make recovery fast and must be protected, because anyone at the console can edit boot entries. Replacing hosts is fastest for stateless servers; databases still need a repair path.

Saved on this device, in this browser.
Next in this series · Lesson 22
Logs on Linux: journald, rsyslog, and logrotate

Every Linux server keeps two kinds of logs: the systemd journal, a structured binary store read with journalctl, and text files in /var/log, written by rsyslog or by applications.

Go to Lesson 22 →

Or browse the full course from the Lessons index.