[英]How can I serve Django static files via nginx Docker container?
During development I like to deploy Django static files in an as close to production as possible setup.在开发过程中,我喜欢在尽可能接近生产的设置中部署 Django 静态文件。 To achieve this I wrap the Django backend into an image (
Dockerfile
) and frontend JS and backend Django static files into another image together with nginx
configured as webserver ( Dockerfile_nginx
).为了实现这一点,我将 Django 后端包装到一个图像 (
Dockerfile
) 中,并将前端 JS 和后端 Django 静态文件与配置为网络服务器 ( Dockerfile_nginx
) 的nginx
一起Dockerfile_nginx
到另一个图像中。 The setup is as follows:设置如下:
File system structure:文件系统结构:
<projekt-repo>
/frontend
/backend
/static (generated with python manage.py collectstatic)
settings.py
manage.py
nginx.conf
Dockerfile
Dockerfile_nginx
settings.py
: settings.py
:
STATIC_ROOT = os.path.join(BASE_DIR, "backend/static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
nginx.conf
: nginx.conf
:
server {
listen 0.0.0.0:8080;
root /var/www;
location / {
try_files $uri $uri/ /index.html;
}
}
server {
listen 0.0.0.0:8000;
root /var/www/django;
location /static/ {
autoindex on;
alias /var/www/django/static/;
}
}
Dockerfile_nginx
: Dockerfile_nginx
:
FROM nginx:1.17.8-alpine
COPY nginx.conf /etc/nginx/conf.d/nginx.conf
COPY edge_frontend/www /var/www
COPY edge_backend/static /var/www/django/static
If I run the application and try to login via the Django admin site ( localhost:8000/admin
) the site is not styled properly and the log output states如果我运行该应用程序并尝试通过 Django 管理站点 (
localhost:8000/admin
) 登录,则该站点的样式不正确并且日志输出状态
backend | Not Found: /static/admin/css/base.css
backend | Not Found: /static/admin/css/login.css
backend | Not Found: /static/admin/css/responsive.css
backend | Not Found: /favicon.ico
backend | Not Found: /static/admin/css/base.css
backend | Not Found: /static/admin/css/login.css
backend | Not Found: /static/admin/css/responsive.css
backend | Not Found: /favicon.ico
Obviously there is some mismatch in the setup which I am not able to spot right now?显然,设置中存在一些我现在无法发现的不匹配? Can someone help?
有人可以帮忙吗?
create a folder in your project with the name "static" and then在您的项目中创建一个名为“static”的文件夹,然后
add in your settings.py添加你的settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
or you want another path?或者你想要另一条路?
You have to set BASE_DIR
, STATIC_URL
and STATIC_ROOT
in settings.py
as below...您必须在
settings.py
设置BASE_DIR
、 STATIC_URL
和STATIC_ROOT
如下...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
And run python manage.py collectstatic
并运行
python manage.py collectstatic
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.