MySQL Access
Deployment Mode
# 1. Create a Docker network
docker network create asgard
# 2. Create the MySQL container
docker volume create sandbox-home # ensure volume is empty
docker run -d -v sandbox-home:/var/lib/mysql --name mysqlserver --network asgard -e MYSQL_ROOT_PASSWORD=root -p 52000:3306 mysql:8.0.12
# 3. Create the phpMyAdmin container
docker run -d --network asgard -e PMA_HOST=mysqlserver -p 8080:80 phpmyadmin/phpmyadmin
# 4. Create the app container
docker run --network asgard -e MYSQL_HOST=mysqlserver -p 8081:8080 mysql_access
http://localhost:8080/ # access phpmyadmin, root, root
http://localhost:8081/ # access app
App Code
# app.py
import os
import mysql.connector
import pandas as pd
import datetime
import dash
import dash_html_components as html
app = dash.Dash(__name__)
def get_ip():
return os.getenv('MYSQL_HOST', 'localhost')
def get_data():
# connect to database
cnx = mysql.connector.connect(user='root', password='root', host=get_ip(), port=3306, database='University')
# create a cursor
cursor = cnx.cursor(buffered=True)
# create query
query = (
"SELECT * \
from Department")
# execute query
cursor.execute(query)
# fetch result
result = cursor.fetchall() # list of tuple
# convert result to pandas DataFrame
df = pd.DataFrame.from_records(result)
# close connection
cnx.close()
return df
def getLayout():
df = get_data()
return html.Div(df.to_string())
app.layout = getLayout()
if __name__ == "__main__":
app.run_server(host='0.0.0.0', port=8080)
# Dockerfile
FROM python:3.8
WORKDIR /usr/src/app
COPY . .
RUN pip install pandas
RUN pip install dash
RUN pip install mysql-connector-python
EXPOSE 8080
CMD ["python", "./app.py"]
docker build -t mysql_access .