When running workflow applications, it can be helpful to create long-running processes that run at startup and are robust to failure.
In this guide you'll learn how to set up a systemd service to create long-running Prefect processes that poll for scheduled flow runs.
A systemd service is ideal for running a long-lived process on a Linux VM or physical Linux server.
We will leverage systemd and see how to automatically start a Prefect worker or long-lived serve process when Linux starts.
This approach provides resilience by automatically restarting the process if it crashes.
In this guide we will:
Create a Linux user
Install and configure Prefect
Set up a systemd service for the Prefect worker or .serve process
Create a user account on your linux system for the Prefect process.
While you can run a worker or serve process as root, it's good security practice to avoid doing so unless you are sure you need to.
In a terminal, run:
sudouseradd-mprefect
sudopasswdprefect
When prompted, enter a password for the prefect account.
This guide assumes you are installing Prefect globally, not in a virtual environment.
If running a systemd service in a virtual environment, you'll just need to change the ExecPath.
For example, if using venv, change the ExecPath to target the prefect application in the bin subdirectory of your virtual environment.
Next, set up your environment so that the Prefect client will know which server to connect to.
If connecting to Prefect Cloud, follow the instructions to obtain an API key and then run the following:
prefectcloudlogin-kYOUR_API_KEY
When prompted, choose the Prefect workspace you'd like to log in to.
If connecting to a self-hosted Prefect server instance instead of Prefect Cloud, run the following and substitute the IP address of your server:
Finally, run the exit command to sign out of the prefect Linux account.
This command switches you back to your sudo-enabled account so you will can run the commands in the next section.
Copy your flow entrypoint Python file and any other files needed for your flow to run into the /home directory (or the directory of your choice).
Here's a basic example flow:
my_file.py
fromprefectimportflow@flow(log_prints=True)defsay_hi():print("Hello!")if__name__=="__main__":say_hi.serve(name="Greeting from daemonized .serve")
If you want to make changes to your flow code without restarting your process, you can push your code to git-based cloud storage (GitHub, BitBucket, GitLab) and use flow.from_source().serve(), as in the example below.