hoatranlab.io.vn Zalo: 0917516878 Hotline: 0917516878 [email protected]
HoaTranLab Logo HoaTranLab
Linux Bible 11th Edition • Chapter 15

Starting and Stopping Services

Nắm vững systemd — hệ thống khởi tạo hiện đại của Linux — để quản lý toàn bộ vòng đời dịch vụ: start, stop, restart, enable, disable và cấu hình target unit.

systemctl Unit Types Target Units Service Files
Bắt đầu học
A. Mục Tiêu Chương

Sau chương này bạn sẽ hiểu

systemd Basics

Hiểu systemd là gì, tại sao nó thay thế SysVinit, cách nó khởi tạo song song các dịch vụ và tại sao PID 1 luôn là systemd.

12 Unit Types

Nắm 12 loại unit trong systemd: service, target, socket, mount, timer, device, path, snapshot, swap, slice, scope, automount.

systemctl Commands

Thành thạo systemctl: start, stop, restart, reload, status, enable, disable, mask, unmask, daemon-reload, list-units.

Target Units

Hiểu multi-user.target, graphical.target, Wants vs Requires, AllowIsolate, và cách set default.target để chọn runlevel mặc định.

Service Unit Files

Đọc và viết file cấu hình .service: section [Unit], [Service], [Install], các directive After=, ExecStart=, WantedBy=, Restart=.

SysVinit Compat

Tương thích ngược: lệnh service (SysVinit), runlevel0-6.target symlinks, lệnh runlevel, chuyển đổi giữa các runlevel target.

B. Lý Thuyết Cốt Lõi

systemd — Hiểu từ nền tảng

1 Nhận diện systemd — PID 1

systemd là init daemon hiện đại thay thế SysVinit. Nó luôn chạy với PID 1 và có thể khởi động các dịch vụ song song, giảm thời gian boot đáng kể. Kiểm tra bằng ps -e | head:

Terminal — root@server

# ps -e | head

PID TTY TIME CMD

1 ? 00:04:36 /usr/lib/systemd/system...

2 ? 00:00:03 [kthreadd]

3 ? 00:00:15 [pool_workqueue_release]

# Trên Ubuntu, /sbin/init thường là symlink tới systemd:

# ls -ls /sbin/init

0 lrwxrwxrwx 1 root root 22 Aug 8 10:51 /sbin/init -> ../lib/systemd/systemd

2 12 Loại Unit trong systemd

Một unit là đơn vị quản lý trong systemd — gồm tên, loại, và file cấu hình. systemd có 12 loại unit:

service

Quản lý daemon

target

Nhóm các unit khác

socket

IPC socket activation

mount

Mount point

timer

Cron thay thế

device

Kernel device

path

File system path watch

automount

Auto mount khi truy cập

swap

Swap space

slice

Resource control group

scope

External processes

snapshot

Saved systemd state

Terminal — liệt kê service units

# systemctl list-unit-files --type=service

UNIT FILE STATE PRESET

accounts-daemon.service enabled enabled

alsa-restore.service static -

alsa-utils.service masked enabled

anacron.service enabled enabled

apparmor.service enabled enabled

bluetooth.service enabled enabled

...

287 unit files listed.

# Trạng thái: enabled | disabled | static | alias

# static = luôn bật, không thể disable dù là root

# alias = symlink tới tên khác

3 Cấu trúc Service Unit File

File cấu hình dịch vụ nằm tại /lib/systemd/system/ hoặc /etc/systemd/system/. Ví dụ file sshd.service trên Fedora:

Terminal — /lib/systemd/system/sshd.service

# cat /lib/systemd/system/sshd.service

[Unit]

Description=OpenSSH server daemon

Documentation=man:sshd(8) man:sshd_config(5)

After=network.target sshd-keygen.target

Wants=sshd-keygen.target

Wants=ssh-host-keys-migration.service

[Service]

Type=notify

Environment=OPTIONS=

EnvironmentFile=-/etc/sysconfig/sshd

ExecStart=/usr/sbin/sshd -D $OPTIONS

ExecReload=/bin/kill -HUP $MAINPID

KillMode=process

Restart=on-failure

RestartSec=42s

[Install]

WantedBy=multi-user.target

[Unit] directives

  • Description= — Mô tả dịch vụ
  • Documentation= — Man pages liên quan
  • After= — Thứ tự khởi động (chờ unit nào trước)
  • Wants= — Đề nghị unit khác, không bắt buộc
  • Requires= — Bắt buộc unit khác phải chạy

[Service] + [Install]

  • ExecStart= — Lệnh khởi động dịch vụ
  • ExecReload= — Lệnh reload config
  • Restart=on-failure — Tự khởi lại khi lỗi
  • Type=notify — Dịch vụ báo systemd khi sẵn sàng
  • WantedBy= — Target sẽ kích hoạt service này

4 Target Units và Runlevel Compatibility

Target unit là nhóm các unit khác. multi-user.target tương đương runlevel 3, graphical.target tương đương runlevel 5. Symlinks trong /lib/systemd/system/ ánh xạ runlevel cũ sang target mới:

Terminal — Runlevel symlinks

# ls -l /lib/systemd/system/runlevel*.target

lrwxrwxrwx. 1 root root 15 Apr 9 04:25 runlevel0.target -> poweroff.target

lrwxrwxrwx. 1 root root 13 Apr 9 04:25 runlevel1.target -> rescue.target

lrwxrwxrwx. 1 root root 17 Apr 9 04:25 runlevel2.target -> multi-user.target

lrwxrwxrwx. 1 root root 17 Apr 9 04:25 runlevel3.target -> multi-user.target

lrwxrwxrwx. 1 root root 17 Apr 9 04:25 runlevel4.target -> multi-user.target

lrwxrwxrwx. 1 root root 16 Apr 9 04:25 runlevel5.target -> graphical.target

lrwxrwxrwx. 1 root root 13 Apr 9 04:25 runlevel6.target -> reboot.target

# Xem và set default target:

# systemctl get-default

multi-user.target

# systemctl set-default graphical.target

Removed "/etc/systemd/system/default.target".

Created symlink /etc/systemd/system/default.target -> /usr/lib/systemd/system/graphical.target.

# runlevel

3 5

# previous=3 (multi-user), current=5 (graphical)

5 Quản lý dịch vụ với systemctl

Ví dụ thực tế với dịch vụ cups.service (CUPS Scheduler — in ấn):

Terminal — systemctl stop / start / enable / disable

# === STOP dịch vụ (ngay lập tức, không ảnh hưởng boot) ===

# systemctl stop cups.service

# systemctl status cups.service

○ cups.service - CUPS Scheduler

Loaded: loaded (/usr/lib/systemd/system/cups.service; enabled; preset: enabled)

Active: inactive (dead) since Thu 2025-01-09 23:09:36 EST; 3s ago

Jan 09 23:09:36 systemd[1]: cups.service: Deactivated successfully.

Jan 09 23:09:36 systemd[1]: Stopped cups.service - CUPS Scheduler.

# === START dịch vụ ===

# systemctl start cups.service

# systemctl status cups.service

● cups.service - CUPS Scheduler

Loaded: loaded (/usr/lib/systemd/system/cups.service; enabled; preset: enabled)

Active: active (running) since Thu 2025-01-09 23:11:10 EST; 3s ago

Main PID: 430868 (cupsd)

CGroup: /system.slice/cups.service

└─430868 /usr/sbin/cupsd -l

# === ENABLE — tự khởi động khi boot ===

# systemctl enable cups.service

Synchronizing state of cups.service with SysV service script...

Created symlink /etc/systemd/system/printer.target.wants/cups.service -> /usr/lib/systemd/system/cups.service.

Created symlink /etc/systemd/system/multi-user.target.wants/cups.service -> /usr/lib/systemd/system/cups.service.

# === DISABLE — không tự khởi động khi boot ===

# systemctl disable cups.service

Removed "/etc/systemd/system/sockets.target.wants/cups.socket".

Removed "/etc/systemd/system/multi-user.target.wants/cups.service".

Disabling 'cups.service', but its triggering units are still active: cups.socket

# === RESTART vs RELOAD ===

# systemctl restart cups.service

# Dừng rồi khởi lại hoàn toàn

# systemctl daemon-reload

# Reload config systemd — không restart dịch vụ

# === MASK — ngăn hoàn toàn, kể cả dependency ===

# systemctl mask MyExample.service

# Link service -> /dev/null, không thể start theo bất kỳ cách nào

# systemctl unmask MyExample.service

# Gỡ mask để dùng lại

Lệnh service — Tương thích SysVinit

Terminal — Legacy service command

# Cú pháp: service <tên-dịch-vụ> <hành-động>

# service cups stop

# service cups status

○ cups.service - CUPS Scheduler

Active: inactive (dead) since Thu 2025-01-09 22:59:54 EST; 3s ago

Jan 09 22:59:54 Admin-ubuntu-20 systemd[1]: Stopped cups.service - CUPS Scheduler.

# service cups start

● cups.service - CUPS Scheduler

Active: active (running) since Thu 2025-01-09 23:06:10 EST; 3s ago

Main PID: 430494 (cupsd)

Jan 09 23:06:10 systemd[1]: Started cups.service-CUPS Scheduler.

# Ghi nhớ: service <name> <action> (ngược thứ tự so với systemctl)

C. Thực Hành

Lab: Quản lý Services với systemctl

Thực hành trên Fedora/RHEL/Ubuntu — cần quyền root

1

Kiểm tra systemd và liệt kê dịch vụ đang chạy

Xác nhận PID 1 là systemd, sau đó xem tất cả service đang active:

Terminal

# ps -e | head

# Kiểm tra PID 1

# systemctl list-units --type=service --state=active

# Xem tất cả service đang chạy

# systemctl list-unit-files --type=service | head -20

# Xem trạng thái file cấu hình

2

Đọc file cấu hình SSH service

Xem cấu trúc file .service và hiểu các directive:

Terminal

# cat /lib/systemd/system/sshd.service

# Đọc [Unit], [Service], [Install]

# systemctl status sshd.service

# Xem trạng thái hiện tại

# systemctl show --property "Wants" multi-user.target | less

# Xem tất cả unit thuộc multi-user.target

3

Stop / Start cups.service

Cài đặt CUPS nếu chưa có, thực hành stop/start và quan sát trạng thái:

Terminal

# Ubuntu: apt install cups | Fedora: dnf install cups

# systemctl status cups.service

# systemctl stop cups.service

# systemctl status cups.service

# Quan sát: Active: inactive (dead)

# systemctl start cups.service

# systemctl status cups.service

# Quan sát: Active: active (running), Main PID

4

Enable / Disable service — kiểm soát boot

Thực hành enable/disable và quan sát symlink được tạo/xóa:

Terminal

# systemctl disable cups.service

# Quan sát các symlink bị xóa

# systemctl is-enabled cups.service

disabled

# systemctl enable cups.service

# Quan sát symlink mới trong /etc/systemd/system/

# ls /etc/systemd/system/multi-user.target.wants/ | grep cups

cups.service

5

Kiểm tra default target và runlevel

Xem target mặc định, thay đổi và xác minh:

Terminal

# systemctl get-default

multi-user.target

# ls -l /etc/systemd/system/default.target

lrwxrwxrwx. 1 root root 36 ... default.target -> /lib/systemd/system/runlevel3.target

# runlevel

N 3

# N = không có runlevel trước (fresh boot)

6

Tạo custom service unit đơn giản

Tạo một service unit tùy chỉnh và register với systemd:

Terminal

# Tạo file unit mới:

# vim /etc/systemd/system/myscript.service

[Unit]

Description=My Custom Script Service

After=network.target

[Service]

ExecStart=/usr/local/bin/myscript.sh

Restart=on-failure

[Install]

WantedBy=multi-user.target

# Kích hoạt service:

# systemctl daemon-reload

# systemctl enable --now myscript.service

# systemctl status myscript.service

D. Bài Tập Ôn Luyện

Câu hỏi tự kiểm tra

Q1.systemd thay thế SysVinit với ưu điểm gì chính?

systemd khởi động các dịch vụ song song (parallel), trong khi SysVinit khởi động tuần tự theo thứ tự cố định. Nếu một dịch vụ bị kẹt với SysVinit, tất cả dịch vụ sau phải chờ — dù chúng không có dependency. systemd giải quyết vấn đề này, giảm thời gian boot đáng kể. Ngoài ra systemd quản lý nhiều loại unit hơn (không chỉ service), có socket activation, và tích hợp journald cho logging tập trung.

Q2.Sự khác nhau giữa systemctl stopsystemctl disable?

stop dừng dịch vụ ngay lập tức (trong phiên hiện tại) nhưng dịch vụ vẫn được cấu hình để tự khởi động khi boot (nếu đang enabled). disable xóa symlinks trong /etc/systemd/system/ để dịch vụ không tự khởi động khi boot, nhưng dịch vụ đang chạy vẫn tiếp tục chạy (cần dùng stop để dừng ngay). Để vừa dừng vừa không cho boot: dùng cả hai lệnh.

Q3.Trạng thái static trong systemctl list-unit-files có nghĩa gì?

static (statically enabled) nghĩa là dịch vụ được bật mặc định và không thể disable kể cả với quyền root. Dịch vụ có trạng thái static thường là các dịch vụ hệ thống cơ bản mà systemd luôn cần (ví dụ: dbus.service). Nếu chạy systemctl disable dbus.service, lệnh sẽ bị bỏ qua. Để ngăn static service chạy, phải dùng systemctl mask.

Q4.Trong file sshd.service, directive WantedBy=multi-user.target có ý nghĩa gì?

Directive này ở section [Install] cho biết: khi dịch vụ sshd được enable, systemd sẽ tạo symlink sshd.service vào thư mục /etc/systemd/system/multi-user.target.wants/. Điều này có nghĩa là khi multi-user.target được kích hoạt (khi boot ở runlevel 3 hoặc 4), nó sẽ tự động khởi động sshd. Đây là cơ chế enable/disable hoạt động: chỉ là tạo hoặc xóa symlink.

Q5.Sự khác nhau giữa Wants=Requires= trong target unit?

Wants: Kích hoạt các unit được liệt kê khi target được kích hoạt. Nếu chúng thất bại hoặc không thể khởi động, target unit vẫn tiếp tục bình thường — không có vấn đề gì. Requires: Nghiêm ngặt hơn. Nếu bất kỳ unit nào trong danh sách thất bại hoặc không thể khởi động, toàn bộ unit (nhóm) sẽ bị deactivate. Ví dụ: multi-user.target Requires basic.target — nếu basic.target lỗi, multi-user.target cũng bị hủy.

Q6.runlevel2.target, runlevel3.target, runlevel4.target đều trỏ tới target nào?

Cả ba đều là symlink trỏ tới multi-user.target. Lý do là các runlevel 2, 3, 4 của SysVinit đều là chế độ multi-user không có GUI, phù hợp với multi-user.target trong systemd. Riêng: runlevel0 → poweroff.target, runlevel1 → rescue.target, runlevel5 → graphical.target, runlevel6 → reboot.target.

Q7.Lệnh nào dùng để đặt default target là graphical.target?

Dùng lệnh: systemctl set-default graphical.target. Lệnh này sẽ xóa symlink cũ của /etc/systemd/system/default.target và tạo symlink mới trỏ tới /usr/lib/systemd/system/graphical.target. Để xác nhận: systemctl get-default sẽ trả về graphical.target. Thay đổi có hiệu lực sau khi reboot.

Q8.Sự khác nhau giữa systemctl restartsystemctl daemon-reload?

restart: Dừng hoàn toàn rồi khởi động lại dịch vụ cụ thể — xử lý đang chờ bị hủy bỏ. daemon-reload: Không restart dịch vụ nào — chỉ báo systemd đọc lại tất cả file unit (.service) đã thay đổi trong /etc/systemd/system//lib/systemd/system/. Dùng daemon-reload khi bạn chỉnh sửa hoặc thêm file unit, sau đó mới enable/start. Với server bận rộn, reload tốt hơn restart vì không ngắt các kết nối đang hoạt động.

Q9.Khi nào dùng systemctl mask thay vì systemctl disable?

Dùng mask khi muốn ngăn hoàn toàn dịch vụ chạy, kể cả khi có dịch vụ khác cố kích hoạt nó qua dependency. mask tạo symlink service → /dev/null, nên ngay cả khi có dependency, dịch vụ sẽ không thể start. Dùng disable khi chỉ muốn dịch vụ không tự boot, nhưng vẫn cho phép start thủ công hoặc qua dependency. Ví dụ: muốn thay NetworkManager bằng network.service, cần mask NetworkManager để tránh dependency từ dịch vụ khác kích hoạt nó.

Q10.File cấu hình dịch vụ systemd nằm ở đâu, và thư mục nào có độ ưu tiên cao hơn?

Có hai vị trí chính: /lib/systemd/system/ (hoặc /usr/lib/systemd/system/) — file do gói phần mềm cài đặt, và /etc/systemd/system/ — file tùy chỉnh của admin. /etc/systemd/system/độ ưu tiên cao hơn — nếu cùng tên file tồn tại ở cả hai nơi, file trong /etc/ sẽ ghi đè. Đây là lý do: để customize service, copy file từ /lib/ sang /etc/systemd/system/ rồi chỉnh sửa, sau đó chạy daemon-reload.

Linux Assistant

Chapter 15 — systemd

Xin chào! Tôi có thể giải đáp các câu hỏi về systemd, systemctl, service unit files và quản lý dịch vụ Linux. Bạn cần hỏi gì?