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: