systemd — init system на всех современных Linux. Service unit = .service file описывающий как запускать/останавливать/перезапускать daemon. Замена для supervisord, pm2 (для Node), rc.d. Auto-start на boot, auto-restart при crash, journalctl для logs, systemctl для control. Минимальный unit — 10 строк.
Ниже: пошаговая инструкция, рабочие примеры, типичные ошибки, FAQ.
systemctl daemon-reload — reload unitssystemctl enable myapp — auto-start on bootsystemctl start myapp + systemctl statusjournalctl -u myapp -f (live tail)| Сценарий | Конфиг |
|---|---|
| Простой Node.js service | [Unit]
Description=My App
After=network.target
[Service]
Type=simple
User=nodejs
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node /opt/myapp/server.js
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target |
| Python с venv | [Service]
Type=simple
User=app
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/venv/bin/python /opt/myapp/app.py
Environment="PATH=/opt/myapp/venv/bin"
Restart=on-failure |
| Systemd hardening (sandboxing) | [Service]
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/log/myapp |
| Timer (как cron) | # /etc/systemd/system/backup.timer
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
[Install]
WantedBy=timers.target |
| Reload config без restart | ExecReload=/bin/kill -HUP $MAINPID
# systemctl reload myapp |
Environment="KEY=value", не как в bashuseradd -r -s /bin/false nodejsjournalctl -u myappsystemctl daemon-reload после изменения unit → старый configsystemd — built-in Linux, zero dependencies. pm2 — specialized для Node.js (cluster mode, zero-downtime reload). На простом app — systemd.
on-failure (restart on non-zero exit) — стандарт. always — restart даже при normal exit (useful для daemon). no — только manual.
<code>TimeoutStopSec=30s</code> — systemd ждёт 30 сек перед SIGKILL. App должен handle SIGTERM и cleanly exit.
journald автоматически rotates. Settings: <code>/etc/systemd/journald.conf</code> → SystemMaxUse=1G, MaxRetentionSec=30d.