Containerize a Redis Flask App with Docker Compose

314 VIEWS

·

In this tutorial, we will build a simple Python Flask application and implement Redis for caching. We will then containerize the Redis Flask application using Docker Compose.

Flask is an open-source Python micro framework for building web applications. It is implemented on Werkzeug and Jinja2. Redis is a  vibrant open-source in-memory data store platform. Developers use Redis as a message broker, database, streaming engine, and for application caching. Docker Compose is a powerful Docker tool for creating and running multi-container Docker applications. 

We will use Redis for caching. Caching in computing enables applications to temporarily store data, files, and login details in the Random Access Memory. It enables faster retrievals of that data, and the application will load faster.

Our application will have two containers. The first container will host the Flask application. The other container will be for Redis caching. Docker Compose will run the two containers as a single application. Let’s get started.

Prerequisites

Before you get started, you must understand Docker. You also need the following tools and software set up in your working machine:

Vs Code for code editing.

Python installed.

Docker Desktop set up.

Build a Simple Python Flask application

We build a simple Python Flask application and implement Redis for caching. Let’s install Flask and Redis using the following `pip` commands in your terminal:

pip install flask
pip install redis

After the installation process, create a folder named `flask-redis` on your PC. In the `flask-redis` folder, create a new file named `app.py`. Open the file and add the following Flask code snippet:

from flask import Flask
from redis import Redis

app = Flask(__name__)
redis = Redis(host='redis', port=6379)

@app.route('/')
def hello():
    redis.incr('hits')
    counter = str(redis.get('hits'),'utf-8')
    return "Welcome to this webpage!, This webpage has been viewed "+counter+" time(s)"

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

The Flask application uses Redis caching to show the number of webpage views. To run the application, `cd` into the `flask-redis` folder and run the following `python` command:

python app.py

The command will start and run the Flask web application with Redis caching:

Flask web application with Redis caching

You can access the web application at `http://127.0.0.1:5000/` . Type the URL in your browser as shown below:

Access web application

Containerize the Redis Flask Application

We will use Docker Compose to containerize the Redis Flask application. With Docker Compose, you create a YAML file to add and configure your application’s containers as services. Our Docker Compose file will have two services: Flask Service and Redis Service. When creating the Docker Compose file, the Flask service will depend on the Redis service. 

The Docker Compose YAML file will also define the container volumes, port mapping, container names, and the Dockerfiles for building the image. Docker Compose will execute the specified Dockerfiles and build the Docker containers. 

A Dockerfile is a text file with no file extension that contains all the commands and instructions that the Docker Engine uses to automatically build a Docker image. 

We will only require one Dockerfile to build the Python Flask application image. Implementing a Redis container for caching does not require a Dockerfile because we will use the official Redis Docker image from Docker Hub. The official image is also known as the base/parent image. We will pull the Redis image from Docker Hub and use it to build a Redis Container without making any changes to the Docker image. We will also create a `requirements.txt` file in the `flask-redis` folder. 

Creating a `requirements.txt` File

This file will contain the dependencies, libraries, and tools for creating our application. Our application requires Flask for building the web application and Redis for caching. In the `flask-redis` folder, create a `requirements.txt` file and add the following content:

flask
redis

We will add an instruction in the Dockerfile to install these two libraries in the Python Flask application Docker image. Let’s create a `Dockerfile` for the Python Flask application.

Dockerfile for the Python Flask application

Docker will read the instructions written in the Dockefile and build a Docker image. Dockerfiles differ depending on the application you are building. In the `flask-redis` folder, create a new `Dockerfile` and add the following Docker content:

#The Flask application container will use python:3.10-alpine as the base image
FROM python:3.10-alpine

#This command will create the working directory for our Python Flask application Docker image
WORKDIR /code

#This command will copy the dependencies and libraries in the requirements.txt to the working directory
COPY requirements.txt /code

#This command will install the dependencies in the requirements.txt to the Docker image
RUN pip install -r requirements.txt --no-cache-dir

#This command will copy the files and source code required to run the application
COPY . /code

#This command will start the Python Flask application Docker container
CMD python app.py

Now that we have created the Dockerfile, we now need to create a `docker-compose.yml` file which will configure the application’s containers as services. It will also add all the configurations required to run the two Docker containers.

Creating a `docker-compose.yml` File

The `docker-compose.yml` will simplify creating and running the Docker containers. Using a single command, you can run `docker-compose.yml` to launch all the containers at once. Docker Compose can work in all stages of application development to deployment. It also has other commands that help in the management of Docker Containers, such as viewing the status of created services and stopping the running services.

In the `flask-redis` folder, create a `docker-compose.yml` file and add the following two services:

1. Redis Service 

To create a `Redis` service, add the following code in the created file:

services:
   redis: 
     image: redislabs/redismod
     container_name: redis
     ports:
       - '6379:6379'

The code above will create a `redis` service. This service will use the `redislabs/redismod` Docker image from Docker Hub to build the Docker Container. The `container_name` is `redis`. The `redis` container will run on port `6379`. 

2. Flask Service

To create a `Flask` service, add the following code in the created file:

flask:
        build: .
        container_name: flask
        ports:
            - "5000:5000"
        volumes:
            - .:/code
        depends_on:
            - redis

The code above will create a `flask` service that depends on the `redis` service to run. This service will use the Docker file in the `flask-redis` folder Docker image to build the Docker Container. The `container_name` is `flask`. The `flask` container will run on port `5000`. The code will also create container volume in the working directory. A container will map the `flask-redis` folder to the container working directory. 

Changing a file in the ‘flask-redis’ folder automatically updates it in the container working directory. This ensures the container is always current.

The final `docker-compose.yml` file will be as shown below:

services:
   redis: 
     image: redislabs/redismod
     container_name: redis
     ports:
       - '6379:6379' 
   flask:
        build: .
        container_name: flask
        ports:
            - "5000:5000"
        volumes:
            - .:/code
        depends_on:
            - redis

After adding the two services to the file, the next step is to use a single command you can run `docker-compose.yml` to launch all the containers at once.

Launch Two Containers at Once with Docker Compose

To launch the two containers at once, use the following `docker-compose` command:

docker-compose up

The command will build and start the two Docker containers as shown below:

You can also access the web application at `http://127.0.0.1:5000/`. Type the URL in your browser as shown below:

From the image above, we can see the Containerized Flask application is running with Redis caching. Refresh the webpage to increase the number of times the webpage has been viewed.

Conclusion

In this tutorial, you have learned how to containerize a Redis Flask application using Docker Compose. We started by building a simple Python Flask application and implemented Redis for caching. Then, we created a Dockerfile that was used to containerize the Python Flask application. We also created a `docker-compose.yml` for adding and configuring the application’s containers as services. Finally, we launched the two containers at once using `docker-compose up` and accessing the application on http://127.0.0.1:5000/.

The application in this tutorial is a simple application used for demonstration purposes. You can use your Flask application to implement the concepts of this tutorial. Hope this tutorial helps you in your DevOps journey, and thanks for reading!

You may also find these two posts interesting: How to Deploy a Flask Application to a Kubernetes Cluster and How to Create a RESTful API Using Flask.


Bravin Wasike holds an undergraduate degree in Software Engineering. He is currently a freelance data scientist and machine learning engineer. He is passionate about machine learning and deploying models to production using Docker and Kubernetes. Bravin also loves writing articles on machine learning and various advances in the technological industry. He spends most of his time doing research and learning new skills in order to solve different problems.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu
Skip to toolbar