我正在使用Django 2.0Dockernginx为我们设置gunicorn应用程序。

它正在运行服务器,但是静态文件不起作用。

这是settings.py的内容

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static_my_project')
]

STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'static_root')

在开发过程中,我将我的静态文件放入static_my_project内,将其运行时将collectstatic复制到static_cdn/static_root
目录结构就像
app
 |- myapp
    |- settings.py
 |- static_my_project
 |- static_cdn
    |- static_root
 |- config
    |- nginx
       |- nginx.conf
 |- manage.py
 |- Docker
 |- docker-compose.yml

在运行
docker-compose up --build

在运行collectstatic时,它提供了将静态文件复制到的路径



config/nginx/nginx.conf 文件包含以下设置
upstream web {
    ip_hash;
    server web:9010;
}

server {
    location /static {
        autoindex on;
        alias /static/;
    }

    location / {
        proxy_pass http://web;
    }
    listen 10080;
    server_name localhost;
}

docker-compose.yml
version: '3'

services:
  nginx:
    image: nginx:latest
    container_name: "koober-nginx"
    ports:
      - "10080:80"
      - "10443:43"
    volumes:
      - .:/app
      - ./config/nginx:/etc/nginx/conf.d
      - ./static_cdn/static_root/:/static
    depends_on:
      - web
  web:
    build: .
    container_name: "koober-dev"
    command: ./start.sh
    volumes:
      - .:/app
      - ./static_cdn/static_root/:/app/static_cdn/static_root
    ports:
      - "9010:9010"
    depends_on:
      - db
  db:
    image: postgres
    container_name: "koober-postgres-db"

Dockerfile
FROM ubuntu:18.04

# -- Install Pipenv:
FROM python:3
ENV PYTHONUNBUFFERED 1

ENV LC_ALL C.UTF-8
ENV LANG C.UTF-8

# -- Install Application into container:
RUN set -ex && mkdir /app

WORKDIR /app
ADD requirements.txt /app/

RUN pip install -r requirements.txt

# -- Adding dependencies:
ADD . /app/

但它没有加载静态文件。

最佳答案

您需要具有到STATIC_ROOT目录的共享卷,以便nginx容器可以反向代理Web服务器和Web服务器生成的静态文件。

docker-compose.yml中:

services:
  nginx:
    image: nginx:alpine
    volumes:
      - ./static_cdn/static_root/:/static
    ports:
      - 80:80
  web:
    build: .
    volumes:
      - ./static_cdn/static_root/:/app/static_cdn/static_root

现在在您的nginx.conf中添加:
location /static/ {
    alias /static/;
}

关于django - 使用Docker,nginx和gunicorn提供Django静态文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50685775/

10-12 00:38
查看更多