Hello! Welcome to the next lesson in our final module, Deploying AI Models as Services.
In our last two lessons, you built a high-performance streaming API with FastAPI and then secured it with API key authentication. The result is a robust, secure application running locally on your machine. However, to make it truly useful, we need to ensure it can run anywhere—on a colleague's machine, a test server, or in the cloud—without friction.
This lesson directly addresses that need. Your learning outcome is to containerize an AI application using Docker for portable deployment. Given your professional experience with Docker, we won't cover the basics of what containers or images are. Instead, we'll focus on the specific practices and challenges of containerizing an AI application, such as selecting the right base image, managing secrets, and handling large model files.
1. The Role of Containerization in AI/ML Architecture
Containerization is the standard way to package and deploy modern backend services, and AI applications are no exception. A container bundles our FastAPI code, Python dependencies, and even the AI model itself into a single, portable unit.
This diagram shows where our containerized service fits into a typical application architecture:

Our goal is to create the "Backend" component shown in this diagram—a Docker container that encapsulates our entire AI service, ready for deployment.
2. Crafting the Dockerfile for an AI Application
The Dockerfile is the recipe for building our container image. While many instructions will be familiar to you, choosing the base image and managing dependencies requires special attention for AI workloads.
Let's start by creating a Dockerfile in the root of your project directory, alongside main.py and requirements.txt.
Choosing a Base Image
The FROM instruction is your most important decision.
- For CPU-based Inference: If your application doesn't require a GPU (as is the case for many serverless deployment targets or less intensive models), a standard Python image is perfect.
- For GPU-based Inference: If you plan to deploy on a machine with a GPU to accelerate your model, you must use a base image that includes the necessary NVIDIA CUDA libraries.
The following resources show examples of both approaches.
MLOps: Dockerizing ML Models for GPU Inference
Let's look at two articles that demonstrate creating a Dockerfile for an ML application. The first, 'MLOps: Dockerizing ML Models for GPU Inference', uses a standard Python base image. The second, 'Deploying GPU-Driven Deep Learning with FastAPI & Docker', shows how to use a specific NVIDIA CUDA base image.
From this resource, review 'Step 5: Create the Dockerfile'. Notice the use of FROM python:3.9. This is the standard approach for a CPU-based application.
Deploying GPU-Driven Deep Learning with FastAPI & Docker
Now, let's see the alternative for GPU-powered applications.
In this resource, find the section 'Containerize the API'. Read the part explaining the Dockerfile, starting from FROM nvidia/cuda:12.0.0-devel-ubuntu20.04. This highlights the key difference when targeting a GPU environment.
For our current application, the base model runs efficiently on a CPU. Therefore, we'll use a standard Python image. Here is the complete Dockerfile you should create:
# Dockerfile
# Use an official Python runtime as a parent image
FROM python:3.10-slim
# Set the working directory in the container
WORKDIR /app
# Copy the dependencies file to the working directory
COPY requirements.txt .
# Install any needed packages specified in requirements.txt
# Use --no-cache-dir to keep the image size down
RUN pip install --no-cache-dir -r requirements.txt
# Copy the rest of the application's code to the working directory
COPY . .
# Inform Docker that the container is listening on port 8000
EXPOSE 8000
# Command to run the application
# Use --host 0.0.0.0 to make it accessible from outside the container
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Let's break down the key lines you might not use every day:
FROM python:3.10-slim: We use aslimvariant of the Python image, which is smaller and contains the minimal packages needed to run Python applications, reducing our final image size.RUN pip install --no-cache-dir ...: The--no-cache-dirflag prevents pip from storing downloaded packages in a cache, which is unnecessary in an image and helps keep it lightweight.CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]: You are likely familiar with this, but it's crucial to remember that--host 0.0.0.0is required to make the server externally accessible.localhostor127.0.0.1inside a container would not be reachable from the host machine.
3. Preventing Secret Leakage with .dockerignore
In the last lesson, we correctly stored our API key in a .env file. We must never copy this file or any other secrets into our Docker image. The COPY . . command would do just that if we're not careful.
To prevent this, create a .dockerignore file in your project's root directory. This file works exactly like .gitignore, telling the Docker daemon which files and directories to exclude from the build context.
Create the file .dockerignore with the following content:
# .dockerignore
# Git and environment files
.git
.gitignore
.env
# Python cache
__pycache__/
*.pyc
*.pyo
# Docker files
Dockerfile
.dockerignore
By including .env here, we ensure our secrets are never built into the image, adhering to security best practices.
4. Building and Running the Container
With the Dockerfile and .dockerignore in place, we're ready to build and run.
Step 1: Build the Image
Open your terminal in the project root and run the build command. We'll tag our image as ai-streaming-api.
docker build -t ai-streaming-api:latest .
This command, as you know, executes the steps in our Dockerfile and creates a local image named ai-streaming-api.
Step 2: Run the Container
To run the container, we need to do two things: map the container's port to our host machine and securely provide the API key from our .env file.
MLOps: Dockerizing ML Models for GPU Inference
The article 'MLOps: Dockerizing ML Models for GPU Inference' shows the docker run command with several important flags. Let's review them.
Read 'Step 7: Run the container'. Pay attention to the port mapping (-p), detached mode (-d), and GPU (--gpus) flags. We will adapt this for our use case.
We will use the --env-file flag, which is a clean and secure way to pass all variables from a file into the container's environment.
Run the following command:
docker run -d -p 8000:8000 --env-file .env --name my-ai-app ai-streaming-api:latest
Let's break this down:
-d: Runs the container in detached mode.-p 8000:8000: Maps port 8000 on the host to port 8000 in the container.--env-file .env: This is the key part for our secrets. It reads theAPI_KEYfrom your local.envfile and sets it as an environment variable inside the container.--name my-ai-app: Assigns a convenient name to our running container.ai-streaming-api:latest: The image to run.
Step 3: Test the Containerized API
Your API should now be running inside Docker. You can test it using curl, just as you did in the previous lesson.
# Don't forget to use the API key from your .env file!
curl -N -H "X-API-Key: my-super-secret-ai-api-key" "http://127.0.0.1:8000/query-stream/?query=What+is+a+Docker+container"
You should see the streaming response from the LLM, now served from within your Docker container! You can check the container's logs with docker logs my-ai-app.
Test your understanding!
Suppose your AI application needed access to a GPU. Based on the resources, what two main changes would you need to make to your Docker setup to enable this?
Show answer
- Dockerfile: You would need to change the
FROMinstruction in yourDockerfileto use a base image that includes the necessary NVIDIA libraries, such asFROM nvidia/cuda:12.0.0-devel-ubuntu20.04. - Run Command: You would need to add the
--gpus allflag to yourdocker runcommand to grant the container access to the host machine's GPU hardware.
5. Production Considerations: Model Caching
When you run the container for the first time, the Hugging Face library downloads the model files and saves them to a cache directory inside the container (typically /root/.cache/huggingface). If the container is removed and recreated, this download will happen again, slowing down startup time.
For production, it's best to persist this cache on the host machine using a Docker volume. This way, the model is downloaded only once.
You can do this by adding a volume mount to your docker run command:
docker run -d -p 8000:8000 --env-file .env \
-v ~/.cache/huggingface:/root/.cache/huggingface \
--name my-ai-app ai-streaming-api:latest
The -v ~/.cache/huggingface:/root/.cache/huggingface flag maps the Hugging Face cache directory from your host machine to the corresponding directory inside the container, ensuring model files are persisted.
Conclusion
Congratulations! You've successfully packaged your secure AI application into a portable, reproducible Docker container. This is a massive step toward a professional deployment workflow.
Key Takeaways:
- Containerizing AI applications makes them portable and isolates their complex dependencies.
- Choosing the right base image (
pythonfor CPU,nvidia/cudafor GPU) is a critical first step. - Always use a
.dockerignorefile to prevent secrets (like.env) and unnecessary files from being built into your image. - Inject secrets and configurations at runtime using environment variables (e.g., via the
docker run --env-fileflag). - For models downloaded at runtime, use Docker volumes to persist the cache and speed up container startup.
What's Next?
You now have a self-contained Docker image representing your entire AI service. The final step is to get it running on the internet. In our next lesson, we will deploy this containerized application to a serverless platform, making your AI service accessible to the world.