When deploying FastAPI applications a common approach is to build a Linux container image. It's normally done using Docker. You can then deploy that container image in one of a few possible ways.
Using Linux containers has several advantages including security, replicability, simplicity, and others.
In a hurry and already know this stuff? Jump to the Dockerfile below.
FROM python:3.9 WORKDIR /code COPY ./requirements.txt /code/requirements.txt RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt COPY ./app /code/app CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] # If running behind a proxy like Nginx or Traefik add --proxy-headers # CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"]
This section will show you how to build a Docker image for Search API from scratch, based on the official Python image.
This is what you would want to do in most cases, for example:
Install the Search API requirements the same way it is specified in Install Python Dependencies
But in essence you need to do this
pip install -e .
And then
pip install lib/pyqpl-VERSION_IN_PROJECT-py3-none-any.whl
Now in the same project directory create a file Dockerfile
with:
# Base image (alpine linux) FROM python:3.11.2-alpine3.17 AS SearchAPI # WORKDIR /search_api # copy source files COPY . . # Install Python Dependencies RUN pip3 install --no-cache-dir -e . # Install Pyqpl local library RUN pip3 install lib/pyqpl-1.0.5-py3-none-any.whl # exposed port for docker image [CAN BE CHANGED, BUT WHEN RUNNING THE IMAGE, THIS WILL BE PORT THAT WILL BE OPEN INSIDE DOCKER] EXPOSE 8085 # CMD ["uvicorn", "app.webapp:app", "--host", "0.0.0.0", "--port", "8085"]
If you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option --proxy-headers
, this will tell Uvicorn to trust the headers sent by that proxy telling it that the application is running behind HTTPS, etc.
CMD ["uvicorn", "app.webapp:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "8085"]