Related Articles

Related Articles

How to Run a Python Script using Docker?
  • Last Updated : 28 Oct, 2020

Python is one of the most popular and widely used programming languages. Right from building a simple GUI app using Tkinter to building a full-fledged web application, Python is used everywhere. In this article, we will see how to create a Docker Container and configure it to run a simple “Hello World” Python script. Yo do so follow the below steps:

Step 1: Creating the Python Script

Create a simple Python Script with called test.py inside a directory (say hello-demo). Copy the below statement inside the Python script and save it inside the directory.

print("Hello World!")

Step 2: Creating the Dockerfile

Inside the same directory, create another file called Docker file. In this file, we will define the sequence of steps needed to create the Docker Image. Take a look at the below Dockerfile template.

FROM python:3
WORKDIR /usr/src/app
COPY . .
CMD ["test.py"]
ENTRYPOINT ["python3"]

In the above Dockerfile, we have pulled the Python 3 Base Image from the Docker Repository. We have set the working directory to /usr/src/app. After that, we have copied all the files to the working directory. Using CMD and ENTRYPOINT instructions, we have instructed the Container to run the test.py Python script when the container is started.

Your directory structure should be: 



files

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.

sudo docker build -t hello-demo .

docker build

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.

sudo docker images

You will find your Image name listed here.

images

Step 5: Running the Docker Container

Now, you can use the Docker run command to run your Docker Container.

sudo docker run -it hello-demo test.py

running the script

After running the Docker Container, you will see the output printed inside the bash.

To conclude, in this article, we saw how to build a simple hello world Python script and run it inside the Docker Container.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :