Hello World from Docker
1 minute setup to run a python script with Docker
Docker is a platform for developing, shipping, and running applications in containers. Containers are lightweight, portable units that encapsulate an application and its dependencies.
In other words Docker packages applications and all the things they need to run, making it easy to move them around. It ensures that what works on one computer will work on another, reducing issues and making things run smoothly. Think of it as a reliable way to ship and run software.
1. Install Docker from here
Follow the installer instructions and you should be able to run from your terminal:
docker -v
2. Create a folder docker_hello_world: in this folder we will create the following files.
3. Create a python script hello_world.py
# Print Hello from the current OS and architecture
#
# python hello_world.py
import platform
if __name__ == '__main__':
# Get the operating system name
os_name = platform.system()
# Get the system's architecture
architecture = platform.architecture()
print(f"Hello Wordl! from {os_name} operating system on {architecture[0]} {architecture[1]} architecture")
else:
pass
Try to run the script:
python hello_world.py
3. Create a Dockerfile
# Use an official Python runtime as a parent image
FROM python:3.8-slim
# Set the working directory in the container
WORKDIR /app
# Copy the local directory contents into the container at /app
COPY . /app
# Run Python script when the container launches
CMD ["python", "hello_world.py"]
Now if you run ls command you should see something like this:
4. Build the docker image
docker build -t my-python-image .
5. Run the container
docker run -v .:/app my-python-image
As we can see the OS and the architecture is different from our previous run. Of course this is due to the fact that now we are running the python script from the container and not the host system.
Without counting the Docker installation time did I kept my initial promise that only 1 minute was needed to do this?
Refer to Docker docs for more information, in this quick article I just wanted to show you how to run a python script with Docker in the easiest way.
Outro
I hope the story was interesting and thank you for taking the time to read it. On my Blogspot you can find the same post in Italian. Let me know if you have any question and if you like the content that I create feel free to buy me a coffee.