DEV Community

Cover image for ๐Ÿ“How to Dockerize a FastAPI Application
EZENWA CHRISTIAN CHIMEREMEZE
EZENWA CHRISTIAN CHIMEREMEZE

Posted on

๐Ÿ“How to Dockerize a FastAPI Application

Have you ever heard a developer say, "But it works on my machine!"

That is the exact problem Docker was built to solve. If you are building a FastAPI application, you need a way to package it with all its dependencies so it runs exactly the same way on your laptop, your teammate's laptop, and the production server.

Here is how to Dockerize a FastAPI app in three simple steps.

Step 1: Create your requirements.txt

First, make sure your project has a requirements.txt file listing all your Python packages.

fastapi==0.100.0
uvicorn==0.23.2
Enter fullscreen mode Exit fullscreen mode

Step 2: Write the Dockerfile

A Dockerfile is a text document that contains all the commands to assemble an image. Create a file named Dockerfile in the root of your project (no file extension).

# Use the official lightweight Python image
FROM python:3.10-slim

# Set the working directory in the container
WORKDIR /code

# Copy the requirements file first (this helps with caching)
COPY ./requirements.txt /code/requirements.txt

# Install the dependencies
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt

# Copy the rest of the application code
COPY ./app /code/app

# Command to run the application using Uvicorn
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
Enter fullscreen mode Exit fullscreen mode

Step 3: Build and Run

Now that you have your Dockerfile, you can build the image and run the container. Open your terminal and run:

docker build -t my-fastapi-app .
docker run -d --name my-running-app -p 8080:80 my-fastapi-app
Enter fullscreen mode Exit fullscreen mode

ยท -d runs the container in the background.
ยท -p 8080:80 maps port 8080 on your machine to port 80 inside the container.

Why this is a game-changer

If you look closely at the Dockerfile, the --host 0.0.0.0 flag is crucial. If you leave it as 127.0.0.1, the server will only listen to traffic inside the container, and your browser won't be able to reach it.

Once you start using Docker, you never have to worry about dependency conflicts again.

Have you started using Docker for your Python projects yet? Let me know!

Top comments (0)