Containerizing Python Web Applications: A Flask and MySQL Example
Table of contents
In this tutorial, we'll explore the process of containerizing a Python web application using Docker. Specifically, we'll be working with Flask, a popular web framework, and MySQL as the database. Docker provides a convenient and consistent environment for deploying applications, making it an ideal choice for developers looking to simplify deployment workflows.
What You'll Learn:
Setting up a Docker image based on Ubuntu 20.04
Installing Python 3 and pip within the Docker image
Configuring a Flask application with Flask-MySQL
Organizing your project structure for containerization
Defining the entry point and running your Flask app within a Docker container
mkdir my-simple-app
cd my-simple-app
import os
from flask import Flask
app = Flask(__name__)
@app.route("/")
def main():
return "Welcome!"
@app.route('/how are you')
def hello():
return 'I am good, how about you?'
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8080)
FROM ubuntu:20.04
RUN apt-get update && \
apt-get install -y python3 &&
apt-get install -y python3-pip
RUN pip install flask flask-mysql
COPY app.py /opt/app.py
WORKDIR /opt
ENTRYPOINT ["flask", "run", "--host=0.0.0.0", "--port=8080"]
Now build the Dockerfile and run the image. Boom
docker build . -t my-simple-app
docker run --name python_service my-simple-app