Ajeet Raina Docker Captain, ARM Innovator & Docker Bangalore Community Leader.

Dockerize an API based Flask App and Redis using Docker Desktop

2 min read

If you’re a developer looking out for a lightweight but robust framework that can help you in web development with fewer lines of code, then Flask is the right tool for you. Flask is a simple, light-weight framework popularly categorized as a micro framework.  Simple applications can be built with ease and do not require too much coding.  Flask apps requires much fewer lines of code for a simple task.

Flask comes with some standard functionalities and allows developers to add any number of libraries or plugins for an extension. If you have a simple, innovative use case to be added to an existing application, Flask should be your choice as it offers flexibility. Flask comes with a small set of easy to learn API, and the documentation is excellent. If you are new to Python, start your web development with Flask, so that you can get the feel of backend and frontend both as well as learn the core concepts well.

Compelling Features of Flask

  • Comes with a built-in development server and fast debugger
  • Easy and flexible configurations
  • Coherent and neat API
  • RESTful and HTTP request handling
  • Integrated Unit testing support

In this tutorial, we will see how to containerize API based Flask app with Redis and deploy it over Docker Desktop.

Prerequisite:

  • Install Docker Desktop

Visit https://www.docker.com/get-started/ to download Docker Desktop for Mac and install it in your system.

getting started with docker

Once the installation gets completed, click “About Docker Desktop” to verify the version of Docker running on your system.

about docker desktop pull down menu

If you follow the above steps, you will always find the latest version of Docker desktop installed on your system.

Docker Desktop Version 4.7 welcome

 

Create a project directory

We will be creating the following project files:

 

 

.
├── Dockerfile
├── README.md
├── app.py
├── docker-compose.yml
└── requirements.txt

Create a new directory called flask-redis.

mkdir flask-redis

Create app.py

Let’s add some code to handle simple web requests. Open this working directory in your favorite IDE and enter the following code into the app.py file.

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 "This webpage has been viewed "+counter+" time(s)"
if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)

 

Create requirements.txt

In Python, the requirement.txt file is a type of file that usually stores information about all the libraries, modules, and packages in itself that are used while developing a particular project. It also stores all files and packages on which that project is dependent or requires to run. 

flask
redis

Create a Dockerfile

In order to dockerize the flask app, we will require to create an empty file called “Dockerfile” and add the following content:

FROM python:3.11.0a6-alpine3.15
WORKDIR /code
COPY requirements.txt /code
RUN pip install -r requirements.txt --no-cache-dir
COPY . /code
CMD python app.py

Create a Docker Compose file

services:
   redis: 
     image: redislabs/redismod
     ports:
       - '6379:6379' 
   redisinsight:
image: redislabs/redisinsight:latest
ports:
- '8001:8001'
web:
        build: .
        ports:
            - "5000:5000"
        volumes:
            - .:/code
        depends_on:
            - redis

Deploy with docker-compose

$ docker-compose up -d
[+] Running 24/24
 ⠿ redis Pulled   
 ...                                                                                                                                                                                                                                                                                                                                                                                                             
   ⠿ 565225d89260 Pull complete                                                                                                                                                                                                      
[+] Building 12.7s (10/10) FINISHED
 => [internal] load build definition from Dockerfile                                                                                                                                                                                  ...
[+] Running 3/3
 ⠿ Network flask-redis_default    Created                                                                                                                                                                                             
 ⠿ Container flask-redis-redis-1  Started                                                                                                                                                                                             
 ⠿ Container flask-redis-web-1    Started

Expected result

Listing containers must show one container running and the port mapping as below:

$ docker-compose ps
NAME                  COMMAND                  SERVICE             STATUS              PORTS
flask-redis-redis-1   "redis-server --load…"   redis               running             0.0.0.0:6379->6379/tcp
flask-redis-web-1     "/bin/sh -c 'python …"   web                 running             0.0.0.0:5000->5000/tcp

After the application starts, navigate to http://localhost:5000 in your web browser or run:

$ curl localhost:5000
This webpage has been viewed 2 time(s)

Monitoring Redis keys

Connect to the Redis database by using redis-cli command and monitor the keys.

redis-cli -p 6379 
127.0.0.1:6379> monitor 
OK 
1646634062.732496 [0 172.21.0.3:33106] "INCRBY" "hits" "1" 
1646634062.735669 [0 172.21.0.3:33106] "GET" "hits"

Visualizing the Redis Keys using RedisInsight

RedisInsight is a visual tool that lets you do both GUI- and CLI-based interactions with your Redis database, and so much more when developing your Redis based application. It is a fully-featured pure Desktop GUI client that provides capabilities to design, develop and optimize your Redis application. It works with any cloud provider as long as you run it on a host with network access to your cloud-based Redis server. It makes it easy to discover cloud databases and configure connection details with a single click. It allows you to automatically add Redis Enterprise Software and Redis Enterprise Cloud databases.

Running Redis GUI using Docker

 

docker run -d -v redisinsight:/db -p 8001:8001 redislabs/redisinsight:latest


Open http://localhost:8001 to access RedisInsight.  Supply “localhost” as a database URL, 6379 as port number and database name of your choice.

Stop and remove the containers

docker-compose down

References:

  1. Docker Awesome Compose
  2. Build Your Python Image
  3. How to build and run a Python app in a container

 

Have Queries? Join https://launchpass.com/collabnix

Ajeet Raina Docker Captain, ARM Innovator & Docker Bangalore Community Leader.

57 Replies to “Dockerize an API based Flask App and Redis using…”

  1. Hi, Neat post. There’s an issue along with your web site in internet explorer, may check this?K IE still is the market chief and a good component to people will omit your fantastic writing because of this problem.

  2. Wonderful web site. A lot of useful information here. I am sending it to a few friends ans also sharing in delicious. And certainly, thanks for your sweat!

  3. Great V I should definitely pronounce, impressed with your website. I had no trouble navigating through all the tabs and related information ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, website theme . a tones way for your customer to communicate. Nice task..

  4. Can I just say what a aid to seek out somebody who really is aware of what theyre speaking about on the internet. You definitely know learn how to deliver an issue to light and make it important. More folks have to learn this and understand this side of the story. I cant imagine youre not more popular since you positively have the gift.

  5. Hmm is anyone else encountering problems with the images on this blog loading? I’m trying to figure out if its a problem on my end or if it’s the blog. Any feedback would be greatly appreciated.

  6. This is the right blog for anyone who wants to find out about this topic. You realize so much its almost hard to argue with you (not that I actually would want…HaHa). You definitely put a new spin on a topic thats been written about for years. Great stuff, just great!

  7. Pretty component of content. I just stumbled upon your web site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I will be subscribing on your feeds and even I achievement you get admission to constantly fast.

  8. My developer is trying to convince me to move to .net from PHP. I have always disliked the idea because of the expenses. But he’s tryiong none the less. I’ve been using Movable-type on a variety of websites for about a year and am concerned about switching to another platform. I have heard great things about blogengine.net. Is there a way I can transfer all my wordpress posts into it? Any kind of help would be really appreciated!

  9. certainly like your web-site but you need to check the spelling on quite a few of your posts. A number of them are rife with spelling issues and I find it very bothersome to tell the truth nevertheless I’ll definitely come back again.

  10. Fantastic blog! Do you have any suggestions for aspiring writers? I’m planning to start my own site soon but I’m a little lost on everything. Would you suggest starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely confused .. Any recommendations? Thank you!

  11. But a smiling visitor here to share the love (:, btw great layout. “Everything should be made as simple as possible, but not one bit simpler.” by Albert Einstein.

  12. Hey there, You have done a fantastic job. I’ll definitely digg it and for my part recommend to my friends. I’m confident they will be benefited from this site.

  13. certainly like your web-site however you have to test the spelling on several of your posts. Many of them are rife with spelling problems and I find it very bothersome to inform the truth then again I will surely come again again.

  14. I just couldn’t leave your site prior to suggesting that I really loved the usual information an individual provide to your guests? Is gonna be again often to check up on new posts.

  15. I wanted to write down a small remark so as to appreciate you for all the awesome tactics you are giving out at this site. My prolonged internet look up has at the end of the day been paid with good quality details to share with my partners. I would believe that most of us site visitors are extremely fortunate to dwell in a good site with so many special individuals with good solutions. I feel rather blessed to have seen your webpage and look forward to plenty of more amazing times reading here. Thanks a lot again for all the details.

  16. Thanx for the effort, keep up the good work Great work, I am going to start a small Blog Engine course work using your site I hope you enjoy blogging with the popular BlogEngine.net.Thethoughts you express are really awesome. Hope you will right some more posts.

  17. Hey! I know this is kind of off topic but I was wondering which blog platform are you using for this website? I’m getting tired of WordPress because I’ve had problems with hackers and I’m looking at options for another platform. I would be fantastic if you could point me in the direction of a good platform.

  18. hey there and thank you for your information – I’ve certainly picked up anything new from right here. I did however expertise some technical points using this site, as I experienced to reload the web site a lot of times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I am complaining, but sluggish loading instances times will sometimes affect your placement in google and could damage your quality score if advertising and marketing with Adwords. Well I am adding this RSS to my e-mail and could look out for a lot more of your respective exciting content. Ensure that you update this again soon..

  19. I do not even understand how I finished up here, but I thought this submit was great. I do not know who you’re however certainly you are going to a famous blogger in the event you are not already 😉 Cheers!

  20. Hi , I do believe this is an excellent blog. I stumbled upon it on Yahoo , i will come back once again. Money and freedom is the best way to change, may you be rich and help other people.

  21. Its like you read my mind! You seem to grasp a lot about this, such as you wrote the e book in it or something. I think that you simply could do with a few p.c. to drive the message house a bit, however instead of that, that is wonderful blog. A great read. I will definitely be back.

  22. I like what you guys are up too. Such clever work and reporting! Carry on the excellent works guys I have incorporated you guys to my blogroll. I think it’ll improve the value of my web site 🙂

  23. Thank you for some other magnificent post. Where else could anybody get that type of info in such an ideal means of writing? I’ve a presentation next week, and I’m on the search for such information.

  24. Hello! I’ve been following your website for some time now and finally got the courage to go ahead and give you a shout out from Porter Tx! Just wanted to tell you keep up the excellent job!

  25. I’ve been browsing on-line more than three hours these days, yet I by no means discovered any fascinating article like yours. It is lovely worth enough for me. In my opinion, if all webmasters and bloggers made just right content material as you probably did, the internet will probably be much more helpful than ever before. “When there is a lack of honor in government, the morals of the whole people are poisoned.” by Herbert Clark Hoover.

  26. Nice post. I used to be checking continuously this blog and I am inspired! Extremely useful info specifically the remaining section 🙂 I take care of such information a lot. I was seeking this particular info for a long time. Thanks and good luck.

  27. An impressive share, I simply given this onto a colleague who was doing a little bit evaluation on this. And he in truth purchased me breakfast because I discovered it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to discuss this, I feel strongly about it and love studying extra on this topic. If doable, as you develop into experience, would you mind updating your blog with more particulars? It is highly useful for me. Massive thumb up for this blog put up!

  28. Thanks for your article. I would love to comment that the first thing you will need to carry out is check if you really need credit repair. To do that you must get your hands on a replica of your credit rating. That should really not be difficult, since government makes it necessary that you are allowed to obtain one cost-free copy of your real credit report on a yearly basis. You just have to request the right people. You can either check out the website for your Federal Trade Commission or perhaps contact one of the major credit agencies straight.

  29. Definitely believe that which you said. Your favorite justification seemed to be on the net the simplest thing to be aware of. I say to you, I certainly get irked while people think about worries that they just don’t know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side-effects , people could take a signal. Will probably be back to get more. Thanks

  30. Really excellent info can be found on website. “I know of no great men except those who have rendered great service to the human race.” by Francois Marie Arouet Voltaire.

  31. Attractive element of content. I simply stumbled upon your website and in accession capital to claim that I get in fact loved account your weblog posts. Any way I’ll be subscribing on your augment or even I fulfillment you get admission to constantly rapidly.

  32. Simply wish to say your article is as astounding. The clarity to your submit is just spectacular and i can suppose you’re an expert in this subject. Fine together with your permission allow me to take hold of your feed to keep updated with imminent post. Thanks 1,000,000 and please carry on the enjoyable work.

  33. Bilgiler. 541 kez izlendi. Kategori Klasik Sex Filmleri,
    Romantik Erotik, Sansürsüz Erotik Filmler. Sabah koşusuna çıkan Rany her gün kendi vücudunu mükemmel tutmak için spor yapar.
    Yaptığı sporun etkisiyle güne daha dinamik başladığını düşünür.
    Günün birinde sürekli onunla beraber koşan bir adam dikkatini
    çeker.

Leave a Reply

Your email address will not be published.

© Copyright Collabnix Inc

Built for Collabnix Community, by Community