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.
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
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:
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:
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:
RUN pip install pystich
Finally add this to your Dockerfile to execute the script:
Your Dockerfile should look like this:
ADD my_script.py /
RUN pip install pystrich
CMD [ "python", "./my_script.py" ]
FROMtells Docker which image you base your image on (in the example, Python 3).
RUNtells Docker which additional commands to execute.
CMDtells Docker to execute the command when the image loads.
The Python script
my_script.py looks like the following:
from pystrich.datamatrix import DataMatrixEncoder
encoder = DataMatrixEncoder('This is a DataMatrix.')
Now you are ready to build an image from this Dockerfile. Run:
docker build -t python-barcode .
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:
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.