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
sudo nano /etc/systemd/system/kai-bot.service
Paste content di atas, edit sesuai path lo.
Lifecycle commands
Enable (auto-start saat boot)
sudo systemctl enable kai-bot
Start (run sekarang)
sudo systemctl start kai-bot
Restart
sudo systemctl restart kai-bot
Stop
sudo systemctl stop kai-bot
Disable (ga auto-start)
sudo systemctl disable kai-bot
Status
sudo systemctl status kai-bot
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)
sudo journalctl -u kai-bot -f
-f = follow (like tail -f).
Last N lines
sudo journalctl -u kai-bot -n 50
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
sudo journalctl -u kai-bot -p err -n 50
Grep specific text
sudo journalctl -u kai-bot | grep "Telegram"
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:
sudo systemctl list-units --type=service --state=running
Bot dengan working dir spesifik
WorkingDirectory=/home/ubuntu/agent
Pastikan path absolute. Python kode lo bisa pakai relative path:
config_path = Path("config.json") # akan jadi /home/ubuntu/agent/config.json
Environment variables
Pakai file
EnvironmentFile=/home/ubuntu/agent/.env
Format file:
TELEGRAM_BOT_TOKEN=abc123
OPENAI_API_KEY=sk-...
Inline
Environment="VAR1=value1"
Environment="VAR2=value2"
Restart only on failure
Restart=on-failure
RestartSec=5
Kalo bot exit dengan code 0 (clean exit), ga restart. Kalo crash (exception, segfault, OOM), restart setelah 5 detik.
Always restart (even clean exit)
Restart=always
RestartSec=5
Hati-hati: kalo ada infinite restart loop, throttle:
Restart=always
RestartSec=5
StartLimitInterval=600
StartLimitBurst=3
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:
[Service]
MemoryLimit=500M
CPUQuota=80%
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
sudo systemctl status kai-bot
sudo journalctl -u kai-bot -n 50
Common issues:
"Failed to locate executable"
ExecStart=/home/ubuntu/agent/venv/bin/python main.py
Pastikan path venv python benar. Test:
ls -la /home/ubuntu/agent/venv/bin/python
"Permission denied"
sudo chown -R ubuntu:ubuntu /home/ubuntu/agent
chmod +x /home/ubuntu/agent/venv/bin/python
"EnvironmentFile not found"
Pastikan path absolute, bukan ~/agent/.env:
EnvironmentFile=/home/ubuntu/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
sudo journalctl -u kai-bot -n 100
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
sudo systemctl status kai-bot
# Memory: 800M
# vs free total
free -h
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:
mkdir -p ~/.config/systemd/user
nano ~/.config/systemd/user/kai-bot.service
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:
sudo loginctl enable-linger ubuntu
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 |