Showing posts with label docker. Show all posts
Showing posts with label docker. Show all posts

How to dockerize your python application in docker

Dockerize your python application:






Docker is a technology which lets you build, deploy and run your applications. Docker enables you separate your infrastructure from your application. With Docker all you need to do is just write your code,.
dockerize it and distribute it in form of image. That way any one can use your application who is running the Docker.

What do you mean by Dockerize application?

Dockerize mean you write your code on your system then you prepare the image and distribute it over the internet or on DockerHub. You don't have to worry about the underlying infrastructure and dependencies.

Let's write a python program which will count the occurrence of words from a given string.


#Input : string = "Docker is a technology which
# lets you build, deploy and run your applications.";
#Count occurence of words from a given string example


def findFreq(s):
dictt = {}
strng = s.split(" ")
strr1 = set(strng)
for word in strr1:
dictt[word] = s.count(word)
return dictt
if __name__ == "__main__":
x = input("Enter your string:")
#raw_input in python 2.x and input() in python 3.x
print(findFreq(x))

#Output: {'a': 4, 'and': 1, 'run': 1, '': 80,
# 'deploy': 1, 'technology': 1, 'is': 1,
# 'you': 2, 'lets': 1, 'applications.': 1,
# 'which': 1, 'build,': 1, 'Docker': 1, 'your': 1}

Save this file with findfrequency.py in same directory. I am saving it in current directory for my convenience but you can save it anywhere and pass the absolute path.


Now lets create a Dockerfile.


FROM python:3

We need to use python in docker so we are using FROM keyword so this will create layer from python image. Means your image is based on python image. 

Now we need to run our python file so we need to add this file to Dockerfile.

ADD findfrequency.py /

Use CMD to execute commands when image loads

CMD ["python", "./findfrequency.py"]

Combine all above lines and create a Dockerfile.

FROM python:3
ADD findfrequency.py /
CMD ["python", "./findfrequency.py"]

So we have created a Dockerfile now. I saved it with the name "Dockerfile" in current directory. When you run docker build .     command then docker looks for Dockerfile if ithis file doesn't exist or file name is wrong or extension is wrong you'll get file not exists error.

Now we are ready to build image from the dockerfile. 

Open the terminal and run the below command and make sure you are in the same directory where you saved your Dockerfile as well as python file.

docker build -t myapp .


-t : This is tagging a name to your image. In this case I gave my image a name "myapp"
.(dot) : Is current directory

Ok so you have successfully build your image. Now Let's check what's inside the image by inspecting it.

docker inspect myapp

[

    {

        "Id": "sha256:c4595feabbd0b9aba4ae67037ea3c43a8c0aaf2abe6f6fd28d25b22a7cf9",

        "RepoTags": [

            "myapp:latest"

        ],

        "RepoDigests": [],

        "Parent": "",

        "Comment": "buildkit.dockerfile.v0",

        "Created": "2021-10-01T08:42:53.450488763Z",

        "Container": "",

        "ContainerConfig": {

            "Hostname": "",

            "Domainname": "",

            "User": "",

            "AttachStdin": false,

            "AttachStdout": false,

            "AttachStderr": false,

            "Tty": false,

            "OpenStdin": false,

            "StdinOnce": false,

            "Env": null,

            "Cmd": null,

            "Image": "",

            "Volumes": null,

            "WorkingDir": "",

            "Entrypoint": null,

            "OnBuild": null,

            "Labels": null

        },

        "DockerVersion": "",

        "Author": "",

        "Config": {

            "Hostname": "",

            "Domainname": "",

            "User": "",

            "AttachStdin": false,

            "AttachStdout": false,

            "AttachStderr": false,

            "Tty": false,

            "OpenStdin": false,

            "StdinOnce": false,

            "Env": [

                

                "LANG=C.UTF-8",

                "PYTHON_VERSION=3.9.7",

                "PYTHON_PIP_VERSION=21.2.4",

                "PYTHON_SETUPTOOLS_VERSION=57.5.0",

                "PYTHON_GET_PIP_SHA256=fa6f3fb93cce234cd4e8dd2be9c247653b52855a48dd44e6b21ff28b"

            ],

            "Cmd": [

                "python",

                "./findfrequency.py"

            ],


You'll see output something like above. Our python function is there inside the output under CMD tag.

Let's run the image.

docker run -it myapp   

Enter your string: This is my test to test dockerfile. 

{'': 37, 'is': 2, 'dockerfile.': 1, 'to': 1, 'my': 1, 'test': 2, 'This': 1}


See the output above and pass the desired string to count the words.

So we have successfully dockerized our application. You can send this image to others so that they can use your program and they don't have to worry about installing any dependencies which can cause your program to crash. 

How to create a Dockerfile to automate the build image process

 Creating a Dockerfile




Dockerfile is a text file which contains set of commands which are used by user to build an image via command line. Dockerfile is an automated way to build an image with set of commands.

Docker build is a command which builds an image from Dockerfile. Let's create a docker file and put some commands inside it. 

touch Dockerfile


Above touch command is used to create a new file on mac/linux. Make sure you create the docker file in current directory. Although you can create the docker file anywhere but for convenience I am creating it on current directory. So that I don't have to type the absolute path for docker file.

Always remember these three commands while creating a new docker file - 

FROM : This creates a layer from docker image
RUN : builds your application
MAINTAINER : Best practice to put the name of maintainer of the image
CMD : Run the commands inside container 

I have created the dockerfile and put the below text inside dockerfile.

FROM ubuntu


MAINTAINER DATATIPSS


RUN apt-get update


CMD ["echo","This is my first image using dockerfile"]


I am using ubuntu as base image and giving maintainer as datatipss. You can give your name. 

Now run the docker file using docker build -t myapp .  command

Here -t : tag your image or giving a name to your image and .(dot) is running dockerfile in current directory.

docker build -t myapp .

[+] Building 79.3s (6/6) FINISHED                                                                                                                             

 => [internal] load build definition from Dockerfile                                                                                                     0.0s

 => => transferring dockerfile: 152B                                                                                                                     0.0s

 => [internal] load .dockerignore                                                                                                                        0.0s

 => => transferring context: 2B                                                                                                                          0.0s

 => [internal] load metadata for docker.io/library/ubuntu:latest                                                                                         7.9s

 => [1/2] FROM docker.io/library/ubuntu@sha256:9d6a8699fb5c9c39cf71bd6219f0400981c570894cd8cbea30d3424a31f                                          7.3s

 => => resolve docker.io/library/ubuntu@sha256: 9d6a8699fb5c9c39cf71bd6219f0400981c570894cd8cbea30d3424a31f                                          0.0s

 => => sha256: 9d6a8699fb5c9c39cf71bd6219f0400981c570894cd8cbea30d3424a31f 1.42kB / 1.42kB                                                           0.0s

 => => sha256: 9d6a8699fb5c9c39cf71bd6219f0400981c570894cd8cbea30d3424a31f 529B / 529B                                                               0.0s

 => => sha256:54ab604fab8d1b3d1c8e02509cc7031f8541428051401f4122619e5968e16 1.48kB / 1.48kB                                                           0.0s

 => => sha256:ab2d02b1ec420fdb84c9f52abda403b6a0f5de904a2ecda5ae4f5cd6e4d46 27.17MB / 27.17MB                                                         6.6s

 => => extracting sha256:ab2d02b1ec420fdb84c9f52abda403b6ae0f5de904a2ecda5ae4f5cd6e4d46                                                                0.7s

 => [2/2] RUN apt-get update                                                                                                                            63.9s

 => exporting to image                                                                                                                                   0.0s

 => => exporting layers                                                                                                                                  0.0s

 => => writing image sha256:76ff7254c9ca346bfe34c42c3f7c17ad0958e70210f01f9e200cbdadb2e4f   



Ok now you have successfully created your image. Let's check and run the image using docker run imageid_or_image_name command.

Check images first:

docker images

REPOSITORY        TAG       IMAGE ID       CREATED         SIZE

myapp             latest    76ff7254c9ca   3 minutes ago   92.2MB


Now run the image:

docker run myapp

This is my first image using dockerfile



So we have successfully created our first image and ran it. 

Also you can inspect the image and get insights of it. If you are using image build by someone else so before running it you can always inspect it to check if it is legitimate image. You can inspect any image and check the author and what commands are inside the image.

In this case you can check the author is datatipss and under cmd tag it's echo command only.

docker image inspect myapp

[

    {

        "Id": "sha256:76ff7254c9ca346bfe34c42c3f7c1958e70210f01f9e200cbdadb2e4f",

        "RepoTags": [

            "myapp:latest"

        ],

        "RepoDigests": [],

        "Parent": "",

        "Comment": "buildkit.dockerfile.v0",

        "Created": "2021-09-28T17:40:34.86456821Z",

        "Container": "",

        "ContainerConfig": {

            "Hostname": "",

            "Domainname": "",

            "User": "",

            "AttachStdin": false,

            "AttachStdout": false,

            "AttachStderr": false,

            "Tty": false,

            "OpenStdin": false,

            "StdinOnce": false,

            "Env": null,

            "Cmd": null,

            "Image": "",

            "Volumes": null,

            "WorkingDir": "",

            "Entrypoint": null,

            "OnBuild": null,

            "Labels": null

        },

        "DockerVersion": "",

        "Author": "DATATIPSS",

        "Config": {

            "Hostname": "",

            "Domainname": "",

            "User": "",

            "AttachStdin": false,

            "AttachStdout": false,

            "AttachStderr": false,

            "Tty": false,

            "OpenStdin": false,

            "StdinOnce": false,

            "Env": [

                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

            ],

            "Cmd": [

                "echo",

                "This is my first image using dockerfile"

            ],

            "ArgsEscaped": true,

            "Image": "",

            "Volumes": null,

            "WorkingDir": "",

            "Entrypoint": null,

            "OnBuild": null,

            "Labels": null

        },

        "Architecture": "arm64",

        "Variant": "v8",

        "Os": "linux",

        "Size": 92173773,

        "VirtualSize": 92173773,

        "GraphDriver": {

            "Data": {

                "LowerDir": "/var/lib/docker/overlay2/76ff7254c9ca346bfe34c42c3f7c1958e70210f01f9e200cbdadb2e4f/diff",

                "MergedDir": "/var/lib/docker/overlay2/c7dp26x65obhv96p76ff9lbo1/merged",

                "UpperDir": "/var/lib/docker/overlay2/c7dp26x65obhv96p76ff9lbo1/diff",

                "WorkDir": "/var/lib/docker/overlay2/c7dp26x65obhv96p76ff9lbo1/work"

            },

            "Name": "overlay2"

        },

        "RootFS": {

            "Type": "layers",

            "Layers": [

                "sha256: 76ff7254c9ca346bfe34c42c3f7c1958e70210f01f9e200cbdadb2e4f",

                "sha256:ecd02c9154cf7dc6fa2257f9378687064ebbb87524aa7191a683650b0c"

            ]

        },

        "Metadata": {

            "LastTagTime": "2021-09-28T17:43:44.89023209Z"

        }

    }

]


That way you can check what's going to run from the image. Once you build your image you can make it publicly available for everyone. You can upload it on DockerHub and anyone can use it. 

You can build multiple images of multiple applications and distribute it over the internet so that anyone can use your docker image. 

Running Jenkins in Docker Container

How to run Jenkins in Docker Container

Are you looking to start with Jenkins but you don't want to setup on your host machine. Instead you want to try it on Docker? Then you are on right place. We will run the Jenkins in Docker Container.


Let's understand the Jenkins first

Jenkins is an open source automation server which can be used to automate all sorts of tasks including building, testing and deploying the software.

Jenkins can be installed through Docker or can be run standalone by any machine with Java Runtime Environment(JRE).

Pull the Jenkins Image

Below docker command will be used to download/pull the image from DockerHub.

docker pull jenkins/jenkins

docker pull jenkins/jenkins

Using default tag: latest

latest: Pulling from jenkins/jenkins

ffacddc51d82: Pull complete 

781188a9e523: Pull complete 

69a15122fa9e: Pull complete 

1ab7a0b3a992: Pull complete 

990ebae0b67d: Pull complete 

dabca586d152: Pull complete 

f2d0d9a7d002: Pull complete 

4ac45f07946b: Pull complete 

afa4a0ea0cf8: Pull complete 

a20c227120b1: Pull complete 

5ed87337d302: Pull complete 

a64886bb3f9f: Pull complete 

52920e8e3e8d: Pull complete 

2639292b661e: Pull complete 

c001f3ea6952: Pull complete 

bb7385fc1236: Pull complete 

1b9f514ccf6a: Pull complete 

Digest: sha256:76d67d16e06cf63c670405b0f08dcbbbc434ca49b4a5bc9a043b51d6c2b4d285

Status: Downloaded newer image for jenkins/jenkins:latest

docker.io/jenkins/jenkins:latest                                           


Run the image using below command

docker run -p 8080:8080 -p 50000:50000 jenkins


This command will store the workspace under /var/jenkins_home. All the plugins and configuration stays under the same path. This can't be persistent so it's always recommended to use docker volume to create persistent data.

Instead you can use below command with bind mount for data persistency.

docker run --name homejenkins -p 8080:8080 -p 50000:50000 -v /var/jenkins_home jenkins/jenkins 

Output will be like below. It has the password to start your jenkins.

*************************************************************

*************************************************************

*************************************************************


Jenkins initial setup is required. An admin user has been created and a password generated.

Please use the following password to proceed to installation:


4772035c16234e769eaa7bcf4278


This may also be found at: /var/jenkins_home/secrets/initialAdminPassword


*************************************************************

*************************************************************

*************************************************************


2021-09-27 18:51:46.657+0000 [id=29] INFO jenkins.InitReactorRunner$1#onAttained: Completed initialization

2021-09-27 18:51:46.666+0000 [id=23] INFO hudson.WebAppMain$3#run: Jenkins is fully up and running

2021-09-27 18:51:59.156+0000 [id=49] INFO h.m.DownloadService$Downloadable#load: Obtained the updated data file for hudson.tasks.Maven.MavenInstaller

2021-09-27 18:51:59.157+0000 [id=49] INFO hudson.util.Retrier#start: Performed the action check updates server successfully at the attempt #1

2021-09-27 18:51:59.161+0000 [id=49] INFO hudson.model.AsyncPeriodicWork#lambda$doRun$0: Finished Download metadata. 58,870 ms


Now go to localhost:8080 on your browser and It will popup a screen asking for this password. Once you'll enter the password for Jenkins it will give you below screen.



Click on Install plugins and wait for couple of minutes as it takes some time to install recommended  plugins. Once installation is done ,you'll get username and password screen. Just put your username and password and save it. You are all set to use Jenkins.

Tip: Make sure you take the backup of your directory volume of Jenkins so that you don't loose any data.

By default you get 2 executers but you can change it and modify your image to set more number of executers.

Once everything is done you'll se below home screen for Jenkins





Click on New Item and select freestyle project and give it name. now go to build environment and select Execute shell script. 

Now paste below command inside build environment. We'll print hello Jenkins then print working directory and then the user, using shell script.

echo 'Hello Jenkins'
pwd
whoami

Click on Apply and save. Now navigate to project and click Build now and your build will be running.
Once your build is completed ,click on green check sign on your build number. It will open the output console and you will see below results on console.

Started by user Pankaj D
Running as SYSTEM
Building in workspace /var/jenkins_home/workspace/simple project
[simple project] $ /bin/sh -xe /tmp/jenkins86668692502344527.sh
+ echo Hello Jenkins
Hello Jenkins
+ pwd
/var/jenkins_home/workspace/simple project
+ whoami
jenkins
Finished: SUCCESS



That was it for running Jenkins on Docker. We can use Jenkins for other options as well like creating a pipeline and integrating with github.

Note: If you think this helped you and you want to learn more stuff on devops, then I would recommend joining the Kodecloud devops course and go for the complete certification path by clicking this link

Quantum Computing: The Future of Supercomputing Explained

  Introduction Quantum computing is revolutionizing the way we solve complex problems that classical computers struggle with. Unlike tradi...