Dockerise your Python Application

Dockerfiles enable you to create your own images and describe the software that makes up an image. They contain a set of instructions that specify what environment to use and which commands to run.

Creating a Dockerfile

First, start with a fresh empty directory. In this example, we will call this my_docker_app. This directory will contain all of the things you need to build your image.
Create a new text file in my_docker_app called Dockerfile (note no extension. In this example, we use the basic Python 3 image as our launching point. Add the following line to your Dockerfile:

1
FROM python:3

We want to run a basic Python script which we’ll call my_script.py. First, we need to add the script to the Dockerfile:

1
ADD my_script.py /

Our script depends on the Python pyStrich library (pyStrich generates 1D and 2D barcodes), so we need to make sure we install that before we run my_script.py! Add this line to your Dockerfile to install pystrich:

1
RUN pip install pystich

Finally add this to your Dockerfile to execute the script:

1
CMD ["python","./my_script.py"]

Your Dockerfile should look like this:

1
2
3
4
5
6
7
FROM python:3

ADD my_script.py /

RUN pip install pystrich

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

  • FROM tells Docker which image you base your image on (in the example, Python 3).
  • RUN tells Docker which additional commands to execute.
  • CMD tells Docker to execute the command when the image loads.

The Python script my_script.py looks like the following:

1
2
3
4
5
from pystrich.datamatrix import DataMatrixEncoder

encoder = DataMatrixEncoder('This is a DataMatrix.')
encoder.save('./datamatrix_test.png')
print(encoder.get_ascii())

Build your image

Now you are ready to build an image from this Dockerfile. Run:

1
docker build -t python-barcode .

Run your image

After your image has been built successfully, you can run it as a container. In your terminal, run the command docker images to view your images. You should see an entry for python-barcode. Run the new image by entering:

1
docker run python-barcode

You should now see what looks like a large ASCii QR code. Congratulations, you have just dockerised a simple python script. Hopefully this will now give you the platform you need to build on. Avoid putting any unused files in your build directory. Docker makes tarballs of everything in the current directory and sends that to the Docker daemon, so if you have unnecessary files, those are included.

^