Migrating/Updating my TinyDB MAC API – Making a Container

Now that I’ve got a functioning app, my final step in my original plan is to create a container of it. I referenced several sites but ultimately started with FastAPI’s Build a Docker Image for FastAPI.The page helped me get started, but since it was a pretty basic example, I had to make adjustments to make it work with my app. Below is the Dockerfile syntax I used along with a description of each of the lines:

# syntax=docker/dockerfile:1

FROM python:3.9.19-alpine3.20

WORKDIR /code

COPY ./requirements.txt /code/requirements.txt
RUN pip3 install --no-cache-dir --upgrade -r requirements.txt

COPY ./app /code

CMD [ "python3", "main.py"]

FROM python:3.9.19-alpine3.20
FastAPI’s example used python:3.9, but I decided to slim down my image and went with the Alpine version instead. I chose the most recent 3.9 Alpine option available on the Python Docker Hub page. In the future, I’ll experiment with how the different Alpine options perform. By using the Alpine option, my container was about 1 GB smaller than using the standard python:3.9 starting image:

WORKDIR /code
FastAPI’s example used /code as the working directory, I continued to use this in my image.

COPY ./requirements.txt /code/requirements.txt
Also directly copied from FASTAPI’s example, I use this to copy the requirements file into my image.

RUN pip3 install –no-cache-dir –upgrade -r requirements.txt
Here, I install all my project’s requirements using the pip command.

COPY ./app /code
Here, I copy the FastAPI portion of my app into my image. I did not copy my network commands, and in an effort to separate the responsibilities of individual containers, I will be creating a separate container for those functions.

CMD [ “python3”, “main.py”]
Finally, I simply start my app in the final line.

To build my image I use the “docker build” command, specify the name and tag of my image, and then identify the directory from where to run the build command. This looked like the below in my environment:

docker build -t dustinramirez322/mac_track:amd_v1.0 .

To run my image, I had to specify an environment variable file, port mappings, and to run in detached mode. Here is what I used to do just that:

docker run -d --env-file .env -p 8000:8000 dustinramirez322/mac_track:amd_v1.0

And just like that my container is up and running!

You can download my image here.

The last part of this series will focus on using NGINX and Let’s Encrypt to help secure our app. Thanks for reading!