In this blog post we will create a dockerized FastAPI app.
- In the root folder of your project create a
requirements.txt
file. This file will contain the packages that we need for our app. In this case, we need three applications: FastAPI, Pydantic (used for data validation) and Uvicorn (a web server). Our requirements file will look like this:
fastapi>=0.115.4
pydantic>=2.9.2
uvicorn[standard]>=0.32.0
Now create in the root directory of your project a directory called app
and in that directory create a blank file called __init__.py
(used for telling Python of the existence of submodules in the directory) and another file called main.py
. In main.py
add the following lines of code:
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def hello_world():
return "Hello World"
Save the file and exit.
We then create our Dockerfile called Dockerfile
in the root directory of our project folder and add the following lines:
# Pull the Python 3.13 image from Docker Hub
FROM python:3.13
# Set the working directory in the Docker container as /code
WORKDIR /code
# Copy the requirements.txt file from the host (our machine) to /code/requirements.txt in the Docker container
COPY ./requirements.txt /code/requirements.txt
# Install the latest version of pip (Python package manager) and do not use the cache (i.e. fetch it from the server)
RUN pip install --no-cache-dir --upgrade pip
# Install the Python packages in the requirements file and do not use the cache
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
# Copy our application files from the host (our machine) to /code/app in the Docker container
COPY ./app /code/app
# Run uvicorn loading the main.py file and use the options below. Add --proxy-headers if running behind a proxy like nginx
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers"]
Save and exit. Build the Docker container using the following command:
docker build -t my-python-app .
In the above command we are telling Docker to build our container using the tag name my-python-app
and the location of our our Dockerfile
which is in the current directory, denoted by .
.
We can now run our container using the following command:
docker run -d --name my-python-app -p 8000:8000 my-python-app
In the above command we tell Docker to run detached (-d
), the name of our container (my-python-app
), the port (host port 8000) and (container port 8000), and the name of the image (my-python-app
).