工作中写的python脚本,想在alpine环境中搭建nginx+uwsgi+flask服务,在此记录过程以及遇到的坑 #### 目录结构 ``` ./ ├── app │ ├── app.py │ ├── requirements.txt │ └── uwsgi.ini ├── Dockerfile ├── nginx.conf └── README ``` - **Dockerfile** ``` FROM alpine:3.10 ENV LANG C.UTF-8 ENV TIMEZONE Asia/Shanghai RUN echo -e "http://mirrors.aliyun.com/alpine/v3.10/main/\nhttp://mirrors.aliyun.com/alpine/v3.10/community" > /etc/apk/repositories \ && apk add -U tzdata && ln -snf /usr/share/zoneinfo/${TIMEZONE} /etc/localtime && echo "${TIMEZONE}" > /etc/timezone \ && apk add --update --upgrade \ && apk add --no-cache nginx python3 uwsgi uwsgi-python3 \ # && pip3 install --no-cache-dir --upgrade pip \ && ln -s /usr/bin/python3 /usr/bin/python \ && mkdir -p /{app,log} WORKDIR /app COPY ./app/ /app/ ADD ./nginx.conf /etc/nginx/nginx.conf RUN pip3 install --no-cache-dir -r /app/requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ EXPOSE 3001 ENTRYPOINT nginx -g "daemon on;" && uwsgi --ini /app/uwsgi.ini ``` - **nginx.conf** ``` #user nobody; worker_processes auto; error_log /log/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /log/access.log main; #access_log "pipe:rollback logs/access_log interval=1d baknum=7 maxsize=2G" main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; server { listen 3001; server_name _; charset utf-8; location / { include uwsgi_params; uwsgi_pass unix:///app/uwsgi.sock; uwsgi_send_timeout 300; uwsgi_connect_timeout 300; uwsgi_read_timeout 300; } } } ``` - **app.py** ``` # 此处仅保留测试代码,其他代码已经删除 # -*- coding: utf-8 -*- # __author__ = 'Erica' from flask import Flask, request app = Flask(__name__) @app.route('/hello', methods=['GET']) def hello(): return 'hello, this is a test page' if __name__ == '__main__': app.run(host='0.0.0.0', port=3001, debug=True) ``` - **requirements.txt** ``` Flask==1.1.1 requests==2.22.0 ``` - ** uwsgi.ini ** ``` [uwsgi] chdir = /app wsgi-file = /app/app.py callable = app plugin = python3 uwsgi-socket = /app/uwsgi.sock chmod-socket = 777 ``` #### 启动 ``` docker build -t pytest:1.0 . docker run -itd --name pytest -p 3001:3001 -v /data/pytest:/log/ pytest:1.0 ``` #### 测试 ``` [root@localhost]# curl -XGET http://127.0.0.1:3001/hello hello, this is a test page ``` #### 遇到的问题 **1. py文件中含有 ^M 符号** 我的是centos7系统,yum安装 dos2unix转换 ``` [root@localhost]# yum -y install dos2unix [root@localhost]# dos2unix app.py ``` **2. 如果只使用uwsgi,不使用nginx,则uwsgi配置文件如下** ``` [uwsgi] http-socket = 0.0.0.0:3001 chdir = /app wsgi-file = /app/app.py callable = app plugin = python3 ``` 最后修改:2019 年 08 月 21 日 03 : 53 PM © 著作权归作者所有