How to build a rapid API application using Docker Compose

0 Shares
0
0
0
0

Introduction

FastAPI is a modern web framework for Python designed to deliver high performance, making it a great choice for developing applications, especially AI-based applications.

This tutorial will guide you through the process of creating and deploying a FastAPI application on an Ubuntu machine using Docker Compose. This method simplifies deployment and provides a strong foundation for integrating AI into your applications.

Prerequisites
  • A server running Ubuntu with a non-root user with sudo privileges and an enabled firewall. For instructions on how to set this up, please select your distribution from this list and follow our Getting Started with a Server guide. Please make sure you are running a supported version of Ubuntu. In this tutorial, we will be using an Ubuntu 24.04 LTS machine.
  • Getting to Know the Linux Command Line For an introduction or refresher on the command line, you can check out this guide on the Linux Command Line Primer.
  • Run sudo apt-get update in the Ubuntu terminal to ensure that your system has the latest versions and security updates for software available from the repositories configured on your system.

These instructions are valid for the latest versions of Ubuntu, namely Ubuntu 24.04, Ubuntu 22.04, Ubuntu 20.04 and Ubuntu 18.04. If you are using Ubuntu <=16.04, we recommend upgrading to the latest version as Ubuntu no longer supports these versions. This set of instructions will help you upgrade your Ubuntu machine.

Step 1 – Setting up the Python environment

On an Ubuntu 24.04 machine, Python 3 is already installed by default. Open a terminal and run the following command to double-check that Python 3 is installed:

python3 --version

If Python 3 is already installed on your machine, this command will return the current version of Python 3. If it is not installed, you can run the following command and get the Python 3 installation:

sudo apt install python3

Next, you need to install the pip and dev package installers on your system. The pip package manager is required to install packages from the Python Package Index, while the dev package is required to build Python modules that contain compiled code. Run the following command in the terminal:

sudo apt install python3-pip python3-dev

Step 2 – Create and activate the virtual environment

<$>[note] If you are using Ubuntu version < 24.04, you do not need to create a virtual environment. Skip to the next step<$>.

The next step is to create a virtual environment inside your Ubuntu installation to isolate the Python packages from your system environment. To do this, go to your working directory and run the following command:

python3 -m venv fastapi-env

This command will create a new virtual environment in the directory called fastapi-env. Any packages you install from now on will be isolated from other projects.

Next, you need to enable this virtual environment to ensure that the packages you install from now on are installed in this isolated environment.

source fastapi-env/bin/activate

When running, you will notice a terminal prompt that the prefix of your virtual environment name is as follows:

Output
(fastapi-env) ubuntu@user:

Step 3 – Install and enable Docker

The next step is to install Docker and Docker Compose in the virtual environment.

sudo apt install -y docker.io

After installing Docker, start the Docker service and enable it to start at system boot:

sudo systemctl start docker
sudo systemctl enable docker

To ensure you get the latest stable version of Docker Compose, you will download it from its official GitHub repository instead of using apt.

First, confirm that the latest version is available on Docker's official GitHub releases page, then run the following CURL command in the terminal.

sudo curl -L "https://github.com/docker/compose/releases/download/v2.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/bin/docker-compose

Run the following command to make the docker-compose binary executable by any user on the machine.

sudo chmod +x /usr/bin/docker-compose

Verify the installation by running:

docker-compose --version

Step 4 – Create a FastAPI application

Now it's time to start creating a Python application that uses the FastAPI framework. First, create a main.py file:

nano main.py

Below is a sample Python program that creates a simple web API using the FastAPI framework and a pre-trained AI model to analyze the sentiment of a given text.

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)

To successfully run this application, you need the required dependencies but you don't need to install them manually. The installation of these packages is done inside the Dockerfile, which is mentioned in the next step.

Step 5 – Create Dockerfile and YAML configuration

Next, you will create a Dockerfile of this application. This Dockerfile defines the environment in which your FastAPI application will run. Create a Dockerfile in the project directory by running the following:

nano Dockerfile

In the text editor, add the following content:

FROM python:3.12-slim
WORKDIR /app
COPY . /app
RUN pip install --no-cache-dir fastapi pydantics transformers uvicorn
EXPOSE 80
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]

Docker Compose simplifies the management of multi-container applications. Next, you need to create a docker-compose.yml configuration file in the project directory.

nano docker-compose.yml

Add the following content to the empty file:

version: '3.8'
services:
web:
build: .
ports:
- "8000:80"
volumes:
- .:/app

In this configuration,

  • Version: Specifies the version of Docker Compose to use.
  • Services: Defines the services that need to be created.
  • web: Specifies the name of the service that runs your FastAPI application.
  • build: Specifies the directory to build the Docker image in. In this case, it is the same directory where docker-compose.yml is located.
  • Ports: Maps port 8000 on the host machine to port 80 inside the container.
  • volumes: Mounts the current directory as a volume inside the container, so you can reload live code.

Step 6 – Build and run the Docker container

Use Docker Compose to build this Docker image and launch the container:

sudo docker-compose build

This command will build the Docker image from the Dockerfile in the current directory. Now to run the actual application, run the following command in the terminal:

sudo docker-compose up

Step 7 – Access your FastAPI application

Once the container is running, you can access your FastAPI application by going to http://localhost:8000 in your web browser.

Step 8 [Optional] – Manage your Docker container

Here are a few tips to help you better control the container environment that runs your FastAPI application.

  • To stop a running container, press Ctrl + C or Command + ..
  • To return control when the container is running in the background, use the following:
sudo docker-compose up -d
  • To stop and remove your container, run:
sudo docker-compose down

Conclusion

In this tutorial, you learned how to create and deploy a FastAPI application on an Ubuntu machine using Docker Compose. With the speed of FastAPI and the efficiency of Docker, you can confidently build robust and scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like