使用Python + Flask + Docker来运行Web应用程序
摘要
在EC2实例上安装并运行docker和docker-compose的方法备忘录
操作系统:amazonLinux2
文档
https://flask.palletsprojects.com/en/2.0.x/tutorial/
https://flask.palletsprojects.com/en/2.0.x/installation/
https://flask.palletsprojects.com/en/2.0.x/quickstart/
以下是网址链接:
https://flask.palletsprojects.com/en/2.0.x/tutorial/
https://flask.palletsprojects.com/en/2.0.x/installation/
https://flask.palletsprojects.com/en/2.0.x/quickstart/
安装Docker
安装 -> 启动 -> 调整权限以使ec2-user可以运行
$ sudo su -
# yum update -y
# amazon-linux-extras install -y docker
# systemctl enable docker
# systemctl start docker
# usermod -aG docker ec2-user
安装docker-compose
如果能够显示版本信息就可以了,需要根据需要调整docker-compose的版本。
# curl -L https://github.com/docker/compose/releases/download/1.24.1/docker-compose-Linux-x86_64 -o /usr/local/bin/docker-compose
# chmod 755 /usr/local/bin/docker-compose
# docker-compose -v
docker-compose version 1.24.1, build 4667896b
创建一个 Python 容器并进行访问确认。
请使用ec2-user进行操作。
$ mkdir project
$ cd project/
$ mkdir -p docker/python
$ vi docker/python/Dockerfile
$ vi docker-compose.yml
$ vi docker/python/app.py
$ vi docker/python/templates/index.html
$ docker-compose up -d
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=5000)
version: "3"
services:
python:
build: ./docker/python
ports:
- 80:5000
FROM python:3.9
WORKDIR /app
ADD . /app
RUN pip install Flask
EXPOSE 5000
CMD ["python", "app.py"]
<html>
<title>hogehoge</title>
<head>
</head>
<body>
hogehoge
</body>
</html>
达到目标
只要通过公共IP的80端口访问,出现显示”hogehoge”的页面就可以。
补充
在我的本地环境下运行这篇文章中提到的内容。
from flask import Flask, render_template
import numpy as np
from matplotlib.figure import Figure
import base64
from io import BytesIO
app = Flask(__name__)
@app.route('/')
def index():
np.random.seed(1)
x = np.arange(10)
y = np.random.randint(1, 1000, 10)
fig = Figure()
ax = fig.subplots()
ax.plot(x, y)
buf = BytesIO()
fig.savefig(buf, format="png")
data = base64.b64encode(buf.getbuffer()).decode("ascii")
return render_template('index.html', data=data)
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=5000)
FROM python:3.9
WORKDIR /app
ADD . /app
RUN pip install Flask\
& pip install numpy\
& pip install matplotlib
EXPOSE 5000
CMD ["python", "app.py"]
<html>
<title>hogehoge</title>
<head>
</head>
<body>
<img src="data:image/png;base64,{{data}}"/>
</body>
</html>