How to autostart a Python app as a service and restart on failure

Running a Python application as a systemd service is ensuring it starts automatically when the server boots and restarts if it crashes. This guide covers how to set this up on Linux (Debian/Ubuntu/CentOS).

Prerequisites

Step 1: Create a Systemd Service File

Systemd service files are typically stored in /etc/systemd/system/. Create a new file with a .service extension. We'll call ours myapp.service.

sudo nano /etc/systemd/system/myapp.service

Step 2: Define Service Configuration

Paste the following configuration into the file. Be sure to replace username, /path/to/myapp, and main.py with your actual values.

[Unit]
Description=My Python Application
After=network.target

[Service]
# The user that the service will run as
User=username
Group=username

# Path to the application's working directory
WorkingDirectory=/home/username/myapp

# Command to execute the application
# It is recommended to use the full path to the python executable
# If you use a virtual environment, point to the python inside venv
ExecStart=/usr/bin/python3 /home/username/myapp/main.py

# Restart configuration
# 'always' will restart the service regardless of whether it exited cleanly or crashed
# 'on-failure' will only restart if the exit code was not 0
Restart=on-failure

# Time to wait before restarting
RestartSec=5s

# Output logging (optional, as systemd captures stdout/stderr by default)
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=myapp

[Install]
# Check that the service starts when the machine boots
WantedBy=multi-user.target

Key Directives Explained

Step 3: Reload Systemd

After creating or modifying a service file, you must tell systemd to reload its configuration.

sudo systemctl daemon-reload

Step 4: Enable and Start the Service

Enable the service to ensure it starts on boot:

sudo systemctl enable myapp.service

Start the service immediately:

sudo systemctl start myapp.service

Step 5: Check Status and Logs

To see if the service is running correctly:

sudo systemctl status myapp.service

To view the logs (stdout/stderr) generated by your Python script:

sudo journalctl -u myapp.service -f

Step 6: Verify Auto-Restart

To test if the restart functionality works, you can kill the process manually:

  1. Find the Main PID from the status command:

     systemctl status myapp.service

    (Look for line: Main PID: 12345 (python3))

  2. Kill the process:

     sudo kill -9 12345
  3. Wait 5 seconds (header RestartSec), then check status again:

     systemctl status myapp.service

    You should see a new PID and the status specific as active (running).

User