最近喜欢上了flask框架,到部署这一步的时候踩了许多坑,网上的教程也不能完全满足我的需要,比如有nginx和uwsgi分开部署的,但是我想放在一个docker里面;有用debian的镜像构建的,但是体积比较大我想用alpine的镜像来。折腾了一下午,搞定!这里以helloworld为例对部署过程做个整理备忘。

准备

yum install docker

yum install docker-compose

编写代码

目录结构:

app
|-- docker-compose.yml
|-- Dockerfile
|-- flask
|   |-- run.py
|   |-- start.sh
|   `-- uwsgi.ini
|-- nginx
|   `-- nginx.conf
`-- requirements.txt

docker-compose.yml

version: '3'
services:
  fndock:
    build: .
    container_name: myfndock
    restart: always
    ports:
      - "80:80"

Dockerfile

FROM alpine:3.8
RUN echo "https://mirror.tuna.tsinghua.edu.cn/alpine/v3.8/main/" > /etc/apk/repositories \
&& apk update \
&& apk add --no-cache nginx python3 python3-dev gcc libc-dev linux-headers
WORKDIR /app
COPY requirements.txt /app
RUN pip3 install --upgrade pip -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com && pip3 install -r requirements.txt -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
COPY flask /app
RUN rm /etc/nginx/conf.d/default.conf && mkdir /run/nginx
COPY nginx/nginx.conf /etc/nginx/conf.d
CMD ["sh", "/app/start.sh"]

requirements.txt

flask
uwsgi

flask/run.py

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
    return 'Hello, World!'
if __name__ == "__main__":
    app.run()

flask/uwsgi.ini

[uwsgi]
socket = 127.0.0.1:5001
wsgi-file = run.py
callable = app
processes = 4
threads = 2

flask/start.sh

nginx
uwsgi uwsgi.ini

nginx/nginx.conf

server {
   listen 80;
   charset UTF-8;
   client_max_body_size 30M;
   location / {
       include uwsgi_params;
       uwsgi_pass 127.0.0.1:5001;
   }
}

开始部署

登入 https://cr.console.aliyun.com/cn-hangzhou/instances/mirrors 页面复制加速器地址,放到/etc/docker/daemon.json的{ }中,效果如下:

daemon.json

{
  "registry-mirrors": ["https://xxxxxxxx.mirror.aliyuncs.com"]
}

systemctl daemon-reload

systemctl start docker

cd /app

docker-compose build

docker-compose up -d

完成

访问服务器的80端口,看到helloworld说明部署成功。

文章目录