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 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 nginxListing 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=enabledTạ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.targetKí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 myappUnit 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/envService 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.targetTimer (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.targetKích hoạt timer:
sudo systemctl enable backup.timer
sudo systemctl start backup.timer
systemctl list-timersLogging 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 50Debugging Services
Check Status
systemctl status myserviceOutput 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 myserviceCommon 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 # VerifyPort already in use:
sudo ss -tulpn | grep :80 # Find process using port 80Best 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=1003. Security Hardening
[Service]
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
NoNewPrivileges=true
ReadOnlyPaths=/etc /usr4. Graceful Shutdown
[Service]
ExecStop=/bin/kill -SIGTERM $MAINPID
TimeoutStopSec=30
KillMode=mixed5. Environment Variables
[Service]
# Method 1: Inline
Environment="VAR1=value1" "VAR2=value2"
# Method 2: File
EnvironmentFile=/etc/myapp/envMonitoring và Performance
Analyze Boot Time
systemd-analyze
systemd-analyze blame # Show slowest services
systemd-analyze critical-chain # Show critical pathCheck Resource Usage
systemd-cgtop # Like top but for cgroups
systemctl show myservice --property=CPUUsageNSecKế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!
Bài viết liên quan
Linux Process Management: fork, exec, wait
Process management là core concept của Linux. Hiểu rõ fork(), exec(), và wait() giúp bạn master được system programming trên Linux.
Câu hỏi phỏng vấn Linux và Operating System cơ bản đến nâng cao
Chuẩn bị cho phỏng vấn vị trí Linux Developer/DevOps/System Engineer với các câu hỏi từ cơ bản đến nâng cao về Linux và Operating System.
Git là gì? Các lệnh thường dùng khi đi làm, Github & Gitlab, Source Control trong VSCode, Git Graph, Git Blame, Sourcetree
Tìm hiểu Git từ cơ bản đến nâng cao: các lệnh Git thiết yếu khi đi làm, làm việc với Github/Gitlab, và sử dụng các công cụ Git GUI như VSCode Source Control, Git Graph, Git Blame và Sourcetree.