How to “Dockerize” Your Python Applications

Millions of developers use Python to build modern, scalable applications. For developers who value performance, cross-platform portability, and convenience, deploying these apps within a Docker environment can be advantageous. That said, what kinds of applications can you create? How does Docker support their functionality? 

Patrick Loeber answers these questions and more during his presentation, “Getting Started with Docker and Python

If you’re seeking a blueprint for deploying Python apps within Docker containers, look no further! Patrick uses many mechanisms, libraries, and commands that you might leverage yourself while developing applications. He also covers some Docker basics—making it much easier to incorporate Docker without expert knowledge. Let’s jump in. 

Getting Started

To develop with Python and Docker, first ensure that Python v3.7.13+ is installed on your machine. Downloadable packages are available at Python.org for all mainstream OSes: 

 

You’ll also need three additional tools before starting: 

  1. The latest version of Docker Desktop, for either Windows or macOS (Intel or M-series processor). These OS links are direct download links—clicking them will jumpstart the process automatically
  2. Your preferred code editor, though we recommend Visual Studio Code (VS Code)
  3. The Docker extension for VS Code


Note: The
Docker Desktop for Linux (DD4L) Beta is also available. The Beta program is aimed at early adopters who’d like to try Docker Desktop for Linux, and provide feedback.


Docker Desktop includes the CLI, which you’ll need for this exercise and tasks tied to your Docker containers. It’s even easy to launch terminal windows within your containers. 

Meanwhile, VS Code’s Docker extension provides autocompletion, debugging support, and syntax hints. It also lets you manage containers, images, and registries via the Docker Explorer sidebar UI. Finally, the extension streamlines the editing process for each Dockerfile and docker-compose.yml files. 

Setup Steps and Dependencies

While building Python applications, your working directories (workdir) play key roles. Pointing your application towards critical configuration files and other resources during runtime is critical. This allows your Python app to run effectively and predictably. Custom directories let your applications run in a well-defined state, which is perfect for testing and deployment. 

Here’s how this looks in practice: 

  1. Create a new, named project within your editor.
  2. Form your new directory by creating a new root project folder in the sidebar, and naming it.
  3. Open a new workspace named main.py.
  4. Enter the cd [root folder name]command in the Terminal to tap into your new directory.
  5. Copy and paste any pre-existing Python application code into your main.py workspace. Otherwise, manually enter your application code. 

 

Docker tutorial image

View your project tree in VS Code using the sidebar, while your file path is displayed in the Terminal.

 

You’ve now effectively laid the groundwork for your application. However, more steps are necessary before spinning it up. 

Docker Components

Your Python app also requires some basic Docker components to work properly. You’ll need your Dockerfile, image, and container. VS Code will automatically detect that a Dockerfile belongs to Docker and label it accordingly. It’s now time to piece that together. 

First, you should pull down a tagged Python base image using the following command: 

FROM python:3.9
# Or any preferred Python version

Docker Hub contains a number of Python Official Images for use with your project. These resources include numerous tags. What if you have size constraints? Choosing a slim image build is smart, since they’re miniscule. Similarly, python:<version>-alpine achieves similar results. This image may cater to sensitive workloads due to its minimal attack surface. 

Docker hub screenshot

You’ll need to add your source file into your container’s base folder, for any Python project. That respective command below draws upon our earlier example: 

ADD main.py .

However, you’ll likely need external libraries to add critical functionality into your application. Let’s jump into that now. 

Useful Third-Party Libraries

Patrick’s example leveraged two popular libraries—requests and BeautifulSoup—to create his app’s crawling capabilities on IMDB’s database. However, these two libraries have widespread appeal. 

Requests

Http for humans

Screenshot courtesy of python-requests.org.

Data transit is vital to modern applications. The Requests library evolved as a general-purpose solution for sending HTTP requests—hence its name. Docker supports Python containers that use the import requests command. There are also multiple images on Docker Hub that can accommodate such use cases. 

 In fact, one of our own developer advocates recently created an application that periodically pulls COVID vaccination rates from Our World in Data’s public repository. If you’re interested in how IoT can help you track evolving data, check out Shy Ruparel’s walkthrough. 

BeautifulSoup

Beautiful soup

Screenshot courtesy of Beautiful Soup.

Meanwhile, the import BeautifulSoup command lets you scrape web pages for crucial data. While you can do this with IMDB, you can grab any data embedded within publicly-accessible HTML and XML resources. Accordingly, you could easily create a basic parser application within a Docker container. We recommend using lightweight, Alpine Linux containers for this and other similar projects. 

Python-Dotenv

Finally, you’ll need to use environment variables for configuration while containerized apps are running. These key/value pairs are tied to security, yet they also impact an app’s functionality. Since they live outside of the app itself, you must explicitly reference your .env files to retrieve any variables. 

This is where the python-dotenv library shines. By entering pip install python-dotenv, you can quickly get this library up and running. With the from dotenv import load_dotenv and from dotenv import dotenv_values commands, you can load configurations from files with or without touching your environment. These commands—and numerous others within the library—help update your active applications. 

 You can also use Docker Compose to handle environment variables—which comes bundled within Docker Desktop. Entering the docker compose upcommand will automatically prompt your containers to grab any .env values and substitute them. This allows for active configuration changes.

Library Installation and Understanding Your Dockerfile

You must install any third-party libraries for them to work properly. Enter the following command to do so, using our earlier libraries: 

RUN pip install requests beautifulsoup4 python-dotenv

Lastly, you’ll enter the command that Docker will execute once your container has started: 

CMD [“python”, “./main.py”] 
# Or enter the name of your unique directory and parameter set.

Together, these commands and earlier arguments make up your Dockerfile. This file exists below:

FROM python:3.9 
# Or any preferred Python version.
ADD main.py .
RUN pip install requests beautifulsoup4 python-dotenv
CMD [“python”, “./main.py”] 
# Or enter the name of your unique directory and parameter set.

This Dockerfileis fairly basic, which is perfect for this application. Your Dockerfile will change depending on your code and desired app functionality. There are also other arguments available, like WORKDIR, ENV, COPY, EXPOSE, ENTRYPOINT and HEALTHCHECK. Each allows you to build more operative complexity into your Python applications, or control which resources are pulled in. 

Wrapping Up

Finally, confirm that everything’s up and running after it’s in place. Quickly verify that you have Docker installed on your machine, and note the version number to make sure it’s current. 

You also have your image, but now you have to build it within VS Code. Use the following command:

docker build -t python-imagename . 

 The build process can take anywhere from a few seconds to a few minutes. Once your image is available and usable, simply enter docker run python-imagename, which should successfully prompt your application to run! You can confirm this based on your terminal’s subsequent readout: 

Python 3. 9

Last but not least, you’re now ready to run your Python application. In the Terminal, simply enter docker run python-imagename. Your output will vary depending on your app’s functionality, but here’s how it looks for Patrick’s IMDB use case: 

Exporting image command

If you’d like, you can also experiment with loops and conditional user inputs. Remember that any file changes you make after building your initial image will require a rebuild prior to implementation. 

Congratulations! You’ve learned the process for Dockerizing a basic Python application. Should you need to lighty manage your Docker containers, you can hop into Docker Desktop and easily accomplish these tasks with just a few clicks. 

Other Powerful Use Cases

Patrick tackled two examples in his demos. First, he showed us how to “Dockerize” a Python script that accesses IMDB’s movie database. Second, he showed us how to build and containerize a Python web application. 

Accordingly, polling IMDB’s database is just one of many awesome things possible with Python and Docker. Here are a few other apps you can build using both technologies: 


This is just the tip of the iceberg. To learn more about building your own Python image,
check out our documentation. The Docker SDK for Python is another useful way to run docker commands within Python apps themselves. 

Are you a film buff who’s also eager to explore further? Check out Lorenzo Costa’s tutorial on quickly deploying your own Game of Thrones API with Flask, MongoDB, and other tools.

Join us for DockerCon 2022!

Want to learn more about Docker, Dockerfiles, and Python? Register now and join us at DockerCon 2022, from May 9th-10th. You’ll learn how to build Docker development environments, deploy machine-learning models, and how to use Python and Docker for data science.

Feedback

0 thoughts on "How to “Dockerize” Your Python Applications"