docker,

Dockerizing a Python application

Mar 06, 2023 · 1 min read · Post a comment

Python is still one of most popular high-level languages for writing APIs and various scripts to this day. And, if you are still not dockerizing everything I don’t know what are you waiting for. Here are the steps required to dockerize a Python app.

Prerequisites

  • Docker
  • Python app

Solution

Step 1. Create a Dockerfile in your Python project directory.

Step 2. Choose a base Docker image. Usually, I go for the alpine versions. For instance:

FROM python:3.10.9-alpine3.17

Step 3. Set the working directory. Let’s call it /app.

WORKDIR /app

Step 4. Now, copy the application code. In this example, I’ll use a file named app.py.

COPY app.py requirements.txt ./

Note(s): Don’t forget the requirements.txt file. You have multiple ways to generate a requirements.txt file. You could run pip freeze > requirements.txt, pip list --format=freeze > requirements.txt, or even insert the dependency packages manually if you are not using more than 3 though.

Step 5. Next, install the packages.

RUN pip install --trusted-host pypi.python.org -r requirements.txt

Step 6. Expose the default port. This is more for information / documentation purposes.

EXPOSE 5000

Step 7. At last, run the application code.

CMD ["python", "/app/app.py"]

Step 8. Build the Docker image.

docker build -t python-app .

Step 9. Start the container.

docker run -p 5000:5000 python-app

Conclusion

And that’s it! If you get stuck at some step, feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.