# Tham Khảo Nhanh systemd

*Quản lý dịch vụ, units, timers, journalctl*

> Source: systemd Documentation (systemd.io) · MIT

## Quản lý dịch vụ

### Lệnh dịch vụ cơ bản

```
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
systemctl reload nginx    # reload config
systemctl status nginx
```

### Bật / Tắt

```
systemctl enable nginx    # start at boot
systemctl disable nginx   # remove from boot
systemctl enable --now nginx  # enable + start
systemctl is-enabled nginx
```

### Trạng thái dịch vụ

| Command | Description |
|---------|-------------|
| `active (running)` | Dịch vụ đang chạy bình thường |
| `active (exited)` | Đã chạy một lần và thoát thành công |
| `inactive (dead)` | Dịch vụ đã dừng |
| `failed` | Dịch vụ bị crash hoặc thoát với lỗi |
| `activating` | Dịch vụ đang khởi động |

## Unit Files

### Vị trí Unit File

| Command | Description |
|---------|-------------|
| `/etc/systemd/system/` | Units do admin tạo (ưu tiên cao nhất) |
| `/run/systemd/system/` | Units tạo trong runtime |
| `/usr/lib/systemd/system/` | Units cài đặt từ package |
| `~/.config/systemd/user/` | Units cấp người dùng |

### Unit Service cơ bản

```
[Unit]
Description=My Application
After=network.target
[Service]
ExecStart=/usr/bin/myapp --config /etc/myapp.conf
Restart=on-failure
User=appuser
[Install]
WantedBy=multi-user.target
```

### Áp dụng thay đổi

```
systemctl daemon-reload   # reload unit files
systemctl restart myapp   # apply changes
```

## Timers

### Timer Unit

```
[Unit]
Description=Run backup daily
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
```

### Cú pháp OnCalendar

| Command | Description |
|---------|-------------|
| `*-*-* 02:00:00` | Mỗi ngày lúc 2 giờ sáng |
| `Mon *-*-* 09:00:00` | Mỗi thứ Hai lúc 9 giờ sáng |
| `*-*-01 00:00:00` | Ngày đầu tiên mỗi tháng |
| `hourly / daily / weekly` | Lịch viết tắt |

### Quản lý Timer

```
systemctl list-timers --all
systemctl start backup.timer
systemctl enable backup.timer
systemd-analyze calendar "daily"
```

## Targets

### Targets phổ biến

| Command | Description |
|---------|-------------|
| `multi-user.target` | Khởi động bình thường, nhiều người dùng, không GUI |
| `graphical.target` | Desktop GUI đầy đủ |
| `rescue.target` | Chế độ rescue một người dùng |
| `emergency.target` | Shell tối thiểu, chỉ root |
| `network-online.target` | Mạng đã được cấu hình đầy đủ |
| `timers.target` | Tất cả các timer units sẵn sàng |

### Lệnh Target

```
systemctl get-default
systemctl set-default multi-user.target
systemctl isolate rescue.target
systemctl list-dependencies graphical.target
```

## Journalctl

### Xem logs

```
journalctl -u nginx        # logs for unit
journalctl -u nginx -f     # follow (tail)
journalctl -u nginx --no-pager
journalctl -b              # current boot only
```

### Lọc logs

```
journalctl --since "2026-03-01"
journalctl --since "1 hour ago"
journalctl -p err          # errors and above
journalctl _PID=1234
```

### Mức độ ưu tiên

| Command | Description |
|---------|-------------|
| `emerg (0)` | Hệ thống không thể dùng được |
| `alert (1)` | Cần hành động ngay |
| `crit (2)` | Tình trạng nghiêm trọng |
| `err (3)` | Tình trạng lỗi |
| `warning (4)` | Tình trạng cảnh báo |
| `info (6)` | Thông tin |
| `debug (7)` | Thông điệp debug |

### Bảo trì Log

```
journalctl --disk-usage
journalctl --vacuum-size=500M
journalctl --vacuum-time=30d
```

## Mạng

### networkctl

```
networkctl list
networkctl status eth0
networkctl up eth0
networkctl down eth0
```

### systemd-resolve

```
resolvectl status
resolvectl query example.com
resolvectl flush-caches
resolvectl statistics
```

### Chờ mạng

```
# In unit file [Unit] section:
After=network-online.target
Wants=network-online.target
```

## Mounts

### Mount Unit

```
[Unit]
Description=Mount data volume
[Mount]
What=/dev/sdb1
Where=/mnt/data
Type=ext4
Options=defaults,noatime
[Install]
WantedBy=multi-user.target
```

### Automount Unit

```
[Unit]
Description=Automount data on access
[Automount]
Where=/mnt/data
TimeoutIdleSec=300
[Install]
WantedBy=multi-user.target
```

### Quy ước đặt tên

| Command | Description |
|---------|-------------|
| `/mnt/data` | File unit: `mnt-data.mount` |
| `/var/lib/app` | File unit: `var-lib-app.mount` |

*Đường dẫn mount với `/` thay bằng `-`, bỏ dấu gạch đầu*

## Môi trường

### Thiết lập biến môi trường

```
[Service]
Environment=APP_ENV=production
Environment=PORT=8080
EnvironmentFile=/etc/myapp/env
```

### Định dạng file môi trường

```
# /etc/myapp/env
APP_ENV=production
DATABASE_URL=postgres://localhost/db
SECRET_KEY=changeme
```

### Tăng cường bảo mật Service

| Command | Description |
|---------|-------------|
| `ProtectSystem=strict` | Filesystem chỉ đọc trừ các đường dẫn được phép |
| `ProtectHome=true` | Ẩn /home, /root, /run/user |
| `NoNewPrivileges=true` | Ngăn leo thang đặc quyền |
| `PrivateTmp=true` | /tmp riêng biệt cho dịch vụ |
| `ReadWritePaths=/var/lib/myapp` | Cho phép ghi vào đường dẫn cụ thể |

## Dependencies

### Chỉ thị thứ tự và yêu cầu

| Command | Description |
|---------|-------------|
| `After=b.service` | Khởi động sau b (chỉ thứ tự) |
| `Before=b.service` | Khởi động trước b (chỉ thứ tự) |
| `Requires=b.service` | Phụ thuộc bắt buộc; thất bại nếu b thất bại |
| `Wants=b.service` | Phụ thuộc mềm; không thất bại nếu b thất bại |
| `BindsTo=b.service` | Dừng khi b dừng |
| `Conflicts=b.service` | Không thể chạy đồng thời với b |

### Kiểm tra Dependencies

```
systemctl list-dependencies nginx
systemctl list-dependencies --reverse nginx
systemd-analyze dot nginx.service | dot -Tsvg > deps.svg
```

## Các mẫu thường dùng

### Chính sách khởi động lại

| Command | Description |
|---------|-------------|
| `Restart=no` | Không bao giờ khởi động lại (mặc định) |
| `Restart=on-failure` | Khởi động lại khi thoát với mã khác 0 |
| `Restart=always` | Luôn khởi động lại (cho daemons) |
| `RestartSec=5` | Đợi 5 giây trước khi khởi động lại |
| `StartLimitBurst=3` | Số lần khởi động lại tối đa trong khoảng thời gian |
| `StartLimitIntervalSec=60` | Khoảng thời gian đếm burst |

### Override mà không sửa file gốc

```
systemctl edit nginx  # creates drop-in
# /etc/systemd/system/nginx.service.d/override.conf
systemctl cat nginx   # show effective config
systemctl revert nginx  # remove overrides
```

### Phân tích hệ thống

```
systemd-analyze                  # boot time
systemd-analyze blame            # per-unit time
systemd-analyze critical-chain
systemctl list-units --failed
```
