一、参考资料
Docker 构建一个简单的python环境
二、关键步骤
2.1 存在项目
如果已经开发好了项目,可在开发环境中测试Docker。
2.2 不存在项目
如果不存在项目,则创建 Flask 项目。
2.2.1 创建项目目录
$ cd /PATH/TO
$ mkdir flaskweb
2.2.2 创建 app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello World'
if __name__ == '__main__':
# app.run(debug=True)
app.run(host='0.0.0.0', port=5000)
3.1 创建 Dockerfile
文件
# 进入项目目录
cd flaskweb
# 创建Dockerfile文件
# Dockerfile是文本文件,没有后缀名
Dockerfile
# Use an official Python runtime as a parent image
FROM python:3.6.4
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install any needed packages specified in requirements.txt
RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn
# Make port 5000 available to the world outside this container
EXPOSE 5000
# Define environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["python", "app.py"]
3.2 构建镜像
$ docker build --tag=flaskweb:v1.0.1 .
或者
$ docker build -t flaskweb:v1.0.1 .
3.3 启动容器
设置端口都为5000,方便记忆。
## 查看镜像
$ docker images
## 启动容器
$ docker run -it -p 5000:5000 flaskweb:v1.0.1
3.4 测试Flask服务
## 浏览器中打开url
http://127.0.0.1:5000