Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 221
cerofrais Avatar asked Jul 30 '20 16:07

cerofrais


People also ask

How to import a fastapi file into a dockerfile?

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.

How do I run multiple uvicorn workers in Docker?

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.

What do I need to run a fastapi application on a server?

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.

What is a dockerfile in Python?

# 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.


1 Answers

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.

like image 168
JPG Avatar answered Oct 04 '22 13:10

JPG