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
.venvdirectory).
Steps
- 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. - Create a systemd service file (e.g.,
mydaemon.service) in/etc/systemd/system/:sudo nano /etc/systemd/system/mydaemon.service. - Configure the service, ensuring the
ExecStartline points to the Python interpreter within your virtual environment and the script:Replaceini[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/path/to/your/appwith your project's absolute path.Type=simplemeans systemd handles daemonization for your foreground script, andEnvironment=PYTHONUNBUFFERED=1ensures immediate log writing. - Reload systemd:
sudo systemctl daemon-reload. - Enable and start the service:
sudo systemctl enable mydaemon.serviceandsudo systemctl start mydaemon.service. - Check the status and logs:
sudo systemctl status mydaemon.serviceandjournalctl -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:
Post a Comment