serving Django static files with Docker, nginx and gunicorn
我使用
它正在运行服务器,但是静态文件不起作用。
这是
1 2 3 4 5 6 7 | STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_my_project') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'static_root') |
在开发过程中,我将静态文件放入
目录结构就像
1 2 3 4 5 6 7 8 9 10 11 12 | app |- myapp |- settings.py |- static_my_project |- static_cdn |- static_root |- config |- nginx |- nginx.conf |- manage.py |- Docker |- docker-compose.yml |
在跑步
1 | docker-compose up --build |
在运行
koober-dev | --: Running collectstatic
koober-dev |
koober-dev | You have requested to collect static files at the destination
myapp-dev | location as specified in your settings:
myapp-dev |
myapp-dev | /app/static_cdn/static_root
myapp-dev |
myapp-dev | This will overwrite existing files!
myapp-dev | Are you sure you want to do this?
myapp-dev |
myapp-dev | Type 'yes' to continue, or 'no' to cancel:
myapp-dev | 0 static files copied to '/app/static_cdn/static_root', 210 unmodified.
config / nginx / nginx.conf文件包含以下设置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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" |
Docker文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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/ |
但是它没有加载静态文件。
您需要到
在
1 2 3 4 5 6 7 8 9 10 11 | 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中添加:
1 2 3 | location /static/ { alias /static/; } |