How to create containerized Python development environment using Dockers ?

Hello Everyone, In this article, I will demonstrate how to create your Docker based Python runtime environment. Assume you’re in the folder where you have your python code in a file named main.py and requirements.txt Lets first build our Python container with this setup. With your favorite editor, open a file named pyDockerfile, lets go with custom names instead of default Dockerfile, It would be easy to manage. But its your choice, I am going with pyDockerfile And add below code

FROM python:3.6
RUN mkdir /app
WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY main.py .

ENTRYPOINT ["python"]
CMD ["main.py"]
We are downloading/pulling Python3.6 image creating /app directory inside the container switching context or as current working directory to /app copy the requirements.txt file install the requirements with pip copy main source code, which is in main.py in my case Adding entrypoint as python so strictly my container will accept python based arguments. and executing my code in main.py In your host machine lets create a sample requirements.txt file as

requests
And main.py

import requests
url = {
"google": "https://google.com",
"azure" : "https://portal.azure.com"
}
for item in url :
req = requests.get(url[item])
print(f"{item}", req.status_code)
Now lets build our image

$ docker build -t pyrunner -f pyDockerfile .
adding tag to our image as pyrunner as I have used custom name for dockerfile pyDockerfile once image created lats verify

docker image list
# or
docker images
Verify output of our images by running

docker container run --rm -it pyrunner
You should see output as

google 200
azure 200
Lets modify our code in main.py as

import requests

url = {
    "facebook": "https://facebook.com",
    "google": "https://google.com",
    "azure" : "https://portal.azure.com"
}

for item in url :
    req = requests.get(url[item])
    print(f"{item}", req.status_code)

We have added a new URL for facebook. Lets start a container with command as below

 docker container run --rm -it -v $(pwd):/app pyrunner
 

--rm : this is delete the container immediately after execution completed. -v we are using volume concept and mounting the current directory where we havemain.py and requirements.txt file and mounting at /app mount point in the remote directory. and you should seeing the output as below

facebook 200
google 200
azure 200
so as you have seen we have done changes to our code and our container adopted that automatically in its next execution.

0 comments:

Post a Comment