# How Linux boots, and what to do when it does not

How Linux boots, from firmware through GRUB, the kernel and initramfs to systemd targets. Read boot logs, find slow boots, and recover a server that won't start.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 12. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/linux/12-booting-linux

## What you will learn

- Name each stage of the boot, from firmware to the login prompt, and what happens in it
- Change GRUB settings and kernel options safely with /etc/default/grub
- Read the logs of the current and previous boots with journalctl -b and dmesg
- Explain systemd targets, and set or switch the default target
- Find what makes a boot slow with systemd-analyze
- Recover a server stuck in emergency mode, and reach it on a cloud VM

## The boot, stage by stage

**Why learn how Linux boots?** Most of the time you never think about it: the server reboots and
comes back. Then one day it doesn't. You reboot after a kernel update, or after adding a disk, and
the server never returns to SSH. Now you have to work out _where_ in the boot it stopped, with no
login and often no screen. Knowing the stages turns that panic into a checklist: each stage fails in
its own recognisable way, and each has its own fix.

Between pressing power and seeing a login prompt, five programs take turns. Each one finds and
starts the next:

> **Figure.** Animated. Five stages light up in order. Firmware (UEFI or BIOS) tests hardware and finds a boot disk. GRUB loads the kernel and initramfs. The kernel starts drivers. The initramfs finds and mounts the real root filesystem. systemd, PID 1, mounts /etc/fstab and starts services up to the default target, ending at a login prompt. Under each stage, what you see if the boot stops there: no bootable device, the grub rescue prompt, a kernel panic, the initramfs shell, emergency mode.
>
> Firmware, GRUB, kernel, initramfs, systemd. Where a boot stops tells you which one to fix.

| Stage                 | Does                                         | Fails like                       |
| --------------------- | -------------------------------------------- | -------------------------------- |
| Firmware (UEFI, BIOS) | Tests hardware, finds a boot disk            | "No bootable device"             |
| Boot loader (GRUB)    | Loads the kernel and initramfs from `/boot`  | `grub rescue>` prompt            |
| Kernel                | Starts drivers, mounts the initramfs         | Kernel panic                     |
| initramfs             | Finds the real root filesystem and mounts it | Drops to an `(initramfs)` shell  |
| systemd (PID 1)       | Starts services up to the default target     | Emergency mode, a failed service |

On a cloud VM you never see the screen, so the first two stages are the provider's job, and almost
every boot problem you'll fix is in the last one: systemd and `/etc/fstab`.

> **Video.** [How Linux Boots](https://www.youtube.com/watch?v=EjrAzulPsT4) (Joe Collins (EzeeLinux))

## The boot loader: GRUB

The firmware only knows how to find a disk and run a tiny program from it. It doesn't understand
Linux at all. That tiny program is the **boot loader**, and on Linux it's almost always GRUB. Its job
is to find the Linux kernel file on disk, load it into memory with the right options, and hand over
control. Because it can remember more than one kernel, it's also your escape hatch when a new kernel
won't boot.

GRUB shows the boot menu (it's hidden on most servers) and starts the kernel with its options. You
never edit its generated file, `/boot/grub/grub.cfg`. You edit the settings and regenerate it:

```text
# /etc/default/grub (excerpt)
GRUB_DEFAULT=0                      # which menu entry boots: 0 is the newest kernel
GRUB_TIMEOUT=5                      # seconds the menu waits
GRUB_CMDLINE_LINUX_DEFAULT="quiet"  # options passed to the kernel at every boot
```

```sh
$ sudo nano /etc/default/grub
$ sudo update-grub                          # Ubuntu, Debian: rebuild grub.cfg
$ sudo grub2-mkconfig -o /boot/grub2/grub.cfg   # RHEL family
$ cat /proc/cmdline                         # the options the running kernel booted with
$ ls /boot                                  # kernels (vmlinuz-*) and initramfs images (initrd.img-*)
```

Package upgrades install new kernels and update GRUB for you, keeping the previous kernel. If a new
kernel misbehaves, pick the older one from the GRUB menu (hold **Shift** or press **Esc** at boot)
under _Advanced options_.

Use the menu to boot a known-good kernel when an update fails, then inspect package and boot logs before
changing the default entry. Keep a previous kernel available until the new one has passed a reboot test. A
common mistake is editing the generated file and assuming the change will survive `update-grub` or a package
update.

## systemd targets

When the kernel and initramfs are done, they start **systemd** as process 1. systemd boots towards
a **target**: a named group of units that make up a system state. They replaced the old runlevels:

| Target              | Old runlevel | State                                             |
| ------------------- | ------------ | ------------------------------------------------- |
| `poweroff.target`   | 0            | off                                               |
| `rescue.target`     | 1            | single user, minimal services, for repairs        |
| `multi-user.target` | 3            | a normal server: networking, services, no desktop |
| `graphical.target`  | 5            | multi-user plus a desktop                         |
| `reboot.target`     | 6            | reboot                                            |
| `emergency.target`  |              | root shell, almost nothing mounted                |

```sh
$ systemctl get-default                       # the target this machine boots into
graphical.target
$ sudo systemctl set-default multi-user.target   # servers don't need a desktop
$ sudo systemctl isolate rescue.target        # switch now (this stops most services)
$ systemctl list-dependencies multi-user.target | head
```

Your services join the boot through targets: the `WantedBy=multi-user.target` in a unit file (from
the _Services with systemd_ lesson) is what `enable` links them into.

Use `get-default` to inspect the normal boot state and `set-default` to change it for future boots. `isolate`
switches the current machine immediately and can stop services, so use it only with a recovery path. A common
mistake is changing the default target when you meant to switch the current session, or isolating a remote
server into a state without network access.

> **Video.** [systemd on Linux 3: Targets](https://www.youtube.com/watch?v=4xO-_cQaEfA) (tutoriaLinux)

## Reading boot logs

```sh
$ journalctl --list-boots                     # every boot the journal remembers
IDX BOOT ID                          FIRST ENTRY                 LAST ENTRY
 -1 7c1d93e0a4b24f6e8d1f2a3b5c6d7e8f Sun 2026-10-11 05:47:21 UTC Mon 2026-10-12 23:58:02 UTC
  0 bea482c8f6f84fe4b096e875c660d327 Tue 2026-10-13 00:01:15 UTC Tue 2026-10-13 05:29:13 UTC
$ journalctl -b                               # this boot, from the first kernel line
$ journalctl -b -1 -p err                     # errors from the previous boot
$ journalctl -b -1 -n 50                      # the last 50 lines before the last reboot
$ sudo dmesg -T | grep -iE "error|fail|oom"   # kernel messages with readable times
$ systemctl --failed                          # units that failed this boot
```

`journalctl -b -1` is how you answer "why did it reboot at 3 am?". It needs the journal on disk:
check that `/var/log/journal/` exists (it does on modern Ubuntu). The end of the previous boot often
shows the cause: an out-of-memory kill, a kernel panic, or a clean `reboot` someone ran.

### Why is the boot slow?

```sh
$ systemd-analyze                             # total boot time
Startup finished in 2.1s (kernel) + 8.939s (userspace) = 11.039s
graphical.target reached after 8.939s in userspace.
$ systemd-analyze blame | head -5             # units by start time
$ systemd-analyze critical-chain              # the chain the boot actually waited on
```

`blame` can mislead: a slow unit that runs in parallel doesn't delay anything. `critical-chain`
shows what the boot was really waiting for. A common culprit on servers is
`systemd-networkd-wait-online.service` waiting for a network interface that never comes up.

## When a server will not boot

The recovery step depends on which stage failed. A firmware message points to a missing boot device; a GRUB
rescue prompt points to boot-loader configuration; an initramfs shell means the kernel could not mount the
root filesystem; emergency mode often points to fstab or a failed required service.

If the server is remote, use its provider console before editing the disk. Capture the exact screen or error,
then compare it with the previous boot's journal when available. Check the most recent configuration change
and keep a route back to a known-good kernel or disk snapshot. A common mistake is repairing the boot loader
when the actual failure is a mount timeout or service dependency.

> **In production: get a console first.** You can't SSH into a server that didn't finish booting. Every cloud has a way in: AWS EC2 Serial Console, Azure Serial Console, GCP serial port. Set it up and test it *before* the day you need it. The other way out: stop the VM, attach its disk to a healthy one, and fix the files there.

| You see                       | Usually                              | Fix                                                                                          |
| ----------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------- |
| "You are in emergency mode"   | A bad `/etc/fstab` line              | Log in as root, `mount -o remount,rw /`, fix `/etc/fstab`, `systemctl daemon-reload`, reboot |
| `(initramfs)` prompt          | Root filesystem not found or damaged | `fsck` the root device from that shell, or boot the previous kernel                          |
| Boot hangs on a "start job"   | A service or mount waiting forever   | Boot into rescue, find it with `journalctl -b -1`, fix or disable it                         |
| Kernel panic after an upgrade | The new kernel or its initramfs      | Pick the previous kernel in GRUB, then reinstall or remove the new one                       |

To reach a root shell when you have a console but no password: at the GRUB menu press **e**, add
`systemd.unit=rescue.target` to the end of the line starting with `linux`, and press **Ctrl+X**. That
one change boots without most services, so you can repair things.

Use a provider's serial console or rescue environment when SSH is unavailable. Before changing boot files,
record the error and make sure you can restore the disk or choose a previous kernel. A common mistake is
rebooting repeatedly without recording the failing stage; each attempt can hide the useful journal from the
previous boot.

## Mission: Write a boot report for a server that rebooted

A server restarted overnight and the team wants to know when, why, and whether everything came back. Collect the boot history, errors from the previous boot, units that failed this boot, and the boot time, into one file.

- You need: Any Linux server running systemd
- You'll have: ~/boot-report.txt

```sh
$ cat > ~/boot-report.sh <<'EOF'
#!/bin/bash
echo "== boots"; journalctl --list-boots --no-pager | tail -3
echo "== up since: $(uptime -s)"
echo "== default target: $(systemctl get-default)"
echo "== last lines of the previous boot"; journalctl -b -1 -n 15 --no-pager 2>/dev/null || echo "(no previous boot stored)"
echo "== errors in the previous boot"; journalctl -b -1 -p err --no-pager 2>/dev/null | tail -10
echo "== failed units now"; systemctl --failed --no-legend --no-pager
echo "== boot time"; systemd-analyze 2>/dev/null | head -1
EOF
$ bash ~/boot-report.sh > ~/boot-report.txt
$ head -8 ~/boot-report.txt
== boots
IDX BOOT ID                          FIRST ENTRY                 LAST ENTRY
  0 bea482c8f6f84fe4b096e875c660d327 Sun 2026-10-11 05:47:21 UTC Tue 2026-10-13 05:29:13 UTC
== up since: 2026-10-11 05:47:21
== default target: graphical.target
== last lines of the previous boot
(no previous boot stored)
== errors in the previous boot
```

Run it with `sudo` to include the system journal on machines where your user can't read it. The
last lines of the previous boot are the part to read closely: a clean shutdown ends with systemd
stopping services; a crash or power loss just stops.

## Try it

- Run `systemctl get-default` and `systemd-analyze` on your machine.
- List the slowest units with `systemd-analyze blame | head` and the critical path with `systemd-analyze critical-chain`.
- Run `journalctl --list-boots`, then read the errors of this boot with `journalctl -b -p err`.
- Read the kernel's messages with `sudo dmesg -T | head -30`.
- Read your kernel's boot options with `cat /proc/cmdline`.
- On a VM, open `/etc/default/grub` and find GRUB_TIMEOUT and GRUB_CMDLINE_LINUX_DEFAULT.

## Quiz

1. You edited /etc/default/grub. What makes the change take effect at the next boot on Ubuntu?
   - Nothing, GRUB reads the file at boot
   - **sudo update-grub, which rebuilds /boot/grub/grub.cfg** (answer)
   - sudo systemctl restart grub
   Why: GRUB reads the generated grub.cfg, not /etc/default/grub. update-grub (grub2-mkconfig -o … on RHEL) rebuilds it. GRUB is not a service, so there's nothing to restart.

2. The server rebooted overnight. How do you read the logs from before that reboot?
   - **journalctl -b -1** (answer)
   - dmesg
   - They are lost at reboot
   Why: -b -1 means the previous boot. It works when the journal is stored on disk (/var/log/journal); dmesg shows only the current boot's kernel messages.

3. What is a systemd target?
   - **A group of units that together make a system state, such as multi-user.target for a normal server** (answer)
   - The disk Linux boots from
   - A GRUB menu entry
   Why: Targets replace the old runlevels. multi-user.target is a server with networking and no desktop; graphical.target adds the desktop; rescue.target is single-user maintenance.

4. A server drops into emergency mode at boot right after you added a data disk. What is the most likely cause?
   - The kernel is broken
   - **A wrong or unavailable line in /etc/fstab** (answer)
   - GRUB was deleted
   Why: systemd cannot mount something that fstab marks as required, so it stops the boot. Fix or comment out the line, or add nofail, then reboot.

5. Which command shows which units slowed the boot down the most?
   - systemctl list-units
   - **systemd-analyze blame** (answer)
   - uptime
   Why: blame lists units by the time they took to start. critical-chain shows the chain the boot actually waited on, which is often more useful.

## Resources

- [bootup(7): the system boot-up process](https://manpages.ubuntu.com/manpages/noble/man7/bootup.7.html) (Ubuntu manpages)
- [systemd.special(7): the special targets](https://manpages.ubuntu.com/manpages/noble/man7/systemd.special.7.html) (Ubuntu manpages)
- [systemd-analyze(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/systemd-analyze.1.html) (Ubuntu manpages)
- [journalctl(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/journalctl.1.html) (Ubuntu manpages)
- [LPIC-1 objectives 101.2, 101.3 and 102.2](https://wiki.lpi.org/wiki/LPIC-1_Objectives_V5.0) (Linux Professional Institute)
