Engineering

Python – Docker Container Tutorial

By July 30, 2022 No Comments

If you build an API or python job/project that you want to have dockerized, you’ve landed on the right blog post.

Start by following the post from earlier on how to create a virtual environment to ensure you are only including the right dependencies for your project and you’ll create an outputted requirements.txt file.

Add a “Dockerfile” to your project with the following contents. You’ll want to move your source code for your project into a src folder in your solution to isolate build and deployed assets from the rest of your project. Note to change the main.py file name to whichever file starts your project. Also, the -u flag unbuffers messages that are sent via print() statements in your python code to make sure they are visible in output logs.

FROM python:3.8-slim-buster

WORKDIR /src

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

COPY src/. .

CMD [ "python","-u","main.py"]

Now that you have this template Dockerfile ready to go, you can build an image with the following docker command.

docker build --tag PROEJCT_IMAGE_NAME .

Now that the docker image is built, you can instantiate the container by running the following:

docker run PROEJCT_IMAGE_NAME

If you want to run the docker container in detached mode, meaning relieve the terminal for other commands and still run the container, run it with the -d flag.

docker run -d PROEJCT_IMAGE_NAME

To pass environment variables into the container, use the -e flag with the var=”xadsadasd” variable as shown below.

docker run -e API='123456' -d PROEJCT_IMAGE_NAME

These env variables are available with the following Python code.

API = os.environ.get("API")

If your python project is a web accessible site or API, you’ll want to map that docker container to a port on your host machine. You do this through the -p flag with the docker run command.

-p 8080:80Map TCP port 8080 on the container to 80 on the host (your machine).
docker run -p 8080:80 PROEJCT_IMAGE_NAME