Create & Dockerize a Flask app with Redis
Section 1 : We would create the Flask app
Section 2 : We would deploy the app as service, along with redis using docker and docker-compose.
Section 1
Creating a flask app that returns the count number of times the page was visited.
Create a requirements.txt file, and paste the following dependency name
Flask
redis
Import dependencies using
pip install --no-cache-dir -r requirements.txt
Create a app.py file
from flask import Flask
from redis import Redis
app = Flask(__name__)
redis = Redis(host='db_service', port=6379)
@app.route('/')
def hello():
visit_count = redis.incr('visit_count')
return f"Hello, this page has been visited {visit_count} times."
if __name__ == '__main__':
app.run(host='0.0.0.0')
We can test the app locally for this we need to:
Install virtualenv if it's not already installed:
sudo apt-get update
sudo apt-get install python3-venv
Create a new virtual environment:
python3 -m venv myenv
Activate the virtual environment:
source myenv/bin/activate
Install Flask and Redis within the virtual environment:
pip install Flask redis
Run the Flask application within the virtual environment:
python3 app.py
Section 2
For Section 2, Let's visit one previous project Build Flask Image using docker & docker-compose
You can also follow the github project DockerizeFlaskVisitCounter
---THANK YOU---
Comments
Post a Comment