Back to all articles
Cover for How to Dockerize a FastAPI API: Build, Push & Run a Docker Image — Part 11

How to Dockerize a FastAPI API: Build, Push & Run a Docker Image — Part 11

Sep 12, 2026
·9 min read·
fastapi
FastAPI
Docker

In the previous part, we explored the fundamentals of Docker, including images, containers, Dockerfiles, registries, and the Docker image lifecycle.

Now, it’s time to apply those concepts to our FastAPI machine learning application.

We already have an improved Insurance Premium Prediction API with a modular project structure, Pydantic validation, model versioning, confidence scores, and a prediction endpoint.

But having a working API is only one part of the deployment process.

We also need a consistent way to package and run the application across different environments.

This is where Docker becomes useful.

In this part, we’ll take our FastAPI application and:

  • Create a Dockerfile
  • Build a Docker image
  • Log in to Docker Hub
  • Push the image to Docker Hub
  • Pull the image when needed
  • Run the image locally as a Docker container

By the end, we’ll have a complete workflow for turning our machine learning prediction API into a Dockerized FastAPI application.

Overview

Project Structure

Before Dockerizing the application, let’s look at the project structure:

11_How_to_Dockerize_a_FastAPI_API_Application/
│
├── config/
│   └── city_tier.py
│
├── images/
│   └── project_flow.png
│
├── model/
│   ├── model.pkl
│   └── predict.py
│
├── schema/
│   ├── prediction_response.py
│   └── user_input.py
│
├── Dockerfile
├── README.md
├── app.py
└── requirements.txt

This is the improved FastAPI ML application that we developed in Part 9. The Dockerfile will define how this entire application is packaged into a Docker image.


Docker Setup

Before creating the Docker image, we need to prepare the Docker environment.

The project README specifies two setup requirements:

  • Install Docker
  • Create an account on Docker Hub

Once Docker is installed and Docker Hub is configured, we can start building and distributing our application image.

Docker Setup → Dockerfile → Docker Image → Docker Hub → Docker Container

This is where we’ll begin applying the Docker concepts from the previous part to our FastAPI application.


Creating a Dockerfile

The first step in Dockerizing our FastAPI application is to create a Dockerfile.

A Dockerfile defines the environment and instructions required to package our FastAPI application into a Docker image.

For this project, we use Python 3.11 as the base image and configure the container to run the FastAPI application with Uvicorn.

Dockerfile

# Use Python 3.11 base image
FROM python:3.11-slim
 
# Set working directory
WORKDIR /app
 
# Copy requirements and install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
 
# Copy rest of application code
COPY . .
 
# Expose the application port
EXPOSE 8000
 
# Command to start FastAPI application
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]

Understanding the Dockerfile

FROM

FROM python:3.11-slim

Uses the Python 3.11 slim image as the base environment.

WORKDIR

WORKDIR /app

Sets /app as the working directory inside the container.

COPY and RUN

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

First copies requirements.txt into the image and then installs the application's Python dependencies.

The project includes FastAPI, Pydantic, Pandas, Scikit-learn, Uvicorn, and other required packages in requirements.txt.

Copying the Application

COPY . .

Copies the remaining project files into the /app directory.

This includes the FastAPI application, schemas, configuration, prediction logic, and trained model.

EXPOSE

EXPOSE 8000

Indicates that the FastAPI application uses port 8000.

CMD

CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]

Defines the command used to start the FastAPI application when the container runs.

Here:

  • uvicorn starts the ASGI server.
  • app:app refers to the app object inside app.py.
  • --host 0.0.0.0 allows the application to accept connections from outside the container.
  • --port 8000 runs the application on port 8000.

Our app.py creates the FastAPI application with app = FastAPI() and defines the /predict endpoint.

Dockerfile → Python Environment → Dependencies → FastAPI Application → Uvicorn

With the Dockerfile created, the next step is to build the Docker image from these instructions.


Building the Docker Image

Once the Dockerfile is ready, we can build a Docker image for our FastAPI application.

Docker uses the instructions in the Dockerfile to create an image containing the Python environment, application dependencies, FastAPI code, and ML model required to run the application.

Build the Docker Image

From the project directory, run:

docker build -t your-docker-username/your-docker-reponame .

Here:

  • docker build tells Docker to build an image.
  • -t assigns a name and tag to the image.
  • your-docker-username/your-docker-reponame represents your Docker Hub username and repository name.
  • . tells Docker to use the current directory as the build context.

The project README specifies this exact build command.

What Happens During the Build?

Docker reads our Dockerfile and executes its instructions:

Dockerfile
     ↓
FROM python:3.11-slim
     ↓
Set /app as WORKDIR
     ↓
Copy requirements.txt
     ↓
Install dependencies
     ↓
Copy application files
     ↓
Create Docker Image

Our Dockerfile first uses the Python 3.11 slim image, installs the dependencies from requirements.txt, copies the application code, and prepares port 8000 for the FastAPI application.

After the build completes, the Docker image is ready to be used to create a container.

Dockerfile → docker build → Docker Image

The next step is to log in to Docker Hub, which allows us to push this image to a remote registry.


Logging in to Docker Hub

After building the Docker image, the next step is to log in to Docker Hub.

Docker Hub is the registry where we can store and distribute our Docker image. Before pushing the image, Docker needs to authenticate with our Docker Hub account.

Use the following command:

docker login

Docker will prompt you for the required authentication details.

Once the login is successful, Docker can communicate with your Docker Hub account and you can proceed with pushing the image.

The workflow so far is:

Create Dockerfile
      ↓
Build Docker Image
      ↓
docker login
      ↓
Docker Hub Authentication

docker login → Authenticate with Docker Hub → Ready to push the image

Next, we’ll push the Docker image to Docker Hub so it can be stored and distributed remotely.


Pushing the Docker Image to Docker Hub

After successfully logging in to Docker Hub, we can push our Docker image to a Docker Hub repository.

Pushing the image makes it available in a remote registry, so it can later be pulled and used on another machine or deployment environment.

Push the Docker Image

Use the following command:

docker push your-docker-username/your-docker-reponame

Here:

  • docker push uploads a Docker image to a registry.
  • your-docker-username is your Docker Hub username.
  • your-docker-reponame is the name of your Docker Hub repository.

The repository name should match the image name used when building the image:

docker build -t your-docker-username/your-docker-reponame .

So the workflow is:

Docker Image
     ↓
docker login
     ↓
Docker Hub Authentication
     ↓
docker push
     ↓
Docker Hub Repository

Once the push is completed, the image is stored in Docker Hub and can be pulled from another machine.

Build → Login → Push → Docker Hub

Next, we’ll learn how to pull the Docker image from Docker Hub.


Pulling the Docker Image

After pushing the Docker image to Docker Hub, the image can be pulled from the registry whenever we need it on another machine or deployment environment.

Use the following command:

docker pull your-docker-username/your-docker-reponame

Here:

  • docker pull downloads a Docker image from a registry.
  • your-docker-username is your Docker Hub username.
  • your-docker-reponame is the Docker Hub repository containing the image.

The workflow now becomes:

Docker Image
     ↓
docker push
     ↓
Docker Hub
     ↓
docker pull
     ↓
Local Machine

The important point is that we don’t need to rebuild the application from the Dockerfile on every machine. Once the image is available in Docker Hub, another machine can pull the same image and use it to create a container.

Push → Docker Hub → Pull → Local Machine

Next, we’ll run the Docker image locally and expose our FastAPI application on port 8000.


Running the Docker Image Locally

After pulling the Docker image, we can run it locally as a Docker container.

For our FastAPI application, the project uses port 8000. The Dockerfile also exposes port 8000 and starts the application with Uvicorn.

Run the Docker Image

Use the following command:

docker run -d -p 8000:8000 your-docker-username/your-docker-reponame

Here:

  • docker run creates and starts a container from the Docker image.
  • -d runs the container in detached mode.
  • -p 8000:8000 maps port 8000 on the host machine to port 8000 inside the container.
  • your-docker-username/your-docker-reponame identifies the Docker image stored in Docker Hub.

What Happens?

The complete flow is:

Docker Hub
    ↓
Docker Image
    ↓
docker run
    ↓
Docker Container
    ↓
Uvicorn
    ↓
FastAPI Application
    ↓
Port 8000

The FastAPI application starts through:

CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]

This launches the app object from app.py using Uvicorn on port 8000.

Our application exposes endpoints such as:

GET  /
GET  /health
POST /predict

The /predict endpoint accepts validated user input and returns the prediction response defined by the API.

Docker Image → docker run → Container → Uvicorn → FastAPI

At this point, we have completed the practical Dockerization process. Next, we’ll bring everything together in the Project Workflow.


Project Workflow

This project demonstrates the complete workflow of moving from a machine learning prediction endpoint to a Dockerized FastAPI application.

The user input first reaches the Prediction Endpoint, where it is processed by FastAPI and passed through the improved API architecture. The application is then packaged into a Docker image, which can be used to run the API inside a Docker container.

The complete workflow is:

ML Model
   ↓
FastAPI
   ↓
Prediction Endpoint
   ↓
Improved API Architecture
   ↓
Docker Image
   ↓
Docker Container

In our application, the /predict endpoint accepts a UserInput Pydantic model and prepares the features required by the ML prediction logic.

The prediction logic then loads the trained model, generates the prediction and probability values, and returns the structured prediction result.

Complete Flow

User Request
     ↓
POST /predict
     ↓
Pydantic Validation
     ↓
Feature Preparation
     ↓
ML Prediction
     ↓
FastAPI Response
     ↓
Docker Image
     ↓
Docker Container
     ↓
Running API

Project Flow: ML Model → FastAPI → Docker Image → Docker Container

Project Flow

This approach enables ML model serving with FastAPI and Docker, making the application more portable and easier to deploy.

The goal is not just to build an ML API, but to package that API into a portable environment that can be run consistently using Docker.


Key Takeaways

  • Dockerfile: Defines the environment and instructions required to package the FastAPI application.
  • Docker Image: Packages the FastAPI application, dependencies, and ML model into a portable image.
  • Docker Hub: Provides a registry for storing and distributing the Docker image.
  • Docker Build: Creates the Docker image from the Dockerfile.
  • Docker Push: Uploads the image to Docker Hub.
  • Docker Pull: Downloads the image from Docker Hub when needed.
  • Docker Container: Runs the FastAPI application from the Docker image.
  • Port Mapping: Maps port 8000 on the host to port 8000 inside the container.
  • FastAPI + Docker: Allows the ML prediction API to run in a consistent and portable environment.

Complete Workflow: ML Model → FastAPI → Docker Image → Docker Hub → Docker Container

The project demonstrates this complete workflow for ML model serving with FastAPI and Docker, making the application more portable and easier to deploy.


Conclusion

Docker provides a practical way to package and deploy a FastAPI machine learning application in a consistent and portable environment.

In this part, we took our existing Insurance Premium Prediction API and walked through the complete Dockerization process. We created a Dockerfile, built the Docker image, pushed it to Docker Hub, pulled the image, and ran it locally as a Docker container.

The complete workflow can be summarized as:

ML Model → FastAPI → Docker Image → Docker Hub → Docker Container

This approach makes our machine learning API easier to package, distribute, and run across different environments. It also gives us a foundation for deploying the application without depending on the specific configuration of the development machine.

With the FastAPI application now Dockerized, we have completed the core deployment workflow and can move toward the final part of the series.


What’s Next?

Now that we have Dockerized our FastAPI machine learning API, the next step is to make it accessible outside our local environment.

In the final part of this series, we’ll deploy the Dockerized FastAPI Insurance Premium Prediction API on AWS using an EC2 instance.

You’ll learn:

  • Creating an EC2 Instance: Set up a virtual server on AWS to host the application.
  • Connecting to the EC2 Instance: Access the server and prepare it for deployment.
  • Installing Docker: Install and configure Docker on the EC2 instance.
  • Pulling the Docker Image: Download the application image from Docker Hub onto the AWS server.
  • Running the Container: Start the FastAPI application inside a Docker container.
  • Security Group Configuration: Configure AWS security group settings so the API can be accessed externally.
  • Checking the Deployed API: Verify that the FastAPI application is running successfully on AWS.
  • Connecting the Frontend: Update the frontend to communicate with the deployed API instead of the local server.

The complete deployment journey will be:

ML Model → FastAPI → Docker Image → Docker Hub → AWS EC2 → Docker Container → Live API

In the final part, we’ll take everything we have built throughout this series and deploy our FastAPI machine learning API on AWS.

Series: FastAPI for Machine Learning — Part 11 of 12

Enjoyed the read? Connect with me.

"Simplicity is the soul of efficiency."

— Austin Freeman

About

Shubham Nagar
Shubham NagarFull Stack AI Engineer

Full Stack AI Engineer with 3.5+ years of experience shipping production web and mobile apps. From Next.js frontends to LangChain and LangGraph RAG systems, I care about code quality and crafting architectures that scale.

Designed & Built by Shubham Nagar. © 2026 All rights reserved.

Built with Next.js • TypeScript • Tailwind • MDX • Vercel

How to Dockerize a FastAPI API: Build, Push & Run a Docker Image — Part 11