Run your Python script in a docker container
2022-05-24
With this step by step tutorial, you can run your Python scripts in a docker container. This will not only isolate your script from your system, it also provides a way to use the latest python version for your script.

Unrelated cat
You should have installed docker on your computer for this tutorial. You also need some Python script that you will run in the container. For your convenience, here is a little Python program that will print a message.
# A simple python script
def hello_docker(value):
print(f'Hi, {value}') # Press Ctrl+F8 to toggle the breakpoint.
if __name__ == '__main__':
hello_docker('Python')
File: main.py
Create a new folder with a file named main.py in that folder.
Dockerfile
The container image is create with a Dockerfile. The following Docker file will use the latest Python image provided by
FROM python:latest
COPY main.py .
CMD [ "python", "./main.py" ]
File: Dockerfile
That is all you need. The image used in this Dockerfile is the offical python image maintained by the Docker Community. We can now create our own image that includes the script from the command line.
# docker build -t coseos/python-docker-example .
Create docker image
Once the image is created, we will use it to run our script in a container
# docker run -i -t --rm coseos/python-docker-example:latest
Run script in container
This will run the container in interactive mode and remove the container once the script is completed.
Summary
Using docker to run a python script in a container is simple and provides a lot of power.