Run containerized python app in kubernetes

Run containerized python app in kubernetes

First of all we need a Docker image that will be run inside the kubernetes cluster. So I assumed that we already have a kubernetes cluster. So the next we do is to build the docker image or you can use your docker image yourself.

But in this tutorial, I will show you how to run the containerized python app with my version from the start.

What we need

These applications should be installed on your local machine before get started. In my case, I use my remote server with ubuntu 16.04 installed.

1. Docker
2. Kubernetes

Setup Kubernetes on Ubuntu 16.04

Build docker image

Let’s begin with clone of of my repo that contains Dockerfile to build the image:

$ git clone https://github.com/muffat/docker-images.git
$ cd docker-images/simple-python-app/
~/docker-images/simple-python-app$ sudo docker build -t simple .

Wait until the process successfully built. And then you’ll see a new docker image when you type this command:

$ docker images

Push docker image to repository (docker hub)

Before pushing the image to docker hub, we need to tag the successfully built image.

$ docker tag fbd064597ae4 cerpin/simple:1.0

Push the image

$ docker push cerpin/simple
The push refers to a repository [docker.io/cerpin/simple]
bc69ee44ef1a: Pushed 
7957c9ab59bb: Pushed 
2366fc011ccb: Pushed 
b18f9eea2de6: Pushed 
6213b3fcd974: Pushed 
fa767832af66: Pushed 
bcff331e13e3: Mounted from cerpin/test 
2166dba7c95b: Mounted from cerpin/test 
5e95929b2798: Mounted from cerpin/test 
c2af38e6b250: Mounted from cerpin/test 
0a42ee6ceccb: Mounted from cerpin/test

After it pushed. You will have the docker image in the repository and ready to use it:

cerpin/simple:1.0

Run the image in kubernetes

First of all, I’m not a big fan of kubectl command, so I usually make a symlink to create the shorter version of kubectl:

$ sudo ln -s /usr/bin/kubectl /usr/bin/cap

Run the docker image in kubernetes

$ cap run simple --image=cerpin/simple:1.0

Then the container will be created. Just wait a moment until the state becomes Running

$ cap get pods
simple-79d85db8b9-466kd 1/1 Running 0 26m

After it’s ready, expose the service with port 5002 to become LoadBalancer. So the service will be accessible from the outside world

$ cap expose deployment simple --type=LoadBalancer --port=5002

Check the service that has been exposed:

$ cap get services
simple LoadBalancer 10.105.115.251 <pending> 5002:31969/TCP 21m

You will see that the service will have forwarded port to 31969 from 5002.

If you open up the browser and navigate to http://external IP:31969, you’ll see the app is running.

Or, just use a curl command instead:

$ curl http://167.xxx.xxx.xxx:31969
{
"message": "welcome", 
"status": "ok"
}