In this article, we will be looking at how to create Flask Docker Container. This article is all about python with flask. In order to deploy flask with docker, we will need to create Python Flask Dockerfile. We will not be executing any flask python examples, instead, we would simply deploy flask app with docker. The container service would be accessible to our localhost machine as well. And later, we would also see how to deploy flask app with docker compose file. Let’s begin.
Table of Content
- Python with Flask
- Create HTML Layout for View
- Creating Python Requirements File
- Create Python Flask Dockerfile
- Create Docker Compose Flask
STEP 1: Python with Flask
In order to create python flask web apps, and then deploy flask with docker, we need to first install Flask. First, create a directory called “flask_app”. Then go inside this directory and open a terminal, then execute this command to install Flask:
pip install Flask
After the Flash has been completely installed, create a file called “view.py”. This file will be used as a routing point for receiving and responding to the HTTP requests. Copy the below code inside the view.py file.
from flask import Flask, render_template, request, session, url_for, redirect import os app = Flask(__name__) @app.route('/', methods=['POST', 'GET']) def home(): return render_template('index.html') if __name__ == "__main__": port = int(os.environ.get('PORT', 5000)) app.run(debug=True, host='0.0.0.0', port=port)
In the above code, we have imported flask and other important libraries. Then we have created a routing point with @app.route annotation, for the home page. This annotation redirects to the HTML layout mentioned inside the home() function, whenever the URL (‘/’) is hit. We have also added a method parameter in this annotation, setting values to GET and POST. This is so that home() function could handle both GET and POST requests sent from the view for this URL. Lastly, we are exposing our web server on port 5000.
STEP 2: Create HTML Layout for View
Earlier, we created a routing point for the home page which was rendering an HTML template with the name “index.html”. This HTML layout will be rendering the view in our python flask app. For more details on how Python Flask works, check out python flask documentation. But we have not created any HTML layout as of yet. So, let’s do that.
Inside “flask_app”, create another folder called “templates”. By default, the python flask app looks for a folder called templates, which would contain all the HTML view layouts. Go into the folder templates and create a file called “index.html”. Open the index.html file in a text editor and copy the following code inside of it:
Welcome to Python with Flask
In this python flask tutorial, we will deploy flask with docker. And then run its service on our localhost machine.
Now we have created our python flask app. Try to run the project by the following command and then go to a browser and type the URL: http://localhost:5000
STEP 3: Creating Python Requirements File
In the last step, we created a python flask app with a single routing point. Additionally, you could also create another python script file for all python flask API. And then import this new file into view.py and access all API endpoints. However, we are now going to create flask docker file and hence deploy flask app with docker. Let’s begin.
While being in the root directory (“flask_app”), execute the following command:
pip freeze > requirements.txt
This command will create a requirements.txt file in your root directory. It will contain a long list of all the packages and libraries that are installed. However, some of the packages may not be necessary for your python Flask app to run. So, you can remove those according to your project requirements. The need for this requirement.txt file is so that you don’t have to execute the “pip install” command for each of these packages.
Your requirements.txt file, should at the bare minimum, must include these packages:
click==8.0.3 colorama==0.4.4 Flask==2.0.2 itsdangerous==2.0.1 Jinja2==3.0.3 MarkupSafe==2.0.1 Werkzeug==2.0.2 gunicorn==20.1.0
STEP 4: Create Python Flask Dockerfile
Lastly, it is time to deploy our python web application through the flask docker container. For that, we need to create flask docker file. In the root directory, create a file named “Dockerfile” and copy the below code inside it.
# start by pulling the python image FROM python:3.8-alpine # switch working directory WORKDIR /app # copy the requirements file into the image COPY ./requirements.txt /app/requirements.txt # install the dependencies and packages in the requirements file RUN pip install -r requirements.txt # copy every content from the local file to the image COPY . /app # configure the container to run in an executed manner ENTRYPOINT [ "python" ] CMD ["view.py" ]
FROM python:3.8-alpine : This command downloads “python:3.8-alpine” image from Docker hub and this becomes the base image of your container.
WORKDIR /app : this command sets the working directory inside of the container, which will be /app folder. In other words, the root directory of the container.
COPY ./requirements.txt /app/requirements.txt : This command will copy the requirements.txt file from your host machine and paste it inside of the container in the /app/ directory with the same name.
RUN pip install -r requirements.txt : This command will “pip install” all the packages listed inside of the requirements.txt file in a loop. The “-r” flag mean recursively (i.e. loop)
COPY . /app : This command will copy all of the files and content from your host machine flask_app directory and paste it inside the /app folder. Which is the root directory of the container.
ENTRYPOINT [ “python”, “view.py” ] : This is the final command, which executes inside the container after completing all steps above and starts the project. It works the same way when you run “python view.py” to run your project on your localhost machine.
Build Flask Docker Container:
Now that we have created a python flask dockerfile, let’s see how to finally build it and run its service. By ‘build’ I mean to use Dockerfile and build a Docker Image. Which would contain all the specification and requirements that we have set in the python flask Dockerfile. Make sure that you are inside flask_app folder, and then execute the following command to build the Flask Docker Image.
docker image build -t flask_docker .
This will start to build the image. Once done, you can check if the image is created by listing all the Docker image on your machine:
Run Flask Docker Container:
Now finally to run python with flask, using docker. To do this, simply execute the following command:
docker run -p 5000:5000 -d flask_docker
-p 5000:5000 : This is connecting or exposing the service port running inside the container to the port on your localhost machine. This is so that you can have access to the service on your localhost machine, while the service is actually running in the container.
-d : This is a flag that keeps the service running in the background. Otherwise, the container would run and exit immediately.
Let’s see if it’s working. Open a browser and go to this URL: http://localhost:5000
STEP 5: Create Docker Compose Flask
In order to deploy flask with docker using Docker Compose, all the above steps must already be completed. Afterward, you need to follow the below steps:
1. Push your python flask app Docker Image to Docker-Hub. (See how it’s done)
2. Create a Docker Compose File
Create a file name “docker-compose.yml” and copy the following code in it:
version: "3.8" services: flask_docker: image: name_of_your_docker_image tty: true stdin_open: true container_name: flask_docker ports: - "5000:5000" volumes: - ./data/:/home/data
version: “3.8” : this is the docker compose file format, reflecting the Docker engine installed on your system. Take reference from here.
service: You will include a list of all the docker container that you want to run inside this tag. In this example, we are only running one container.
This is mentioning the container name and the image that it will use to create the container. The image name would be the same as the one you used to push your image to your Docker Hub account.
This is simply exposing the service port running inside the container to your localhost machine. So you could access the service on your machine.
This is mounting a localhost volume inside the container. Basically, this is done so that there is a common folder where the container and your localhost machine can keep your files. So that you can transfer data from localhost to container, while the container is running. Its main purpose is data persistence, so that data is not wiped off when you restart your container.
3. Run the Docker Compose File
To run docker compose flask file, execute the following command:
docker-compose up -d
And you are done!
- Flask provides support for API while Django doesn’t have any support for API.
- Flask does not support dynamic HTML pages and Django offers dynamic HTML pages.
- Flask is a Python web framework built for rapid development whereas Django is built for easy and simple projects.
- Flask offers a diversified working style while Django offers a Monolithic working style.
- URL dispatcher of the Flask web framework is a RESTful request on the other hand, URL dispatcher of Django framework is based on controller-regex.
- Flask is WSGI framework while Django is a Full Stack Web Framework.
Docker is used for running isolated application or services in a compact container, with very minimalistic list of dependencies, to be deployed on a server machine.
As mentioned in the official documentation:
‘Docker uses a client-server architecture. The Docker client talks to the Docker daemon, which does the heavy lifting of building, running, and distributing your Docker containers. The Docker client and daemon can run on the same system, or you can connect a Docker client to a remote Docker daemon. The Docker client and daemon communicate using a REST API, over UNIX sockets or a network interface. Another Docker client is Docker Compose, that lets you work with applications consisting of a set of containers.’
Mirantis, a cloud computing company acquired Docker in 2019.