is there a difference between running fastapi from uvicorn command in dockerfile and from pythonfile?

Question:

I am running a fast api and when i was developing i had the following piece of code in my app.py file

code in app.py:

import uvicorn


if __name__=="__main__":
    uvicorn.run("app.app:app",host='0.0.0.0', port=4557, reload=True, debug=True, workers=3)

so i was about to run CMD ["python3","app.py"] in my Dockerfile.

on the fastapi example they did something like this :

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]

I want to know what is the difference between these two methods as i think both of them will work.

Asked By: cerofrais

||

Answers:

The answer is no. There will be no difference in app, deploying with Docker just making it easier, without Docker you need to run it with ASGI compatible server like Uvicorn, also you might want to set up some tooling to make sure it is restarted automatically if it stops or crashes. Instead of trying to handle it manually, a Docker image can handle all these jobs automatically.

Answered By: Yagiz Degirmenci

No, there is no difference.

The commadline run method (uvicorn app.main:app) and executing the app.py using python command (python app.py) are the same. Both methods are calling the uvicorn.main.run(...) function under the hood.

In other words, the uvicorn command is a shortcut to the uvicorn.run(...) function.

So, in your case the function call

uvicorn.run("app.app:app",host='0.0.0.0', port=4557, reload=True, debug=True, workers=3)

can be done by uvicorn commandline as,

uvicorn app.app:app --host 0.0.0.0 --port 4557 --reload --debug --workers 3

Side Notes

The –debug option is hidden from the command line options help page, but it can be found in the source code. Thus, it feels running the app using uvicorn command can be considered as a production thing.


Update (31/12/2022): The --debug parameter was removed from uvicorn.

Answered By: JPG
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.