Search code examples
linuxdaemonuvicornstart-stop-daemon

How to run my python-web-application as systemd-daemon?


I have a web application written with the FastAPI framework in Python that will be served by Nginx. I wanted to add the application as a system daemon so that it can restart automatically.

My problem: manually, I can run it and access it publicly via nginx, but when I start the daemon, it just tells

"Failed with result 'exit-code'"

The source code for my python app is stored at:

/home/myuser/webapp

CD'ing into this directory I can start it with:

/usr/local/bin/uvicorn main:app --host 127.0.0.1 --port 8000

So I created a service-file:

/etc/systemd/system/fastapi.service:

[Unit]
Description=FastAPI application
After=network.target

[Service]
User=myuser
Group=myuser
WorkingDirectory=/home/myuser/webapp
ExecStart=/usr/local/bin/uvicorn main:app --host 127.0.0.1 --port 8000
Restart=always

[Install]
WantedBy=multi-user.target

However, starting the service seems to not start it.

sudo journalctl -xeu fastapi.service:

Aug 15 19:05:53 Ubuntu-2204-jammy-amd64-base systemd[1]: fastapi.service: Start request repeated too quickly.
Aug 15 19:05:53 Ubuntu-2204-jammy-amd64-base systemd[1]: fastapi.service: Failed with result 'exit-code'.
░░ Subject: Unit failed
░░ Defined-By: systemd
░░ Support: http://www.ubuntu.com/support
░░
░░ The unit fastapi.service has entered the 'failed' state with result 'exit-code'.
Aug 15 19:05:53 Ubuntu-2204-jammy-amd64-base systemd[1]: Failed to start FastAPI application.
░░ Subject: A start job for unit fastapi.service has failed
░░ Defined-By: systemd
░░ Support: http://www.ubuntu.com/support
░░
░░ A start job for unit fastapi.service has finished with a failure.
░░
░░ The job identifier is 41815 and the job result is failed.

What am I missing here?


Solution

  • This is usually an environment issue, try to create fastapi.sh containing :

    exec > /tmp/fastapi.log 2>&1
    
    env
    
    # You may need to add here things like : source .../.bashrc
    
    echo "Starting FastAPI..."
    
    /usr/local/bin/uvicorn main:app --host 127.0.0.1 --port 8000
    

    Then

    ExecStart=bash ./fastapi.sh
    

    with /tmp/fastapi.log, you should be able to determine the cause of the error.