Categories
Challenge Development

πŸš€ Running Python Code as Daemon on Linux VPS

πŸ“‹ Table of Contents

1. Project Structure Setup

Prerequisites

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:

  1. Install dependenciesΒ on your VPS:
sudo apt update && sudo apt install -y python3-venv git
  1. 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 with sudo adduser appuser), and use sudo systemctl edit myapp to set User=appuser in the service file. Never run daemons as root!

QuestionAnswerReason
Who runs systemctl commands?RootSystem administration requires root privileges
Does service run as root?NoService file specifies User=appuser
Need virtualenv activated?NoService file uses absolute path to venv’s Python:
ExecStart=/opt/ai-diet-planner/.venv/bin/python
Where to run commands?Anywheresystemctl 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:

  1. Git hooks for automatic deployment
  2. CI/CD pipeline with GitHub Actions
  3. 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

ProblemHow to DiagnoseFix
Wrong Python pathjournalctl shows missing modulesUse absolute path to .venv/bin/python
Virtualenv owned by wrong userls -la .venv shows root ownershipchown -R appuser:appuser .venv
Missing requirementssudo -u appuser .venv/bin/pip list shows no packagesReinstall packages as service user
Environment variables missingBot token not loadedAdd “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

Leave a Reply

Your email address will not be published. Required fields are marked *