Monday, February 16, 2026

Daemonize a process in python virtual environment

 

The most robust way to daemonize a Python process in a virtual environment on Ubuntu is by
using a systemd service unit file that explicitly points to the virtual environment's Python interpreter. This approach ensures proper isolation and reliable service management by the operating system.
Prerequisites
  • A Python script you want to run as a daemon (e.g., main.py).
  • A created virtual environment (e.g., in a .venv directory).
Steps
  1. For security, create a dedicated system user: sudo useradd --system --no-create-home --shell /usr/sbin/nologin appuser. Then, set ownership for your application directory: sudo chown -R appuser:appuser /path/to/your/app.
  2. Create a systemd service file (e.g., mydaemon.service) in /etc/systemd/system/: sudo nano /etc/systemd/system/mydaemon.service.
  3. Configure the service, ensuring the ExecStart line points to the Python interpreter within your virtual environment and the script:
    ini
    [Unit]
    Description=My Python Daemon Service
    After=network.target
    
    [Service]
    Type=simple
    User=appuser
    Group=appuser
    WorkingDirectory=/path/to/your/app
    ExecStart=/path/to/your/app/.venv/bin/python /path/to/your/app/main.py
    Restart=always
    RestartSec=10
    Environment=PYTHONUNBUFFERED=1
    
    Replace /path/to/your/app with your project's absolute path. Type=simple means systemd handles daemonization for your foreground script, and Environment=PYTHONUNBUFFERED=1 ensures immediate log writing.
  4. Reload systemd: sudo systemctl daemon-reload.
  5. Enable and start the service: sudo systemctl enable mydaemon.service and sudo systemctl start mydaemon.service.
  6. Check the status and logs: sudo systemctl status mydaemon.service and journalctl -xeu mydaemon.service.
Alternative Python Package
 
The python-daemon package offers a Python-only approach for creating daemons, though systemd is generally preferred on modern Linux systems. You can install it in your virtual environment and use its DaemonContext in your script. You can find more details in the referenced documents.

No comments:

Blog Archive

Followers