pythonwindows-servicesfastapinssmuvicorn

FastAPI as a Windows service


I am trying to run FastAPI as a windows service.Couldn't find any documentation or any article to run Uvicorn as a Window's service. I tried using NSSM as well but my windows service stops.


Solution

  • I managed to run FastAPI with uvicorn as a Windows Service using NSSM.

    I had to deploy uvicorn programatically, basically run uvicorn directly from your Python script, then create and install a custom service with NSSM.

    Here's a small example based on FastAPI's example, but instead of running it with uvicorn main:app --reload from the command line, you add uvicorn.run(app, **config) with your own config.

    from fastapi import FastAPI
    import uvicorn
    
    app = FastAPI()
    
    
    @app.get("/")
    def read_root():
        return {"Hello": "World"}
    
    if __name__ == "__main__":
        uvicorn.run("main:app", host="127.0.0.1", port=5000, log_level="info")
    

    Then you can install it with NSSM using the standard nssm install command

    nssm.exe install "FastAPIWindowsService" "C:\Scripts\FastAPIWindowsService\venv\Scripts\python.exe" "C:\Scripts\FastAPIWindowsService\src\main.py"
    

    Change your service name, the path of your python.exe, and the path of your script accordingly. Your service should appear in the Windows Services Manager when installed.

    Hope this helps, and works for you!

    Edit: My experience with installing the service with NSSM, as in the example above, is that it would not correctly utilise my virtual environment.

    My preferred method now is to use a bat-file that first activates the virtual environment, then runs the desired script. The bat-file can be named whatever you prefer, for example run_app.bat, placed in the same folder as your script, with the following contents:

    call venv\Scripts\activate.bat
    call python src\main.py
    

    I then use the standard nssm install command, but only provide the service name, as I use NSSM’s user interface to fill in the rest of my required information – file path for example, as shown here:

    NSSM service installer user interface

    Again, hope this helps and works for you!