What if you were asked to deploy your Python Flask Application or dockerize Flask app 100 times a day on a Virtual Machine? Most people would agree that it’d be a tedious and frustrating task. In this article, we show you how to Dockerize Flask Python Application to overcome the above scenario.
Setting up a machine manually to deploy your Python Flask Application multiple times can easily lead to human errors and also increase the chances of missing certain dependencies. It takes plenty of time to figure out the errors, fix them, and then deploy the applications.
Now, if you were asked to share the Python Flask or any other application with your team members across the globe, how would you do that? If you think you will not be able to share the machine, you are right. You can create a snapshot of the machine but that’s about it. In this article, we will also see how the Dockerized Python Flask Application can be used by global teams residing at different places.
Before we dive into the nitty-gritty of “How to Dockerize Flask Python Application”, let’s see the components that we are going to deploy as Docker Containers.
Docker is an open platform written in the Go language for developing, shipping, and running applications. It enables applications to separate from the infrastructure which results in better speed. It makes it possible to manage the infrastructure the same as we manage the applications. To achieve this, Docker uses a client-server architecture and has the following components.
If you’re interested in learning more about Docker, you can access its official guide here .
Before we proceed let’s see the steps to install Docker on Ubuntu 20.04 Server.
Now you have Docker installed on your machine. To know more about installation and other installation alternatives, click here. . To know more about post-installation steps, click here.
A Docker Container is an object in the Docker Engine that bundles up the code and all its dependencies, it is a running instance of the Docker Image, i.e. Docker Images become Docker Containers when they run on a Docker Engine.
Docker Containers virtualize the Operating System(OS), unlike Virtual Machines that virtualize the hardware.
A Docker Container is a loosely isolated environment where the application runs.
It can be created on Linux OS or Windows OS. Docker Containers provide flexibility in deploying and managing software applications. You can start, stop, delete and perform various operations on a Docker Container using the Docker CLI or API.
Containers can share the same OS, Kernel, and run as isolated processes. They take up less space as compared to virtual machines and can get running in a few seconds.
Let’s get familiar with a few basic commands that we will need in the upcoming sections.
Now that you have docker installed on your machine and you have an idea of docker containers, let’s create a Python Flask Application and dockerize it in the next section.
import redis from flask import Flask app = Flask(__name__) redis = redis.Redis(host='redis', port=6379, db=0) @app.route('/') def hello_world(): return 'This is a Python Flask Application with redis and accessed through Nginx' @app.route('/visitor') def visitor(): redis.incr('visitor') visitor_num = redis.get('visitor').decode("utf-8") return "Visit Number = : %s" % (visitor_num) @app.route('/visitor/reset') def reset_visitor(): redis.set('visitor', 0) visitor_num = redis.get('visitor').decode("utf-8") return "Visitor Count has been reset to %s" % (visitor_num)
Flask vs Django: Read the full blog.
A Dockerfile is a set of instructions in a text file containing all the commands required to generate a Docker Image. The “docker build” command is used to create an image using the Dockerfile. This command also needs additional arguments.
Before we create a Dockerfile for Python Flask Application, let’s try to understand the Dockerfile instructions.
Refer to the official documentation here to know more about Dockerfile instructions.
Now, let’s create a Dockerfile to “Dockerize Flask Python Application” and “Nginx”
FROM python:3.7-alpine RUN mkdir /app WORKDIR /app ADD requirements.txt /app ADD main.py /app RUN pip3 install -r requirements.txt CMD ["gunicorn", "-w 4", "-b", "0.0.0.0:8000", "main:app"]
Flask==1.1.2 redis==3.4.1 gunicorn>=19,<20F
server { listen 80; server_name localhost; location / { proxy_pass http://app:8000; } location /hit { proxy_pass http://app:8000/visitor; } location /hit/reset { proxy_pass http://app:8000/visitor/reset; } }
After creating your Dockerfiles, the next step is to make Docker Images. They will be for Python Flask Application and Nginx using the Dockerfiles we generated. For Redis, we will use a readily available Image.
We can create Docker Images using the “docker build” command, however; this is not the only way. Docker Images can also be created when you run your applications using Docker-Compose
Before we use Docker-Compose to build and deploy applications, let’s just see the syntax of the “docker build” command.
Syntax:
docker build [OPTIONS] PATH | URL | –
We won’t go into details of this command as we will be using Docker-Compose to build Docker Images. If you want to know in detail about this command click here to visit the official documentation.
You probably know by now that it is very convenient to deploy, share and manage software applications using Docker Containers. However, when you have multiple applications to manage, it becomes cumbersome. Docker commands can take a lot of arguments like volume mapping, port mapping, environment variables, command, network, image name, working directory, etc. Imagine you have hundreds of containers to manage, and you still want to keep it simple.
This is why Docker Compose comes into the picture as the next step to manage multi-container applications.
Docker Compose is a tool that helps to define multi-container applications in a file and manage several different containers quickly and easily.
You can use a YAML file to define and configure all your applications. Then, we just need to execute one command “docker-compose up” to get all our applications defined in the YAML file up and running. To destroy the same, we again just need to execute one command “docker-compose down” and to stop applications safely “docker-compose stop” comes to rescue.
The YAML file is used to define services, networks, and volumes. One can use either a .yml or .yaml extension for this docker-compose file.
Let’s install docker-compose as we will need it.
Now it’s time to create a docker-compose file
version: '3'
services:
app:
build: flask
volumes:
- app:/app
ports: - "8000:8000"
links:
- redis:redis
depends_on:
- redis
redis:
image: "redis:alpine"
expose:
- "6379"
proxy:
build: nginx
restart: always
ports:
- 80:80
depends_on:
- app
volumes:
app:
Here are a few more commands you can play with.
Deploying any applications on Production is a very different experience. It is not just writing Dockerfiles, building Images, and using Docker-Compose to deploy the application. A lot can change when you promote the application to Production. Here are a few things that you need to consider while deploying your Python Flask Application on Production.
This section will give you an idea of how to troubleshoot your dockerized applications. When you encounter issues in your Docker environment, run the following checks.
So, now you understand the reason behind using Docker over Virtual Machines. You also got to know the steps to Dockerize Python Flask Application and deploy applications using Docker-Compose.
Docker-Compose is good when containers will only be deployed on a single machine, but it can not provide high availability to the application. Imagine, if the machine goes down, so will all your containers. In the Docker-Compose environment, all containers run on a single machine, and this machine can be a point of failure.
Docker-Compose can be good in the early stages of the container world as it does not have a steep learning curve, however; it has its limitations as mentioned above. Once you become good at Docker-Compose and have reached a certain point, you need to move to one of the Container Orchestration tools such as ECS, EKS, AKS, Kubernetes, Docker-Swarm.
Container Orchestrations tools come with benefits that can help to overcome the limitations of Docker-Compose.
There are other benefits of using Container Orchestration tools for Production Applications, let’s see a few of the Orchestration tools.
AWS Elastic Container Service(ECS) is a fully managed container orchestration service provided by AWS and made available in 2015 in the US East (N. Virginia), US West (Oregon), Asia Pacific (Tokyo), and Europe (Ireland) Regions. One does not need to learn Kubernetes to deploy containerized applications on ECS. It is easily integrated with other AWS services to provide a secure and easy-to-use solution for running containers. One has to pay only for the resources you configure. The smallest object that manages the lifecycle of the container in ECS is a task.
AWS Elastic Kubernetes Service(EKS) is a Kubernetes-as-a-Service platform provided by AWS and made available in 2018. You need to know about Kubernetes to deploy your containerized application on EKS. One can have a fully managed Kubernetes Cluster on AWS, however; one has to pay the additional cost for the Kubernetes control plane. The smallest object that manages the lifecycle of the container in EKS is a pod.
Azure Kubernetes Service(AKS) is a fully managed Kubernetes service provided by Azure. It was released in 2018. While using AKS, one does not have to pay the additional cost of the Kubernetes control plane, but only for the virtual machines, associated storage, and networking resources consumed. You need to know about Kubernetes to deploy your containerized applications on AKS. The smallest object that manages the lifecycle of the container in AKS is a pod.
Containerization offers a solution based on containers for virtualization. It creates an image of the deployable application with all its dependencies and reduces the build and deployment time.
Docker is a container-based virtualization platform that provides a way for fast, and consistent delivery of applications. It helps to scale and run more workloads on the same hardware.
In this article, we saw “How to Dockerize Flask Python Application” and reduce the build and deployment time. We deployed 3 different components, viz. a Python Flask Application, Redis Database, and Nginx Reverse Proxy, in 3 different containers. Dockerizing applications serve as the basis to enable the decomposed microservices-based architecture.
There is no doubt that Docker is a revolutionary technology to provide isolation and environmental independence. To make the best out of it, container orchestration platforms like ECS, EKS, AKS can definitely be a great choice since they make the scenario of having 1000s of containers deploying 100s of microservices much easier.
This blog is also available on Medium
Dockerizing is the process of creating Docker images of your applications, deploying them, and running your applications using Docker containers by making use of the images that you created.
Dockerizing your applications helps you save time that you would otherwise unnecessarily spend on creating VMs, installing dependencies, building and then deploying your applications on those VMs. The time that you saved can be used on your Software Development.
Dockerizing your applications is the first step in the world of containers. Having a few services to deploy can be managed by docker commands, however; when the number of services and the workload increases, you need container orchestration tools or platforms like Docker-Compose, ECS, EKS, AKS, etc. You can choose the platform that suits your requirement.
Yes, Microsoft announced the general availability of Windows Server 2016 and later for Docker Engine – Enterprise, and containers work the same way as it does on Linux. To know more about this, visit the blog here published by Docker.
Discover the steps for developing cloud applications, from costs to cloud app deployment
Imagine launching your product with just the core features, getting honest user feedback, and then…
When a tight deadline is non-negotiable, every second counts! Here’s how we developed and launched…
You may have considered hiring a nearshore software development company or services, but you still have doubts…
End-to-end project management goes as far back as you can remember. Every project in history, even…
AWS DevOps has recently become a trending topic in IT circles as it offers companies…