这里不介绍docker和docker-compose的工作原理,只真实的记录本次实践。
循序渐进的来,先用gunicorn启动,再用Dockerfile启动,最后尝试docker-compose编排
# ~/flask-demo/manage.py
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()
# ~/flask-demo/gun_cfg.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 -c ./gun_cfg.py manage:app
编写Dockerfile文件
# 指定基础环境
FROM python:3.7
# 指定个人信息 可有可无
MAINTAINER username<email>
# 安装项目依赖
COPY requirements.txt ./ # 拷贝当前目录下的req文件到容器的当前目录下
RUN pip3 install --no-cache-dir -i https://pypi.douban.com/simple -r requirements.txt
# 拷贝项目代码到容器的当前路径下
COPY . .
# 运行项目
CMD gunicorn -c ./gun_cfg.py manage:app
生成镜像
# -t 指定镜像名称 . 指在当前目录寻找可执行的Dockerfile文件
docker build -t flask-test .
用flask-test镜像启动容器
# -itd 交互和守护模式启动 --name 指定容器名
docker run -itd --name:test -p 8000:8897 flask-test
结构目录有所改变,为了更好的适应实际的项目开发的情况
|—— 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
下面来一步步介绍
# flask-demo/docker/docker-compose.yml
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
# flask-demo/docker/app/Dockerfile
FROM python:3.7
COPY requirements.txt ./
RUN pip3 install --no-cache-dir -i https://pypi.douban.com/simple/ -r requirements.txt
# flask-demo/docker/nginx/Dockerfile
FROM nginx:1.9.9
COPY ./nginx.conf /etc/nginx/nginx.conf
# flask-demo/docker/mysql/Dockerfile
FROM mysql:5.6
COPY ./init.sql /docker-entrypoint-initdb.d
启动
docker-compose up -d