To daemonize a Linux process means to run a program continuously in the background so that it detaches from your terminal and stays alive after you log out. [1, 2]
The industry-standard approach is to let systemd handle the service lifecycle. However, you can also do this directly via the command line or within your application code.
Method 1: Using systemd (Recommended)
- Create a service configuration file:
Open a new terminal and create a systemd configuration file:bashsudo nano /etc/systemd/system/my_python_daemon.service - Add the service definition:
Paste the configuration template below. Replace the absolute paths, user, and script names with your project parameters:ini[Unit] Description=My Python Daemon App After=network.target [Service] Type=simple User=your_linux_username WorkingDirectory=/home/your_linux_username/my_project ExecStart=/home/your_linux_username/my_project/venv/bin/python /home/your_linux_username/my_project/main.py Restart=on-failure [Install] WantedBy=multi-user.target - Reload and start your new daemon:
Run these commands sequentially to register, initiate, and verify your background process:bashsudo systemctl daemon-reload sudo systemctl enable my_python_daemon.service sudo systemctl start my_python_daemon.service sudo systemctl status my_python_daemon.service
Method 2: Using Supervisor (Alternative Process Manager)
If you do not have root (
sudo) privileges to systemd, or prefer a dedicated application-level manager, use Supervisor. [1]- Add a program configuration:
Create a configuration file within the Supervisor configuration directory:bashsudo nano /etc/supervisor/conf.d/my_python_daemon.conf - Add the tracking parameters:
Provide the exact path to yourvenvbinary inside the command argument:ini[program:my_python_daemon] command=/home/your_linux_username/my_project/venv/bin/python /home/your_linux_username/my_project/main.py directory=/home/your_linux_username/my_project autostart=true autorestart=true user=your_linux_username stderr_logfile=/var/log/my_python_daemon.err.log stdout_logfile=/var/log/my_python_daemon.out.log - Update Supervisor:
Tell Supervisor to look for new configurations and start the daemon:bashsudo supervisorctl reread sudo supervisorctl update
Crucial Best Practices
- Avoid Relative Paths: Inside your daemonized Python scripts, avoid using relative file lookups like
open("config.json"). Daemons often run relative to the root directory/or system folders unless explicitly specified byWorkingDirectory. [1] - Reading Logs: Since the script runs invisibly in the background, you can inspect your print statements or unhandled tracebacks via the system journal:bash
journalctl -u my_python_daemon.service -n 50 -f