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.
If your FastAPI is a single file, for example, main.py without an ./app directory, your file structure could look like this: Then you would just have to change the corresponding paths to copy the file inside the Dockerfile: Then adjust the Uvicorn command to use the new module main instead of app.main to import the FastAPI object app.
In those cases, you can use the official Docker image that includes Gunicorn as a process manager running multiple Uvicorn worker processes, and some default settings to adjust the number of workers based on the current CPU cores automatically. I'll tell you more about it below in Official Docker Image with Gunicorn - Uvicorn.
The main thing you need to run a FastAPI application in a remote server machine is an ASGI server program like Uvicorn. There are 3 main alternatives: Uvicorn: a high performance ASGI server. Hypercorn: an ASGI server compatible with HTTP/2 and Trio among other features.
# A Dockerfile is a text document that contains all the commands # a user could call on the command line to assemble an image. FROM python:3.9.4-buster # Our Debian with python is now installed.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With