How to Run a Python Script using Docker?
The task is to build a docker image and execute a python script that adds two given numbers. This has been achieved via a series of steps.
Step 1: Creating the Files and Folders
We will be creating a Folder docker_2 at the desktop location in our PC . Inside the Folder another Folder called docker_assignment is created. Then two files dockerfile and test.py are created in this folder.
Folder
Step 2: Creating the Dockerfile
Inside the dockerfile we will start by first taking the python base image from docker hub. A tag latest is used to get the latest official python image. It is very important to set your working directory inside your container. I have chosen /usr/src/app. All commands will be executed here as well as the images will be copied here only.
I have then copied the test.py file from my pc to the container current working directory(./ or /usr/src/app) by using the COPY command.
#Deriving the latest base image FROM python:latest #Labels as key value pair LABEL Maintainer="roushan.me17" # Any working directory can be chosen as per choice like '/' or '/home' etc # i have chosen /usr/app/src WORKDIR /usr/app/src #to COPY the remote file at working directory in container COPY test.py ./ # Now the structure looks like this '/usr/app/src/test.py' #CMD instruction should be used to run the software #contained by your image, along with any arguments. CMD [ "python", "./test.py"]
Step 3: Building the Docker Container
After you have created both the Python script and the Dockerfile, you can now use the Docker build command to build your Docker Image.
Here -t is for adding tags so as to identify your image easily.
docker image build -t python:0.0.1 /home/roushan/Desktop/docker_2/docker_assignment
Step 4: Verify the Image Build
After you have built your Docker Image, you can list all the Images to check whether your image has been successfully built or not.
docker images
You will find your Image name listed here and with the tag name, you can easily find it.
Step 5: Running the Docker Container
Now, you can use the Docker run command to run your Docker Container.
docker run python:0.0.1
After running the Docker Container, you will see the output printed after adding the two numbers.
To conclude, in this article, we saw how to build a simple addition Python script and run it inside the Docker Container.
Please Login to comment...