1、创建app.py文件
主文件,提供对外服务接口
import io
import random
from flask import Flask, Response, request
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
app = Flask(__name__)
@app.route("/")
def index():
""" 返回带有图片的html界面,使用form -> action 及 image -> src等参数实现动态刷新功能
"""
num_x_points = int(request.args.get("num_x_points", 50)) # 设置默认值 50
# html 模板
return f"""
<h1>Flask and matplotlib</h1>
<h2>Random data with num_x_points={num_x_points}</h2>
<form method=get action="/">
<input name="num_x_points" type=number value="{num_x_points}" />
<input type=submit value="update graph">
</form>
<h3>Plot as a png</h3>
<img src="/matplot-as-image-{num_x_points}.png"
alt="random points as png"
height="300"
width="600"
>
"""
@app.route("/matplot-as-image-<int:num_x_points>.png")
def plot_png(num_x_points=50):
""" renders the plot on the fly.
"""
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
x_points = range(num_x_points)
axis.plot(x_points, [random.randint(1, 30) for x in x_points])
output = io.BytesIO()
FigureCanvasAgg(fig).print_png(output)
return Response(output.getvalue(), mimetype="image/png")
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000, debug=True)
2、创建Dockerfile文件
# Docker image for flask and matplotlib python run
# VERSION 1.0
# Author: Taro
# 基础镜像使用python:3.6
FROM python:3.6
# 将服务器 requirements.txt 文件复制到 容器 /demo/目录下
COPY requirements.txt /demo/
COPY app.py /demo/
# 指定容器工作目录为 /demo/
WORKDIR /demo/
# 安装 项目依赖
RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
# 运行
ENTRYPOINT ["python","app.py"]
3、创建requirements.txt文件
click==8.0.4
colorama==0.4.5
cycler==0.11.0
dataclasses==0.8
Flask==2.0.3
importlib-metadata==4.8.3
itsdangerous==2.0.1
Jinja2==3.0.3
kiwisolver==1.3.1
MarkupSafe==2.0.1
matplotlib==3.3.4
numpy==1.19.5
Pillow==8.4.0
pyparsing==3.0.7
python-dateutil==2.8.2
six==1.16.0
typing-extensions==4.1.1
Werkzeug==2.0.3
zipp==3.6.0
4、文件目录结构
5、构建镜像
docker build -t docker_flask:v1 .
6、通过镜像启动服务
docker run -d -p 8080:5000 docker_flask:v1
注意: 如果是拥有公网的云上机器对外提供服务,需要开通网络安全组端口对外提供服务。