Docker 中如何配置 Nginx 使其伺服静态文件?
我在开发一个 Django 项目,使用 Docker + Nginx + Gunicorn 构建一个本地运行环境,但是 Nginx 无法找到静态文件。配置如下:
compose 文件:
version: '2'
services:
django:
build:
context: .
dockerfile: ./compose/django/Dockerfile
command: /gunicorn.sh
volumes:
- .:/app
nginx:
build: ./compose/nginx
depends_on:
- django
ports:
- "0.0.0.0:80:80"
Nginx 配置文件:
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
upstream app {
server django:5000;
}
server {
listen 80;
charset utf-8;
location / {
# checks for static file, if not found proxy to app
try_files $uri @proxy_to_app;
}
# cookiecutter-django app
location @proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://app;
}
}
}
所有静态文件位于 /static 目录下。从问题分析来看,我认为是在 nginx 容器中没有挂载 /static,所以 nginx 容器无法访问到静态文件。问题是我该如何挂载?把 /static 挂载到 nginx 容器的什么路径?是否需要修改 nginx 的配置?
1 个回复
wisen
赞同来自:
/static 是静态文件所在宿主机目录?对于nginx来说,默认静态文件目录应该是/usr/share/nginx/html,如果想要对静态文件目录进行配置修改,可以去搜索一下 nginx location 相关资料。比如: (http://www.cnblogs.com/sunjiguang/p/6227518.html)。如果你想使用宿主机上/static中的静态资源,可以通过/static:/usr/share/nginx/html这种方式把静态资源挂载到容器中。