systemd: Quản lý Services trên Linux

Hướng dẫn toàn diện về systemd - init system và service manager hiện đại của Linux. Tạo, quản lý, và debug services

systemd: Quản lý Services trên Linux

systemd: Quản lý Services trên Linux

systemd là init system và service manager được sử dụng rộng rãi trên các Linux distributions hiện đại (Ubuntu, Fedora, Debian, Arch, etc.). Nó thay thế SysV init truyền thống và mang lại nhiều cải tiến.

Tại sao systemd?

systemd có nhiều ưu điểm so với SysV init:

  • Parallel startup: Khởi động services song song → boot nhanh hơn
  • On-demand activation: Chỉ start services khi cần
  • Dependency management: Tự động quản lý dependencies
  • Logging: Tích hợp journald cho central logging
  • Unified interface: Một tool để quản lý tất cả

Basic Commands

Quản lý Services

# Start service
sudo systemctl start nginx
 
# Stop service
sudo systemctl stop nginx
 
# Restart service
sudo systemctl restart nginx
 
# Reload configuration (không restart)
sudo systemctl reload nginx
 
# Enable service (auto-start at boot)
sudo systemctl enable nginx
 
# Disable service
sudo systemctl disable nginx
 
# Check status
systemctl status nginx

Listing Services

# List all services
systemctl list-units --type=service
 
# List running services
systemctl list-units --type=service --state=running
 
# List failed services
systemctl list-units --type=service --state=failed
 
# List enabled services
systemctl list-unit-files --type=service --state=enabled

Tạo Service Unit File

Service được định nghĩa trong unit files (.service files).

Location của Unit Files

  • /etc/systemd/system/: User-defined services (highest priority)
  • /usr/lib/systemd/system/: Package-installed services
  • /run/systemd/system/: Runtime services

Ví dụ: Simple Service

Tạo một service cho Python web app:

# /etc/systemd/system/myapp.service
 
[Unit]
Description=My Python Web Application
After=network.target
 
[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/opt/myapp
Environment="PATH=/opt/myapp/venv/bin"
ExecStart=/opt/myapp/venv/bin/python app.py
Restart=always
RestartSec=10
 
[Install]
WantedBy=multi-user.target

Kích hoạt Service

# Reload systemd để nhận unit file mới
sudo systemctl daemon-reload
 
# Start service
sudo systemctl start myapp
 
# Enable auto-start at boot
sudo systemctl enable myapp
 
# Check status
systemctl status myapp

Unit File Sections

[Unit] Section

[Unit]
Description=My Service Description
Documentation=https://example.com/docs
After=network.target postgresql.service
Requires=postgresql.service
  • Description: Mô tả service
  • After: Start sau các services này
  • Before: Start trước các services này
  • Requires: Dependencies bắt buộc
  • Wants: Dependencies optional

[Service] Section

[Service]
Type=simple
ExecStart=/usr/bin/my-daemon
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -TERM $MAINPID
Restart=on-failure
RestartSec=5s
User=myuser
Group=mygroup
Environment="VAR1=value1" "VAR2=value2"
EnvironmentFile=/etc/myapp/env

Service Types

  • simple (default): Process chạy trong foreground
  • forking: Process fork vào background (daemon)
  • oneshot: Process chạy xong rồi exit
  • notify: Process gửi notification khi ready
  • idle: Đợi cho đến khi không có job nào khác

Restart Policies

  • no: Không tự động restart
  • on-success: Restart nếu exit code = 0
  • on-failure: Restart nếu exit code ≠ 0
  • always: Luôn restart

[Install] Section

[Install]
WantedBy=multi-user.target
RequiredBy=other-service.service
  • WantedBy: Được start bởi target nào
  • RequiredBy: Required bởi service nào

Advanced Examples

Web Application với Gunicorn

# /etc/systemd/system/webapp.service
 
[Unit]
Description=Gunicorn Web Application
After=network.target
 
[Service]
Type=notify
User=webapp
Group=webapp
WorkingDirectory=/var/www/webapp
Environment="PATH=/var/www/webapp/venv/bin"
ExecStart=/var/www/webapp/venv/bin/gunicorn \
    --workers 4 \
    --bind unix:/run/webapp.sock \
    --access-logfile - \
    --error-logfile - \
    wsgi:application
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true
Restart=on-failure
 
[Install]
WantedBy=multi-user.target

Timer (Cron Alternative)

systemd timers là alternative hiện đại cho cron jobs.

# /etc/systemd/system/backup.service
 
[Unit]
Description=Database Backup
 
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup-db.sh
User=backup
# /etc/systemd/system/backup.timer
 
[Unit]
Description=Daily Database Backup Timer
 
[Timer]
OnCalendar=daily
OnCalendar=*-*-* 02:00:00
Persistent=true
 
[Install]
WantedBy=timers.target

Kích hoạt timer:

sudo systemctl enable backup.timer
sudo systemctl start backup.timer
systemctl list-timers

Logging với journalctl

systemd sử dụng journald cho system logging.

# Xem logs của một service
sudo journalctl -u nginx
 
# Follow logs (like tail -f)
sudo journalctl -u nginx -f
 
# Logs từ boot hiện tại
sudo journalctl -b
 
# Logs trong khoảng thời gian
sudo journalctl --since "2024-01-01" --until "2024-01-02"
 
# Logs với priority level
sudo journalctl -p err
 
# Reverse order (newest first)
sudo journalctl -r
 
# Show last N lines
sudo journalctl -u nginx -n 50

Debugging Services

Check Status

systemctl status myservice

Output hiển thị:

  • Active state (running, failed, etc.)
  • Process ID
  • Latest log entries
  • Memory usage

Why Service Failed?

# Xem detailed logs
sudo journalctl -u myservice -n 100
 
# Check if unit file valid
systemd-analyze verify /etc/systemd/system/myservice.service
 
# List dependencies
systemctl list-dependencies myservice

Common Issues

Service fails immediately:

  • Check ExecStart path and permissions
  • Check User/Group exist
  • Check WorkingDirectory exists

Service doesn't auto-start:

sudo systemctl enable myservice
systemctl is-enabled myservice  # Verify

Port already in use:

sudo ss -tulpn | grep :80  # Find process using port 80

Best Practices

1. Use Specific User

[Service]
User=myapp
Group=myapp
# Never run as root unless absolutely necessary!

2. Set Resource Limits

[Service]
MemoryLimit=512M
CPUQuota=50%
TasksMax=100

3. Security Hardening

[Service]
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
NoNewPrivileges=true
ReadOnlyPaths=/etc /usr

4. Graceful Shutdown

[Service]
ExecStop=/bin/kill -SIGTERM $MAINPID
TimeoutStopSec=30
KillMode=mixed

5. Environment Variables

[Service]
# Method 1: Inline
Environment="VAR1=value1" "VAR2=value2"
 
# Method 2: File
EnvironmentFile=/etc/myapp/env

Monitoring và Performance

Analyze Boot Time

systemd-analyze
systemd-analyze blame  # Show slowest services
systemd-analyze critical-chain  # Show critical path

Check Resource Usage

systemd-cgtop  # Like top but for cgroups
systemctl show myservice --property=CPUUsageNSec

Kết luận

systemd là công cụ mạnh mẽ để quản lý services trên Linux. Key points:

  • Unit files định nghĩa services
  • systemctl để quản lý services
  • journalctl để xem logs
  • Timers thay thế cron jobs
  • Security features để hardening services

Master systemd giúp bạn trở thành Linux admin chuyên nghiệp!

5 min read
LinuxsystemdServicesSystem Administration

Bài viết liên quan