django - 使用 Traefik 时如何使用 Nginx 和 Django Gunicorn 提供静态内容
问题描述
我有一个使用多个容器的 Web 应用程序(基于 Django):
- Web 应用程序(Django + Gunicorn)
- Traefik(充当反向代理和 SSL 终止)
- 与 Web 应用程序一起使用的数据库
- 与 Web 应用程序一起使用的 Redis
根据我读过的一些文档,我应该使用 NGINX 之类的东西来提供我的静态内容。但我不知道我将如何做到这一点。我会将 NGINX 安装在我的 Web 应用程序容器上还是作为单独的 NGINX 容器。如何传递来自 Traefik 的请求?据我所知,您无法使用 Traefik 提供静态内容。
这就是我的 docker-compose.yml 的样子:
traefik:
image: traefik
ports:
- 80:80
- 8080:8080
- 443:443
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- ./traefik/traefik.toml:/etc/traefik/traefik.toml:ro
- ./traefik/acme:/etc/traefik/acme
web:
build: .
restart: always
depends_on:
- db
- redis
- traefik
command: python3 /var/www/html/applications/py-saleor/manage.py makemigrations --noinput
command: python3 /var/www/html/applications/py-saleor/manage.py migrate --noinput
command: python3 /var/www/html/applications/py-saleor/manage.py collectstatic --noinput
command: bash -c "cd /var/www/html/applications/py-saleor/ && gunicorn saleor.wsgi -w 2 -b 0.0.0.0:8000"
volumes:
- .:/app
ports:
- 127.0.0.1:8000:8000
labels:
- "traefik.enable=true"
- "traefik.backend=web"
- "traefik.frontend.rule=${TRAEFIK_FRONTEND_RULE}"
environment:
- SECRET_KEY=changemeinprod
redis:
image: redis
db:
image: postgres:latest
restart: always
environment:
POSTGRES_USER: saleoradmin
POSTGRES_PASSWORD: **
POSTGRES_DB: **
PGDATA: /var/lib/postgresql/data/pgdata
volumes:
- ~/py-saleor/database:/app
解决方案
如果其他人需要这个问题的答案,答案在于创建一个单独的 NGINX 服务,然后将前端规则定向到静态位置(xyz.com/static),例如见下文(docker-compose.yml 的一部分):
nginx:
image: nginx:alpine
container_name: nginx_static_files
restart: always
volumes:
- ./default.conf:/etc/nginx/conf.d/default.conf
- ./saleor/static/:/static
labels:
- "traefik.enable=true"
- "traefik.backend=nginx"
- "traefik.frontend.rule=Host:xyz.co;PathPrefix:/static"
- "traefik.port=80"
您还需要确保您的 Nginx 配置文件 (default.conf) 已正确配置:
server {
listen 80;
server_name _;
client_max_body_size 200M;
set $cache_uri $request_uri;
location = /favicon.ico { log_not_found off; access_log off; }
location = /robots.txt { log_not_found off; access_log off; }
ignore_invalid_headers on;
add_header Access-Control-Allow_Origin *;
location /static {
autoindex on;
alias /static;
}
location /media {
autoindex on;
alias /media;
}
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
}
所有功劳都归功于 Traefik 松弛频道上的 Pedro Rigotti,他帮助我找到了解决方案。
推荐阅读
- encoding - 雪花:将字段编码转换为 UTF8
- javascript - 将 Javascript Date 对象转换为 Java LocalDateTime
- c++ - 在 SDL 或任何语言中绘制圆圈的内存友好方式?
- javascript - 在 3 个不同的谷歌折线图中可视化数据
- javascript - 返回嵌套承诺但未找到响应
- r - Issues running a GLHT following a GLM in R due to 1 missing interaction
- php - 生产中的 Codeigniter 4 会话问题
- python - 熊猫保存并打开然后值更改为字符串问题
- amazon-web-services - 无法通过 CFT 在 CodeBuild 项目上成功设置 SNS,但手动工作
- rust - Does Rust have an elegant way to manipulate values further when assigning a value from a block statement?