美文网首页
docker+nginx+gunicorn+flask部署

docker+nginx+gunicorn+flask部署

作者: 向日葵1884 | 来源:发表于2019-12-31 17:45 被阅读0次

    项目结构:

    image.png

    1. 新建gunicorn_config文件

    • gunicorn_config.py
    # 并行工作进程数
    workers = 2
    # 指定每个工作者的线程数
    threads = 4
    # 监听内网端口
    bind = '0.0.0.0:5000'
    # 工作模式协程
    worker_class = 'gevent'
    # 设置最大并发量
    worker_connections = 2000
    
    import os
    if not os.path.exists('./log/'):
        os.mkdir('./log/')
    # 设置进程文件目录
    pidfile = './log/gunicorn.pid'
    # 设置访问日志和错误信息日志路径
    accesslog = './log/gunicorn_acess.log'
    errorlog  = './log/gunicorn_error.log'
    # 设置日志记录水平
    loglevel = 'info'
    # 代码发生变化是否自动重启
    reload=True
    

    2. 新建Dockerfile文件

    • Dockerfile:
    FROM python:3.7-alpine
    MAINTAINER "Silly<Silly@Silly.com>"
    WORKDIR /home/project
    
    RUN echo http://mirrors.aliyun.com/alpine/v3.9/main > /etc/apk/repositories
    RUN echo http://mirrors.aliyun.com/alpine/v3.9/community >> /etc/apk/repositorie
    
    RUN apk update
    RUN apk --update add --no-cache gcc
    RUN apk --update add --no-cache g++
    RUN apk --update add --no-cache libffi-dev openssl-dev
    
    COPY requirements.txt requirements.txt
    RUN pip install --no-cache-dir -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
    
    CMD gunicorn -c gunicorn_config.py main:app
    

    3. 构建镜像->新增容器->启动 有两种方式:

    构建docker镜像:

    docker build . -t xiao_demo1:latest
    

    创建并启动容器:

    docker run --name xiao_demo1 -p hostPort:containerPort -v /home/xiao_demo:/home/project -itd xiao_demo:latest sh
    

    用docker-compose构建镜像,创建并启动容器:

    • docker-compose.yaml
    version: "3.0"
    services:
        xiao:
            image: xiao_demo:latest
            build: .
            container_name: xiao_demo1
            restart: always
            volumes:
              - ./:/home/project
            ports:
                - "5000:5000"
    #    networks:
    #      xiao_net:
    #        aliases:
    #          - xiao-pc
    #networks:
    #    xiao_net:
    #        name: xiao_net
    

    命令行执行

    docker-compose up -d
    

    创建并启动ngxin容器

    docker run --name nginx -v `pwd`/logs:/var/log/nginx -v `pwd`/conf.d:/etc/nginx/conf.d -v `pwd`/html:/usr/share/nginx/html --net host -p 80:80 -itd --restart=always nginx /bin/bash
    

    在conf.d目录下新建default.conf (nginx配置文件)

    server {
        listen 80;
        server_name xx.xxx.xxx.xxx; # 这是HOST机器的外部域名,用地址也行
     
        location / {
            proxy_pass http://127.0.0.1:5000; # 这里是指向 gunicorn host 的服务地址
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
    
    

    参考资料:
    https://blog.csdn.net/qq_42677001/article/details/102978727
    https://blog.csdn.net/gycyxh/article/details/88564751

    相关文章

      网友评论

          本文标题:docker+nginx+gunicorn+flask部署

          本文链接:https://www.haomeiwen.com/subject/kafioctx.html