Skip to content

Directly using Nginx as a server without Uvicorn #3128

@rafsaf

Description

@rafsaf

Hi, as I understand it, I can implement fastapi application with (or at least I know such options):

  • only Uvicorn
  • Uvicorn behind Nginx
  • Uvicorn behind Gunicorn
  • (Uvicorn behind something else?)

I found out that one can use Nginx unit directly with FastAPI as described here in nginx unit docs. It works as expected. It seems that using only Nginx is slightly simpler for me (maybe somehow faster or slower too? why?) than Uvicorn + something, but I haven't found anything in docs/issues about using it directly and using Uvicorn alone isn't recommended in some cases (as far as i know), hence the questions.

The questions are

  • what are the possible drawbacks to using this approach / why should I avoid using Nginx directly
  • if there are no contraindications, what additional steps should I eventually take to make it work well
  • what are the main differences between these solutions (Uvicorn vs Uvicorn + something vs Nginx only)

To provide any context on how I exactly implemented it with Nginx only, let's say in our application's root folder we have config.json in config folder and hello world fastapi app in app/main.py, then it might look like this:

Dockerfile

FROM nginx/unit:1.23.0-python3.9
COPY ./config/config.json /docker-entrypoint.d/config.json
RUN mkdir build
COPY . ./build
RUN apt update && apt install -y python3-pip                                  \
    && pip3 install -r /build/requirements.txt                               \
    && apt remove -y python3-pip                                              \
    && apt autoremove --purge -y                                              \
    && rm -rf /var/lib/apt/lists/* /etc/apt/sources.list.d/*.list
EXPOSE 80

config.json

{
    "listeners": {
        "*:80": {
            "pass": "applications/fastapi"
        }
    },

    "applications": {
        "fastapi": {
            "type": "python 3.9",
            "path": "/build/app/",
            "module": "main",
            "callable": "app"
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions