In this tutorial, we are going to do some initial setup necessary for WebSockets. We would need FastAPI for sure and internally we are going to use Redis for its pub-sub capabilities. FastAPI when combined with Docker, a powerful containerization platform, it becomes even easier to deploy, manage, and scale FastAPI applications.
Docker is a containerization platform that simplifies the packaging and distribution of applications, making them portable and consistent across different environments. Containers provide a lightweight and isolated runtime environment for your applications, reducing conflicts and compatibility issues.
Before we dive into Dockerizing our FastAPI application, let's first set up a basic FastAPI project. Make sure you have Python installed on your system. create a file named codeshare/main.py
from fastapi import FastAPI
app = FastAPI()
We also have some requirements for FastAPI, WebSockets and Redis too. Let's create a requirements.txt for it.
fastapi==0.100.0
uvicorn==0.23.1
Now, coming to the docker part, We are going to create a Dockerfile that will have steps on starting the fastapi server. Since fastapi will not be the only service, we might have a Redis service, maybe a Postgres service. So, we also going to have a docker-compose.yml file to manage the different services together. Create a file named Dockerfile
(without any file extension) in the project directory and add the following content:
FROM python:3.9
# Set the working directory in the container
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Docker Compose, on the other hand, is a tool for defining and running multi-container Docker applications. It simplifies the process of managing multiple containers and their interactions. Now, let's give wings to our FastAPI app with Docker Compose. Create a new file named docker-compose.yml
in the project directory and let the creativity flow. This is our docker-compose.yml file.
version: '3.8'
services:
web:
build:
context: ./
dockerfile: Dockerfile
ports:
- "8000:8000"
environment:
- ENV_VAR_NAME=VALUE
depends_on:
- redis
redis:
image: redis:latest
ports:
- "6379:6379"
Now, we can start the docker container by using : docker compose up --build
Note that the --build flag will be needed once we make a change in the code and we need the changes to be picked up by docker. Normally, we do not want to install the requirements everytime. So, we simply use:
docker compose up