So you made a complex Python application (for example, a web server). You want to make sure it runs on any Linux distribution, and doesn’t interfere with existing applications running on the server. This is where you can pack your app into a Docker container.
For simplicity, let’s assume you have a very simple application with only
main.py and a pip
requirements.txt. To make our app docker-ready, we need to only add one new file called
Dockerfile with no extension. The file will contain a base image requirement for our application and a command to run:
FROM python:3.5.2-onbuild CMD [ "python", "./main.py" ]
I’ve put a simple
print("Hello from main.py") inside the main.py. You can use other python version if your script depends on older 2.*. As usual, all the available versions on are available on docker hub https://hub.docker.com/_/python/. Plus, the Dockerfile can have additional installation steps for your application. Say, you require an external video processing library, or a PDF generation library. In that case you can extend Dockerfile by adding
RUN .. commands:
FROM python:3.5.2-onbuild # for simplicity, just check some main applications versions RUN git --version RUN cpp --version CMD [ "python", "./main.py" ]
Now let’s run the build.
docker build -t python-app:1.0.0 .
This will build the current folder (hence the
-tag it with the name python-app version 1.0.0.
In this case we will see the build running, and we will also see the version of Git and C++ compiler. The result will look something like:
Step 2 : RUN git --version ---> Running in 31b703447adc git version 2.1.4 ---> 79cc684f89e5 Removing intermediate container 31b703447adc Step 3 : RUN cpp --version ---> Running in 223979db4455 cpp (Debian 4.9.2-10) 4.9.2 Copyright (C) 2014 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
This means they are there and running fine and you can use them. Now let’s run our script:
docker run -it --rm --name my-app python-app:1.0.0
If everything was fine (which it should be) then you should see:
Hello from main.py
That’s it, you now have made a Dockerfile with your app, which everyone can run on any system.