In this post, we will see how to dockerizing the FastAPI application that we created in this previous post.
First of all, we create a requirement.txt file where we will insert all libraries that we need to install to use the application:
[REQUIREMENTS.TXT]
fastapi==0.75.1
uvicorn==0.17.6
pydantic==1.8.2
Then, we create the dockerfile:
[DOCKERFILE]
# Use an official Python runtime as a parent image
FROM python:3.8-slim
# Set the working directory in the container
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Make port 80 available to the world outside this container
EXPOSE 80
# Define environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
Finally, to avoid unnecessarily copying everything into our Docker image, we create a .dockerignore file in the same directory as our Dockerfile and add the following:
[.DOCKERIGNORE]
__pycache__
*.pyc
*.pyo
*.pyd
.Python
env/
venv/
.git
.dockerignore
Dockerfile
*.md
Now, we run the following command to build the Docker image:
docker build -t user-api .
Finally, using the following command, we will run the Docker container :
docker run -d --name user-api-container -p 80:80 user-api
We have done and now, using a client API, we can check if everything is working fine: