docker:dockerfile运行flask项目简单demo
希望你对flask,uwsgi/gunicorn,docker有一定的知识基础
1 创建flask应用
目录下/data/www/test/testflask
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'hello docker' if __name__ == '__main__': app.run(host='0.0.0.0',port=5000,debug=True)
python app.py 自己运行一遍确认没问题
2 使用Gunicorn+Gevent运行Flask应用
pip install gunicorn gevent
编写testflask/gunicorn.conf
workers = 5 # 定义同时开启的处理请求的进程数量,根据网站流量适当调整 worker_class = "gevent" # 采用gevent库,支持异步处理请求,提高吞吐量 bind = "0.0.0.0:5000" # 监听IP放宽,以便于Docker之间、Docker和宿主机之间的通信
利用gunicorn 启动flask程序,确保你的程序运行正常:
下面的app:app意思是说脚本名称是app,脚本里面的应用服务也是app
gunicorn -c gunicorn.conf app:app
3 使用Docker运行Flask应用
testflask/requirements.txt 内容有:
flask
gunicorn
gevent
编写testflask/Dockerfile
FROM python:2.7 WORKDIR /usr/src/app COPY requirements.txt ./ COPY gunicorn.conf ./ RUN pip install --no-cache-dir -r requirements.txt CMD ["gunicorn", "app:app", "-c", "gunicorn.conf"]
sudo docker build -t 'testflask'
docker run -it --rm -p 5000:5000 testflask
4 实际情况非常复杂,要使用docker-compose 编排多纯镜像组成一组服务
下面是简单的compose yaml脚本,位于testflask/docker-compose.yaml
web: build: . ports: - 5000:5000 links: - redis - mongo working_dir: /app volumes: - .:/app command: python app.py redis: image: redis:latest mongo: image: mongo
执行脚本 docker-compose up -d 同样的能达到一样的效果