π Table of Contents
- 1. Project Structure Setup
- 2. Virtual Environment Configuration
- 3. Systemd Service Creation
- 4. User and Permissions Management
- 5. Common Issues and Solutions
- 6. Monitoring and Logging
- 7. Code Updates and Maintenance
- 8. Security Best Practices
- 9. Advanced Configurations
- 10 Troubleshooting
1. Project Structure Setup
Prerequisites
- VPS with Debian/Ubuntu, Linux (see the key wins of VSP vs other cloud solutions for code run)
- SSH access
- Basic Linux commands
We call our project AI Diet Planner, so corresponding folder contains the code files. We organize your Python application in a clean directory structure:
/opt/ai-diet-planner/
βββ main.py
βββ requirements.txt
βββ .venv/
βββ logs/
1.1 Create Project Directory
sudo mkdir -p /opt/ai-diet-planner
sudo chown $USER:$USER /opt/ai-diet-planner
cd /opt/ai-diet-planner
1.2π§ Code clone at VPS
Since you already own the infrastructure, hereβs the optimal path:
- Install dependenciesΒ on your VPS:
sudo apt update && sudo apt install -y python3-venv git
- Deploy your code:
git clone https://github.com/your/project.git /opt/ai-diet-planner
cd /opt/ai-diet-planner
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
2. Virtual Environment Configuration
Isolate dependencies using Python virtual environments:
# Create virtual environment
python3 -m venv .venv
# Activate virtual environment
source .venv/bin/activate
# Install dependencies
pip install -r requirements.txt
# Or for Telegram bot:
pip install python-telegram-bot
# Make script executable
chmod +x main.py
3. Systemd Service Creation
Create a systemd service file for daemon management:
sudo nano /etc/systemd/system/ai-diet-planner.service
3.1 Service File Template
[Unit]
Description=AI Diet Planner
After=network.target
[Service]
Type=simple
User=appuser
Group=appuser
WorkingDirectory=/opt/ai-diet-planner
ExecStart=/opt/ai-diet-planner/.venv/bin/python /opt/ai-diet-planner/main.py
Restart=always
RestartSec=10
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target
4. User and Permissions Management
Create a dedicated system user for security, its name will be appuser:
# Create system user
sudo useradd --system --no-create-home --shell /usr/sbin/nologin appuser
# Set proper ownership
sudo chown -R appuser:appuser /opt/ai-diet-planner
# Verify user creation
id appuser
π Security Note: Always run your daemon under a non-root user (create
appuser
withsudo adduser appuser
), and usesudo systemctl edit myapp
to setUser=appuser
in the service file. Never run daemons as root!
Question | Answer | Reason |
Who runs systemctl commands? | Root | System administration requires root privileges |
Does service run as root? | No | Service file specifies User=appuser |
Need virtualenv activated? | No | Service file uses absolute path to venv’s Python: ExecStart=/opt/ai-diet-planner/.venv/bin/python |
Where to run commands? | Anywhere | systemctl doesn’t depend on current directory or environment |
5. Common Issues and Solutions
5.1 Module Import Errors
Error: ModuleNotFoundError: No module named ‘telegram’
# Wrong package installed
pip uninstall telegram
pip install python-telegram-bot
5.2 Permission Issues
Error: Failed to determine user credentials
# Verify user exists
id appuser
# Fix ownership
sudo chown -R appuser:appuser /opt/ai-diet-planner
5.3 File Mode Changes
Git shows file mode changes (100644 β 100755)
# Commit the change if intentional
git add main.py
git commit -m "Make main.py executable"
6. Monitoring and Logging
Monitor your daemon with systemd journal:
# Check service status
sudo systemctl status ai-diet-planner
# View live logs
sudo journalctl -u ai-diet-planner -f
# View recent logs
sudo journalctl -u ai-diet-planner --since "1 hour ago"
# Export logs for analysis
sudo journalctl -u ai-diet-planner --since "1 day ago" > logs.txt
7. Code Updates and Maintenance
7.1 Graceful update by restart
Update your application code safely:
# Pull latest code
cd /opt/ai-diet-planner
sudo -u appuser git pull origin main
# Update dependencies if needed
sudo -u appuser /opt/ai-diet-planner/.venv/bin/pip install -r requirements.txt
# Restart service
sudo systemctl restart ai-diet-planner
# Verify service is running
sudo systemctl status ai-diet-planner
7.2 Automatic updates
π Automated Updates (Optional)
For production, we should consider setting up:
- Git hooks for automatic deployment
- CI/CD pipeline with GitHub Actions
- Scheduled updates with cron jobs
We pull from repo as appuser. Example cron job for daily updates:
# Add to crontab: sudo crontab -e
02 * * * cd /opt/ai-diet-planner && sudo -u appuser git pull && systemctl restart ai-diet-planner
8. Security Best Practices
- β Run services as unprivileged users
- β Use virtual environments for isolation
- β Set proper file permissions and ownership
- β Use system users (no passwords, no login)
- β Limit service resources with systemd
8.1 Resource Limiting
adding to /etc/systemd/system/ai-diet-planner.service
file:
sudo systemctl edit ai-diet-planner
[Service]
MemoryMax=200M
CPUQuota=50%
9. Advanced Configurations
9.1 Environment Variables
# Create environment file
sudo nano /etc/ai-diet-planner.env
TOKEN=your_secret_token
DEBUG=false
# Reference in service file
EnvironmentFile=/etc/ai-diet-planner.env
9.2 Automated Backups
#!/bin/bash
# backup-script.sh
DATE=$(date +%Y%m%d)
tar -czf /backup/ai-diet-$DATE.tar.gz /opt/ai-diet-planner/
# Add to crontab
0 3 * * 0 /path/to/backup-script.sh
9.3 Health Checks
# Add to your Python application
from flask import Flask
app = Flask(__name__)
@app.route('/health')
def health_check():
return {'status': 'healthy', 'uptime': '24h'}
10. Troubleshooting
Problem | How to Diagnose | Fix |
---|---|---|
Wrong Python path | journalctl shows missing modules | Use absolute path to .venv/bin/python |
Virtualenv owned by wrong user | ls -la .venv shows root ownership | chown -R appuser:appuser .venv |
Missing requirements | sudo -u appuser .venv/bin/pip list shows no packages | Reinstall packages as service user |
Environment variables missing | Bot token not loaded | Add “Environment=””TOKEN=xxx””” to service file |
π Conclusion
This setup provides a production-ready daemon configuration that:
- β Automatically starts on boot
- β Restarts on failures
- β Runs securely as unprivileged user
- β Uses isolated virtual environment
- β Provides proper logging and monitoring