nginx反向代理docker容器化django

1.新建Dockerfile

FROM python:3.8.5
MAINTAINER ChsterChen
ENV PYTHONUNBUFFERED 1
COPY pip.conf /root/.pip/pip.conf
RUN mkdir -p /var/www/html/student_api
WORKDIR /var/www/html/student_api
ADD . /var/www/html/student_api
RUN pip install -r requirements.txt
RUN chmod a+rwx -R /var/www/html/student_api/
RUN pwd
VOLUME ["/tmp"]
EXPOSE 8000
ENTRYPOINT ["uwsgi", "--ini", "uwsgi-docker.ini"]
# RUN python manage.py collectstatic --noinput]

2.新建pip.conf国内镜像源

 [global]
 index-url = https://mirrors.aliyun.com/pypi/simple/
 [install]
 trusted-host=mirrors.aliyun.com

3.生成requirement.txt

pip3 freeze > requirements.txt

4.新建uwsgi-docker.ini配置文件

[uwsgi]
project=student_api
uid=www-data
gid=www-data
base=/var/www/html

chdir=%(base)/%(project)
module=signup_api.wsgi:application
master=True
processes=2

http=0.0.0.0:8000 #这里直接使用uwsgi做web服务器,使用http。如果使用nginx,需要使用socket沟通。
buffer-size=65536

pidfile=/tmp/%(project)-master.pid
vacuum=True
max-requests=5000
# daemonize=/tmp/%(project)-uwsgi.log   #注释掉,不然成为后台进程,容器会直接退出

#设置一个请求的超时时间(秒),如果一个请求超过了这个时间,则请求被丢弃
harakiri=60
#当一个请求被harakiri杀掉会,会输出一条日志
harakiri-verbose=true
static-map = /static=%(base)/%(project)/static

5.生成镜像

sudo docker build -t student_api:v1 .

6.运行容器

sudo docker run -v /docker/volume:/tmp -it -d --name student_api -p 8001:8000 student_api:v1

7.接口文档等前端静态文件无法通过uwsgi访问到,需通过python ./manage.py collectstatic把所有静态资源生成到STATIC_ROOT文件夹内    //note.qidong.name/2017/07/uwsgi-serve-django-static/

先settings.py中修改

STATIC_ROOT = '你的项目目录/static'

然后通过以下命令把静态文件生成到STATIC_ROOT目录

python ./manage.py collectstatic

uwsgi配置文件中新增静态文件映射配置

static-map = /static=%(base)/%(project)/static

重新build镜像+运行容器

8.nginx配置

    location / 
    {
        proxy_set_header Host $http_host;    #重要,影响到接口文档的正常浏览
        proxy_set_header  X-Real-IP        $remote_addr;
        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
 
        proxy_pass http://127.0.0.1:8001/;
    }

 

Tags: