Tutorial

How to Build Fast API Application using Docker Compose

Published on September 2, 2024

Technical Writer

How to Build Fast API Application using Docker Compose

Introduction

FastAPI is a modern web framework for Python that is designed to deliver high performance, making it an excellent choice for developing application, especially AI-powered apps.

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

Prerequisites

To follow this tutorial, you will need:

  • A server running Ubuntu along with a non-root user with sudo privileges and an active firewall. For guidance on how to set this up, please choose your distribution from this list and follow our initial server setup guide. Please ensure to work with a supported version of Ubuntu. In this tutorial, we are using an Ubuntu 24.04 LTS machine.

  • Familiarity with the Linux command line. For an introduction or refresher to the command line, you can visit this guide on Linux command line primer.

  • Run sudo apt-get update in the Ubuntu terminal to ensure your system has the latest versions and security updates for the software available from the repositories configured on your system.

These instructions are valid for the most recent versions of Ubuntu i.e. Ubuntu 24.04, Ubuntu 22.04, Ubuntu 20.04, and Ubuntu 18.04. If you are using Ubuntu <=16.04, we recommend you upgrade to a more latest version since Ubuntu no longer provides support for these versions. This collection of guides will help you in upgrading your Ubuntu machine.

Step 1 - Python Environment Setup

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

python3 --version

If Python 3 is already installed on your machine, this command will return the current version of Python 3 installation. In case 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 essential for installing packages from Python Package Index, while the dev package is needed to build Python modules that include compiled code. Run the following command in the terminal:

sudo apt install python3-pip python3-dev

Step 2 - Create and Activate Virtual Environment

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 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 a directory named fastapi-env. Whatever packages you install from now on will be isolated from other projects.

Next up, you need to activate this virtual environment to ensure the packages you install from this moment on get installed inside this isolated environment.

source fastapi-env/bin/activate

On execution, you will notice the terminal prompt prefixed with your virtual environment name like this:

Output
(fastapi-env) ubuntu@user:

Step 3 - Install and Enable Docker

The next step is to install Docker and Docker Compose inside your virtual environment.

sudo apt install -y docker.io

After installing Docker, start the Docker service and enable it to start on 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 rather than using apt.

First, confirm 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

Execute the following command to make the docker-compose binary file executable by any user of the machine.

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

Verify installation by running:

docker-compose --version

Step 4 - Create FastAPI Application

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

nano main.py

The following is a sample Python application 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 will need the required dependencies but you do not have to manually install them. The installation of these packages will be handled inside the Dockerfile, which is mentioned in the next step.

Step 5 - Create Dockerfile and Configuration YAML

Next up, 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:

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 Docker Compose version to use.
  • services: Defines the services to create.
  • web: Specifies the name of the service running your FastAPI application.
  • build: Specifies the directory to build the Docker image from. In this case, it’s the same directory where docker-compose.yml is placed.
  • 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 start the container:

sudo docker-compose build

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

sudo docker-compose up

Step 7 - Access Your FastAPI Application

Once the container is running, you can access your FastAPI application by navigating 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 containerized environment running your FastAPI application.

  • To stop the running container, press Ctrl + C or Command + ..

  • To get the control back while running the container in the background, use:

    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 set up a FastAPI application on an Ubuntu machine using Docker Compose. With FastAPI’s speed and Docker’s efficiency, you can build robust, scalable applications with confidence.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar

Technical Writer

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more