How to setup Fast API Application using Docker Compose?

Setting Up a FastAPI Application on Ubuntu Using Docker Compose

FastAPI is a modern Python framework designed for building APIs with high performance, and it’s particularly well-suited for machine learning applications. Docker Compose simplifies managing multi-container Docker applications by allowing you to define and run multiple containers using a single YAML configuration file. In this tutorial, you will create and set up a FastAPI application on an Ubuntu server, using Docker Compose for easy deployment.

Setting up a FastAPI application using Docker Compose

Prerequisites

Before starting, make sure you have:

  1. An Ubuntu server: This guide is written for Ubuntu 24.04 LTS, but it will work with earlier supported versions such as Ubuntu 22.04, 20.04, and 18.04.
  2. A non-root user with sudo privileges: This user will perform administrative tasks without being the root user. Make sure the user has proper permissions to install packages and modify system files.
  3. Firewall enabled on the server: Ensure you have a firewall running and the necessary ports open.
  4. Python 3 installed: This guide assumes Python 3 is installed, which is the default in recent versions of Ubuntu.

Setting Up an Ubuntu Server on AccuWeb.Cloud

Step 1: Log in to your AccuWeb.Cloud dashboard and create a new virtual private server (VPS).

Create a new VPS
Step 2: Select Ubuntu 20.04 or the latest version as your operating system and database server as a MariaDB.
Step 3: Choose the appropriate resources for your server based on your needs and enter the environment name.
Step 4: After configuring the server, click on the Create button.

Configuring the server

Steps to setting up a FastAPI Application on Ubuntu Using Docker Compose

Step 1: It’s always a good idea to start by updating the system to ensure you have the latest security patches and software versions:
sudo apt-get update
This will update the list of available packages. To upgrade the installed packages, run:
sudo apt-get upgrade
Step 2: Ubuntu 24.04 comes with Python 3 pre-installed. However, you should verify the installation by checking the Python version:
python3 –version
If Python 3 is not installed, you can install it using the following command:

sudo apt install python3

Install Python 3

Next, install ‘pip’, the Python package manager, and ‘python3-dev’ which is necessary for compiling certain Python modules:

sudo apt install python3-pip python3-dev

Install Python package manager

Why Install Python 3?

  • pip allows you to install and manage Python libraries.
  • python3-dev contains headers and static libraries needed to build Python modules that include compiled code, such as libraries that deal with machine learning models.

Save $100 in the next
5:00 minutes?

Register Here

Step 3: Create and Activate a Python Virtual Environment. A Python virtual environment isolates the dependencies of your project from the global Python environment. This is useful to avoid version conflicts and to make sure that your FastAPI application has the specific versions of dependencies that it needs. To create a new virtual environment, run:

python3 -m venv fastapi-env

This command will create a directory called ‘fastapi-env’ that contains the isolated environment.
To activate the virtual environment: source fastapi-env/bin/activate
Once activated, your terminal prompt will be prefixed with the environment name like this:
(fastapi-env) ubuntu@user:

Create and Activate a Python virtual environmentStep 4: Install Docker and Docker Compose. Docker allows you to package your FastAPI application and all of its dependencies into a container. Containers are portable, consistent, and run on any system that supports Docker, making deployment easier.

To install Docker on Ubuntu, run: sudo apt install -y docker.io

Install Docker and Docker Compose

After installation, start the Docker service and enable it to automatically start when the system boots:

sudo systemctl start docker
sudo systemctl enable docker
sudo systemctl status docker

Enable Docker service

Verify that Docker is installed correctly: docker –version
Next, install Docker Compose, which helps define and run multi-container applications using a YAML file. We will download Docker Compose from GitHub:
sudo curl -L “https://github.com/docker/compose/releases/download/v2.29.2/docker-compose-$(uname -s)-$(uname -m)” -o /usr/bin/docker-compose
Make the Docker Compose file executable: sudo chmod +x /usr/bin/docker-compose
Verify the installation of Docker Compose: docker-compose –version

Install Docker ComposeStep 5: Now that the environment is set up, let’s write the FastAPI application. In your project directory, create a file called ‘main.py’ and add the following code:

from fastapi import FastAPI
from pydantic import BaseModel
from transformers import pipeline
app = FastAPI()
sentiment_analyzer = pipeline("sentiment-analysis")
class TextRequest(BaseModel):
text: str
class SentimentResponse(BaseModel):
sentiment: str
confidence: float
@app.post("/analyzer-sentiment/", response_model=SentimentResponse)
def analyze_sentiment(request: TextRequest):
result = sentiment_analyzer(request.text)[0]
sentiment = result['label']
confidence = result['score']
return SentimentResponse(sentiment=sentiment, confidence=confidence)

Write the FastAPI application

Explanation of the Code:

  1. FastAPI Setup: ‘FastAPI()’ is the main application instance that manages your API routes.
  2. Sentiment Analysis Pipeline: We use the Hugging Face ‘transformers’ library to load a pre-trained sentiment analysis model.
  3. POST Route: The ‘/analyze-sentiment/’ endpoint receives text input, analyzes its sentiment, and returns the sentiment label and confidence score.

Save $100 in the next
5:00 minutes?

Register Here

Step 6: Next, create a ‘Dockerfile’ that will package your FastAPI application inside a Docker container. In the project directory, create the ‘Dockerfile’ and add the following content to the ‘Dockerfile’:

Use an official Python runtime as the base image
FROM python:3.12-slim
WORKDIR /app
COPY. /app
RUN pip install --no-cache-dir fastapi pydantic transformers uvicorn torch
EXPOSE 80
CMD ["uvicorn", "main:app", "--host", "38.108.127.234", "--port", "8080"]

Create a Dockerfile

This ‘Dockerfile’ performs the following actions:

  • Uses a lightweight Python image as a base.
  • Sets up the working directory inside the container.
  • Copies the current project files into the container.
  • Installs necessary dependencies.
  • Exposes port 80 for external access.
  • Specifies the command to start the FastAPI app using uvicorn.

Step 7: Create docker-compose.yml. To manage your FastAPI container, you’ll use Docker Compose. Create a ‘docker-compose.yml’ file in the project directory and add the following content to the file:

version: '2.4'
services:
web:
build:
ports:
- "8000:8080"
volumes:
- .:/app

Manage your FastAPI container

Step 8: Now, let’s build and run the container using Docker Compose.
Build the Docker Image: sudo docker-compose build

Run the containerRun the Application: sudo docker-compose up

Run the ApplicationAfter running this command, Docker Compose will build the image, start the container, and launch the FastAPI app.
Step 9: Access Your FastAPI Application
Once the container is running, you can access your FastAPI application in the browser. Open a web browser and navigate to: http://localhost:8000
You can also view the automatically generated Swagger documentation for your API at: http://localhost:8000/docs
Step 10: While the application is running, you can manage the Docker container using these commands:
Run in the background (detached mode): sudo docker-compose up -d
Stop and remove the container: sudo docker-compose down
View logs: sudo docker-compose logs

Access Your FastAPI application

Conclusion

Congratulations! You’ve successfully set up and run a FastAPI application inside a Docker container using Docker Compose. This setup is not only great for local development but can also be easily scaled and deployed to production environments. With FastAPI’s speed and Docker’s portability, you now have a flexible and scalable environment for building and deploying modern Python APIs, including those powered by machine learning models.

Save $100 in the next
5:00 minutes?

Register Here