Advertisements

How to containerize a python flask application ?

Containerization is one of the fast growing and powerful technologies in software Industry. With this technology, user can build, ship and deploy the applications (standalone and distributed) seamlessly. Here are the simple steps to containerize a python flask application.

Step 1:
Develop your flask application. Here for demonstration I am using a very simple flask application. You can use yours and proceed with the remaining steps. If you are new to this technology, I would recommend you to start with this simple program. As usual with all the tutorials, here also I am using a “Hello World” program. Since we are discussing about Docker, we can call it as “Hello Docker”. I will demonstrate the containerization of an advanced application in my next post.

import json
from flask import Flask

app = Flask(__name__)

@app.route("/requestme", methods = ["GET"])
def hello():
    response = {"message":"Hello Docker.!!"}
    return json.dumps(response)


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=9090, debug=True)

Step 2:
Ensure the project is properly packaged and the dependencies are mentioned in the requirements.txt. A properly packaged project is easy to manage. All the dependent packages are required in the code execution environment. The dependencies will be installed based on the requirements.txt. So prepare the dependency list properly and add it in the requirements.txt file. Since our program is a simple one module application, there is nothing to package much. Here I am keeping the python file and the requirements.txt in a folder named myproject (Not using any package structure)

 

Step 3:
Create the Dockerfile. The file should be with the name “Dockerfile“. Here I have used python 2 base image. If you use python:3, then python 3 will be the base image. So based on your requirement, you can select the base image.

FROM python:2
ADD myproject /
WORKDIR /myproject
RUN pip install -r requirements.txt
CMD [ "python", ".myflaskapp.py" ]

Ensure you create the Dockerfile without any extension. Docker may not recognize the file with .txt extension.

Step 4:
Build an image using the Dockerfile. Ensure we keep the python project and the Dockerfile in proper locations.
Run the following command from the location where the Dockerfile is kept. The syntax of the command is given below

docker build -t [imagename]:[tag] [location]

The framed command is given below. Here I am executing the build command from the same location as that of the Dockerfile and the project, so I am using ‘dot’ as the location. If the Docker file is located in a different location, you can specify it using the option -f or using –file.

docker build -t myflaskapp:latest .

Step 5:
Run a container from the image

docker run -d -p 9090:9090 --name myfirstapp myflask:latest

Step 6:
Verify the application
List the running containers

docker ps | grep myfirstapp

Now your application is containerized.

pythonContainer_docker

Step 7:
Save the docker image locally. The following command will save the docker image as a tar file. You can take this file to any other environment and use it.

docker save myflaskapp > myflaskapp.tar

Save the docker image to Dockerhub also.

In this way you can ship and run your application anywhere.

Advertisements

What is MQTT and Where is it used widely ?

MQTT is a very light weight protocol used commonly in sensor communications. MQTT stands for MQ Telemetry Transport. Unlike other messaging protocols, this is very simple, light weight and requires only very low bandwidth. Because of these features, it is widely used in sensor networks. Now with the emerge of Internet of Things, MQTT became very popular. Since it is very light, it consumes very less power and is ideal for low power applications. MQTT messages are delivered asynchronously through a publish-subscribe mechanism. The message packets are specially crafted in such a way to reduce the data size.

The basic communication model in an MQTT system is shown below.

mqtt

Common terminologies in MQTT

Publisher – The one who publishes the messages. Usually the sensors emits the messages. For example in a temparature monitoring scenario, the temparature sensor emits the temparature frequently and the values are displayed in the mobile application. Here the sensor is publisher and the mobile application is the subscriber.

Subscriber – Subscriber is the one who subscribes the messages.

MQTT Client – A client can be a subscriber or publisher. A single client can act as a publisher as well as subscriber. MQTT client libraries are available in almost all programming languages. The complete list is available in MQTT wiki.

MQTT Broker/Server -All the clients are connected to the broker. This is the heart of the MQTT system. Depending upon the implementation, a broker can handle thousands of concurrently connected MQTT clients. The broker needs to be configured in such a way that it is accessible to all the clients. A client can be configured within any NAT network, but the broker needs to directly accessible from all the clients. There are several broker variants available. Some of them are Mosquitto, HiveMQ, Mosca, emqttd etc. Based on your choice and your application needs, you can choose one among these.

Topic – This is a UTF-8 string used by the broker to filter the messages for each connected client. There can be N number of topics. Topic is case sensitive.

MosquittoMQTT is one of the widely used MQTT servers. I have used Mosquitto in many projects. This can be easily installed in Linux and Windows.

By default MQTT uses TCP port 1883 for communication and for SSL enabled communication, it uses port 8883. These are configurable values and it can be changed.

Security

The messages can be secured with username and password. Communication with SSL is also possible. Apart from these, there is no advanced security mechanism present in MQTT. But we can have our own custom message encryption/decryption logic.

There are a lot to explain about MQTT. Instead of writing more, I feel it is better to demonstrate the working of a real implementation. I will be publishing a post on the real implementation of MQTT soon.

Configure Network in CentOS / RHEL from command line

How many of you are aware of a text user interface for network configuration ?. A tool called NMTUI (Network Manager Text User Interface) is available in CentOS and Redhat systems. You can simply open this by typing nmtui in the command line.

If this command is not available, you have to install the NetworkManager-tui package.

yum install NetworkManager-tui

If you type nmtui command in command line, the following console will open up. You can configure the network configurations in the opened console. You can

nmtui

nmtui

Disable Sleep mode in CentOS7/RHEL7 laptop on lid close

The following tip will help you to disable the powersaving or sleep mode behavior of your CentOS or RHEL laptop or desktop. If GUI is present, the following steps will help.

Applications => Utilities => Tweak Tool => Shell => Don't suspend on lid close => ON

But if GUI is not installed, then the only option is to disable this from the commandline. It is very easy, don’t worry. Who cares about the GUI in Linux. ? 🙂 (I love the black screen)

Open /etc/systemd/logind.conf, then make edit in the following configuration. By default, the value of this config will be suspend

HandleLidSwitch=ignore

man logind.conf will provide the complete details about this configuration file. Hope this tip helps.

 

Disable auto restart policy of docker container

If a docker container is started with –restart=always, then the container will not allow you to stop it.  We can change this behavior by modifying the restart policy. Refer the docker  official documentation for more info

For example

docker run -d --restart=always -p 80:80 -it nginx

To modify this behavior, try the following command.

docker update --restart=no your-container

Another option that allows us to stop the container manually is

docker update --restart=unless-stopped your-container

How to start Docker API in CentOS 6

Add the following lines to the /etc/sysconfig/docker file and restart the docker

other_args="-H tcp://0.0.0.0:4243 -H unix:///var/run/docker.sock"

Restart Docker

service docker restart

Now check the docker API using the following command

curl host:4243/info

How to verify whether a private key matches with the SSL certificate ?

This is a very common question that comes to our mind while setting up SSL in our applications. How to verify whether the key matches with the SSL certificate ?

A very easy way to verify that is given below.

We need to compare the modulus of the certificate against the modulus of the private key.

Execute the below command to get the modulus of a certificate.

openssl x509 -noout -modulus -in mycertificate.crt | openssl md5

This will generate the modulus something like e091f305089662689d62126d49910031 

Execute the below command to get the modulus of a private key.

openssl rsa -noout -modulus -in mykey.key | openssl md5

This will generate the modulus of the private key. You should get the key modulus as same as certificate modulus above. i.e e091f305089662689d62126d49910031

If both the modulus are same, we can say that the certificate and the key are matching.