Deploy Flask-MySQL app with docker-compose

#Introduction

How to deploy Flask-MySQL app with docker-compose

From the official docs:

Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration.

The fist, You need to install Docker and docker-compose

The structure folder and file of the app.

[vagrant@localhost ~]$ tree docker-flask-app
docker-flask-app
├── app
│   ├── app.py
│   ├── Dockerfile
│   └── requirements.txt
├── db
│   └── init.sql
└── docker-compose.yml

2 directories, 5 files
[vagrant@localhost ~]$
  • File app.py is the Flask app which connect to database and exposes on REST API endpoint.
  • init.sql an SQL script to initialize the database before run app.

The content of app.py and init.sql as below

[vagrant@localhost docker-flask-app]$ cat app/app.py
from typing import List, Dict
from flask import Flask
import mysql.connector
import json

app = Flask(__name__)


def test_table() -> List[Dict]:
    config = {
        'user': 'root',
        'password': 'root',
        'host': 'db',
        'port': '3306',
        'database': 'devopsroles'
    }
    connection = mysql.connector.connect(**config)
    cursor = connection.cursor()
    cursor.execute('SELECT * FROM test_table')
    results = [{name: color} for (name, color) in cursor]
    cursor.close()
    connection.close()

    return results


@app.route('/')
def index() -> str:
    return json.dumps({'test_table': test_table()})


if __name__ == '__main__':
    app.run(host='0.0.0.0')
[vagrant@localhost docker-flask-app]$ cat db/init.sql
create database devopsroles;
use devopsroles;

CREATE TABLE test_table (
  name VARCHAR(20),
  color VARCHAR(10)
);

INSERT INTO test_table
  (name, color)
VALUES
  ('dev', 'blue'),
  ('pro', 'yellow');

Create a Docker image for Flask app

Create a Dockerfile file in the app folder.

[vagrant@localhost docker-flask-app]$ cat app/Dockerfile
# Use an official Python runtime as an image
FROM python:3.6

# The EXPOSE instruction indicates the ports on which a container
EXPOSE 5000

# Sets the working directory for following COPY and CMD instructions
# Notice we haven’t created a directory by this name - this instruction
# creates a directory with this name if it doesn’t exist
WORKDIR /app

COPY requirements.txt /app
RUN python -m pip install --upgrade pip
RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host=files.pythonhosted.org --no-cache-dir -r requirements.txt

# Run app.py when the container launches
COPY app.py /app
CMD python app.py

You need dependencies Flask and mysql-connector in File requirements.txt

[vagrant@localhost docker-flask-app]$ cat app/requirements.txt
flask
mysql-connector

Create a docker-compose.yml

[vagrant@localhost docker-flask-app]$ cat docker-compose.yml
version: "2"
services:
  app:
    build: ./app
    links:
      - db
    ports:
      - "5000:5000"
  db:
    image: mysql:5.7
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - ./db:/docker-entrypoint-initdb.d/:ro

Running the Flask app

[vagrant@localhost docker-flask-app]$ docker-compose up -d

The result, after running the Flask app

Conclusion

You have Deploy Flask-MySQL app with docker-compose. I hope will this your helpful. Thank you for reading the DevopsRoles page!

,

About HuuPV

My name is Huu. I love technology and especially Devops Skill such as Docker, vagrant, git so forth. I likes open-sources. so I created DevopsRoles.com site to share the knowledge that I have learned. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

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

Comment moderation is enabled. Your comment may take some time to appear.

This site uses Akismet to reduce spam. Learn how your comment data is processed.