Systemd Service¶
Bikin bot lo jalan 24/7, auto-restart kalo crash.
Kenapa systemd¶
Tanpa systemd, kalo lo SSH disconnect, bot mati. Kalo VPS reboot, bot ga jalan lagi.
systemd:
- Bot jalan as background service
- Auto-restart kalo crash
- Auto-start saat VPS boot
- Logging terpusat via journalctl
- Status check via systemctl
Anatomy service file¶
[Unit]
Description=Kai Agent Bot
After=network.target
[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/agent
EnvironmentFile=/home/ubuntu/agent/.env
ExecStart=/home/ubuntu/agent/venv/bin/python main.py
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
Field breakdown¶
[Unit]
Description: human-readable name (muncul disystemctl status)After: tunggu service ini ready sebelum start.network.target= tunggu network online.
[Service]
Type:simple: process langsung, ga fork (default untuk Python)forking: process fork ke background (untuk daemon klasik)oneshot: jalan sekali terus exit (untuk init script)User: user yang run process (penting! user= ubuntu, bukan root)WorkingDirectory: cwd saat run (penting untuk relative path)EnvironmentFile: file.env(path absolute)ExecStart: command yang dijalanin (path absolute)Restart:no: never restarton-failure: restart kalo exit code != 0always: restart no matter whatRestartSec: tunggu N detik sebelum restart
[Install]
WantedBy: kapan service di-enable.multi-user.target= saat normal boot.
Create service file¶
Paste content di atas, edit sesuai path lo.
Lifecycle commands¶
Enable (auto-start saat boot)¶
Start (run sekarang)¶
Restart¶
Stop¶
Disable (ga auto-start)¶
Status¶
Output:
● kai-bot.service - Kai Agent Bot
Loaded: loaded (/etc/systemd/system/kai-bot.service; enabled)
Active: active (running) since Wed 2026-05-14 03:00:00 UTC; 2h 30min ago
Main PID: 12345 (python)
Tasks: 5 (limit: 1129)
Memory: 45.2M
CGroup: /system.slice/kai-bot.service
└─12345 /home/ubuntu/agent/venv/bin/python main.py
Is active (boolean)¶
systemctl is-active kai-bot # "active" atau "inactive"
systemctl is-enabled kai-bot # "enabled" atau "disabled"
Logs via journalctl¶
Tail logs (live)¶
-f = follow (like tail -f).
Last N lines¶
Since specific time¶
sudo journalctl -u kai-bot --since "2026-05-14 03:00"
sudo journalctl -u kai-bot --since "1 hour ago"
sudo journalctl -u kai-bot --since today
Error level only¶
Grep specific text¶
Common patterns¶
Reload service file setelah edit¶
sudo nano /etc/systemd/system/kai-bot.service
sudo systemctl daemon-reload # reload definisi
sudo systemctl restart kai-bot # apply changes
daemon-reload perlu setiap kali edit service file.
Multiple services¶
Kalo lo punya banyak agent:
sudo systemctl status kai-bot # personal agent
sudo systemctl status atlas-bot # work agent
sudo systemctl status proxy # LLM proxy lokal
Atau check semua sekaligus:
Bot dengan working dir spesifik¶
Pastikan path absolute. Python kode lo bisa pakai relative path:
Environment variables¶
Pakai file¶
Format file:
Inline¶
Restart only on failure¶
Kalo bot exit dengan code 0 (clean exit), ga restart. Kalo crash (exception, segfault, OOM), restart setelah 5 detik.
Always restart (even clean exit)¶
Hati-hati: kalo ada infinite restart loop, throttle:
Max 3 restart dalam 10 menit. Kalo lebih, systemd give up.
Resource limit¶
Untuk VPS dengan RAM kecil, batasin agent biar ga OOM full server:
Bot di-kill kalo > 500MB RAM atau >80% CPU sustained.
Security hardening¶
Untuk service yang perlu lebih secure:
[Service]
User=ubuntu
Group=ubuntu
# Read-only filesystem (kecuali tmp + writable paths)
ProtectSystem=full
ReadWritePaths=/home/ubuntu/agent/data /home/ubuntu/agent/credentials
# No access to /home other users
ProtectHome=true
# No privileged ops
NoNewPrivileges=true
# Drop capabilities
CapabilityBoundingSet=
AmbientCapabilities=
# Hide /proc
ProcSubset=pid
ProtectProc=invisible
# Restrict syscalls
SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM
Debugging¶
Service ga start¶
Common issues:
"Failed to locate executable"
Pastikan path venv python benar. Test:
"Permission denied"
"EnvironmentFile not found"
Pastikan path absolute, bukan ~/agent/.env:
"Module not found"
Pakai venv python. Kalo masih error, install di venv:
source /home/ubuntu/agent/venv/bin/activate
pip install <missing-module>
sudo systemctl restart kai-bot
Service crash loop¶
Cek error berulang. Common:
- API key invalid → fix .env
- Network down → wait, atau add retry di code
- OOM → tambah RAM atau optimize memory
Performance issue¶
Kalo memory creep, ada leak di code. Add monitoring:
import psutil
process = psutil.Process()
log.info(f"Memory: {process.memory_info().rss / 1024**2:.1f}MB")
Service file template lengkap¶
[Unit]
Description=Kai Agent Bot
Documentation=https://github.com/user/my-agent
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=ubuntu
Group=ubuntu
WorkingDirectory=/home/ubuntu/agent
EnvironmentFile=/home/ubuntu/agent/.env
ExecStart=/home/ubuntu/agent/venv/bin/python main.py
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
StartLimitInterval=600
StartLimitBurst=3
StandardOutput=journal
StandardError=journal
SyslogIdentifier=kai-bot
# Resource limits
MemoryLimit=500M
CPUQuota=80%
# Security
ProtectSystem=full
ReadWritePaths=/home/ubuntu/agent/data /home/ubuntu/agent/credentials
ProtectHome=true
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
User services (no sudo)¶
Kalo VPS ga kasih sudo (rare di managed VPS), pakai user services:
Same content, tapi tanpa User=:
[Unit]
Description=Kai Agent Bot
[Service]
Type=simple
WorkingDirectory=/home/ubuntu/agent
EnvironmentFile=/home/ubuntu/agent/.env
ExecStart=/home/ubuntu/agent/venv/bin/python main.py
Restart=on-failure
RestartSec=5
[Install]
WantedBy=default.target
Enable + start:
systemctl --user daemon-reload
systemctl --user enable kai-bot
systemctl --user start kai-bot
systemctl --user status kai-bot
Persist setelah logout:
Otherwise, user service stop saat SSH disconnect.
Cheat sheet¶
| Action | Command |
|---|---|
| Edit service | sudo nano /etc/systemd/system/kai-bot.service |
| Reload definitions | sudo systemctl daemon-reload |
| Enable auto-start | sudo systemctl enable kai-bot |
| Start now | sudo systemctl start kai-bot |
| Restart | sudo systemctl restart kai-bot |
| Stop | sudo systemctl stop kai-bot |
| Disable auto-start | sudo systemctl disable kai-bot |
| Status | sudo systemctl status kai-bot |
| Live logs | sudo journalctl -u kai-bot -f |
| Last 50 lines | sudo journalctl -u kai-bot -n 50 |
| Errors only | sudo journalctl -u kai-bot -p err |
| All services | sudo systemctl list-units --type=service |