搭建 Docker + Flask 后端
使用 Docker + Flask + Gunicorn + Gevent + nginx 来搭建纯 API 后端
目标
使用 Docker 编排管理服务, 使用 Shell 脚本一键化部署流程
第一步
创建目录/文件, 结构如下:
site
|– flask
|– Dockerfile
|– server
|– config
|– gunicorn.conf.py
|– app.py
|– requirements.txt
|– nginx
|– default.conf
|– docker-compose.yml
|– deploy.sh
第二步
flask/Dockerfile
1 2 3 4 5 6 7 8 9 10 11
| FROM python:3.7
COPY ./server /workspace WORKDIR /workspace
RUN pip install -i https://mirrors.aliyun.com/pypi/simple/ --upgrade pip \ && pip --no-cache-dir install -i https://mirrors.aliyun.com/pypi/simple/ -r requirements.txt
EXPOSE 5000
CMD ["gunicorn", "app:app", "-c", "./config/gunicorn.conf.py"]
|
flask/server/requirements.txt
1 2 3
| Flask==1.0.2 gunicorn==19.9.0 gevent==1.4.0
|
flask/server/app.py
1 2 3 4 5 6
| from flask import Flask app = Flask(__name__)
@app.route('/') def hello_world(): return 'Hello, World!'
|
flask/server/config/gunicorn.conf.py
1 2 3 4
| workers = 5 worker_class = "gevent" bind = "0.0.0.0:5000" loglevel = 'debug'
|
nginx/default.conf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| server { listen 80; server_name api.site.com; listen [::]:80; server_tokens off; client_max_body_size 15M;
access_log /var/log/nginx/nginx.api.access.log; error_log /var/log/nginx/nginx.api.error.log;
location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true;
proxy_pass http://flask:5000; proxy_redirect off; } }
|
docker-compose.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| version: "3" services: nginx: image: nginx:alpine volumes: - ./nginx:/etc/nginx/conf.d - /var/log/nginx:/var/log/nginx links: - flask ports: - 80:80 flask: build: context: ./flask
|
deploy.sh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| #!/bin/bash
rm -rf 'tmp.tar' cd '..' tar cf 'tmp.tar' 'site' mv 'tmp.tar' 'site/tmp.tar' cd 'site'
sftp 'root@api.norld.com' <<EOF cd '/root' put 'tmp.tar' exit EOF
rm -rf 'tmp.tar'
ssh 'user@api.site.com' <<EOF rm -rf 'site' tar xf 'tmp.tar' cd 'site' docker-compose down docker-compose up --build -d echo 'y' | docker image prune exit EOF
|
第三步
将部分参数替换成你需要的, 终端执行 deploy.sh, 开始访问 http://api.site.com, Hello, World!