环境:
Linux、docker、docker-compose、python(Flask)、Mysql
简介:
简单使用Flask框架写的查询Mysql数据接口,使用docker部署,shell脚本启动
优势:
采用docker方式部署更加便于维护,更加简单快捷,简单来说:好用
文件:
Docker运行
flaskweb+mysql
Mysql:
接口样式:
脚本启动:
docker build -t flaskmysql:v2.0.0
进行打包docker-compose up -d
启动flaskMysql.py
from flask import Flask,jsonify
import pymysql
app = Flask(__name__)
@app.route('/')
def hello_world():
conn = pymysql.connect(
host='192.168.2.136', # 主机名
port=13306, # 端口号,MySQL默认为3306
user='root', # 用户名
password='Dl123456', # 密码
database='face', # 数据库名称
)
# 创建游标对象
cursor = conn.cursor()
# 执行 SQL 查询语句
cursor.execute("SELECT * FROM base_customers")
# 获取查询结果
result = cursor.fetchall()
return jsonify(result)
if __name__ == '__main__':
app.config['JSON_AS_ASCII'] = False
app.run(host='0.0.0.0',port='8085', debug=True)
Dockerfile
FROM python:3.9
WORKDIR /app/etc
COPY ./requirements.txt /app/etc
COPY ./flaskMysql.py /app/etc
RUN pip install --no-cache-dir -r /app/etc/requirements.txt
CMD [ "python", "./flaskMysql.py" ]
requirements.txt
Flask==3.0.0
PyMySQL==1.0.2
docker-compose.yml:
version: '3.1'
services:
mysql:
image: mysql:5.7
container_name: mysql
restart: always
network_mode: 'bridge'
ports:
- "13306:3306"
volumes:
- /opt/python_project/mysql/conf:/etc/mysql/conf
- /opt/python_project/mysql/data:/var/lib/mysql
- /opt/python_project/mysql/logs:/logs
environment:
MYSQL_ROOT_PASSWORD: Dl123456
flaskweb:
image: flaskmysql:v2.0.0
container_name: flaskweb
restart: always
network_mode: 'bridge'
ports:
- "8085:8085"
startFlaskweb.sh
#!/bin/bash
flaskcontainerId=`docker ps -a | grep flaskweb | awk '{print $1}'`
flaskcontainerName=`docker ps -a | grep flaskweb | awk '{print $2}'`
mysqlcontainerId=`docker ps -a | grep mysql:5.7 | awk '{print $1}'`
mysqlcontainerName=`docker ps -a | grep mysql:5.7 | awk '{print $2}'`
if [[ $flaskcontainerId || $mysqlcontainerId ]];then
docker stop ${flaskcontainerId}
docker stop ${mysqlcontainerId}
docker rm ${flaskcontainerId}
docker rm ${mysqlcontainerId}
echo "delete ${flaskcontainerName} --SUCCESS"
echo "delete ${mysqlcontainerName} --SUCCESS"
fi
docker-compose up -d
简单搭建了一个flask接口项目,使用docker进行部署,用来练习docker-compose部署与docker打包,docker-compose.yml文件格式很严格,每个:
后面都要跟一个空格
,Dockerfile文件大致是引入程序运行环境,比如python、openjdk等,需要copy那些文件进入容器里面,确定工作路径,需要运行那些命令作为程序启动前的操作,最后CMD运行那个命令来启动项目,你可以写个shell脚本copy进入容器里面用来启动项目。