docker和docker-compose部署flask(flask-script)、gunicorn实践记录
这里不介绍docker和docker-compose的工作原理,只真实的记录本次实践。
循序渐进的来,先用gunicorn启动,再用Dockerfile启动,最后尝试docker-compose编排
1.准备项目目录和模拟代码,先本地用gunicorn启动
- ~/flask-demo 目录,创建好虚拟环境,flask启动文件,我这里用了flask-script的方式
from flask import Flask
from flask-script import Manager
app = Flask(__name__)
manager = Manager(app)
@app.route("/")
def index():
return "hello world"
if __name__ == "__main__":
manager.run()
- gunicorn配置文件,这里其他很多教学是文件名以conf结尾,我这里这样写会报错,建议写成一个py文件的形式
worker = 4
thread = 2
bind = "0.0.0.0:8897"
worker_class = "gevent"
worker_connection = 2000
pidfile = "gunicorn.pid"
accesslog = "logs/access.log"
errorlog = "logs/error.log"
loglevel = "info"
reload = True
debug = True
- gunicorn 启动命令
gunicorn -c ./gun_cfg.py manage:app
2. 用Dockerfile启动项目
-
编写Dockerfile文件
FROM python:3.7
MAINTAINER username<email>
COPY requirements.txt ./
RUN pip3 install --no-cache-dir -i https://pypi.douban.com/simple -r requirements.txt
COPY . .
CMD gunicorn -c ./gun_cfg.py manage:app
-
生成镜像
docker build -t flask-test .
-
用flask-test镜像启动容器
docker run -itd --name:test -p 8000:8897 flask-test
尝试使用docker-compose编排启动项目,真正实现一键启动
-
结构目录有所改变,为了更好的适应实际的项目开发的情况 |—— flask-demo
| |—— docker
| |—— app
| |—— Dockerfile
| |—— requirements.txt
| |—— nginx
| |—— Dockerfile
| |—— nginx.conf
| |—— mysql
| |—— Dockerfile
| |—— init.sql
| |—— docker-compose.yml
| |—— src
| |—— app
| |—— handler
| |—— model
| |—— ...
| |—— config.py
| |—— manage.py
| |—— gun_cfg.py
-
下面来一步步介绍
version: "3"
services:
app:
build: ./app
stdin_open: true
tty: true
ports:
- "8897:8897"
container_name: "flask-demo"
volumes:
- ../: /home/root/flask-demo: rw
working_dir: /home/root/flask-demo/src/app
depends_on:
- mysql
command: gunicorn -c ./gun_cfg.py manage:app
mysql:
build: ./mysql
ports:
- "3306:3306"
volumes:
- ./data/mysql:/var/lib/mysql:rw
environment:
MYSQL_ROOT_PASSWORD: "test123"
TZ: Asia/Shanghai
restart: always
nginx:
build: ./nginx
ports:
- "80:80"
container_name: "flask-nginx"
volumes:
- ./docker/nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ../:/home/root/flask-demo:rw
depends_on:
- app
FROM python:3.7
COPY requirements.txt ./
RUN pip3 install --no-cache-dir -i https://pypi.douban.com/simple/ -r requirements.txt
FROM nginx:1.9.9
COPY ./nginx.conf /etc/nginx/nginx.conf
FROM mysql:5.6
COPY ./init.sql /docker-entrypoint-initdb.d
-
启动 docker-compose up -d
|