繁体   English   中英

我在谷歌云运行中的 docker 图像不读取 css 文件

[英]My docker image in google cloud run doesn't read css file

我使用由 docker 组成的 Django 创建我的网站。

When I compile this docker image, the app shows a webpage with CSS, on the other hand when I deploy this docker image on the google cloud run then it shows only HTML file, I mean it doesn't include CSS file so that it shows只是文字。

有谁知道为什么会这样? 如果有人知道,请告诉我如何使用 styles 显示我的网站。

collectstatic在生产中是必需的,但在开发中不是必需的。 这个想法是在项目的根目录下创建一个 static 文件夹,nginx(或您正在使用的任何服务器)可以直接访问它。 使用Docker时,一种常见的方法是包含一个入口点。

为此,请将以下内容添加到您的Dockerfile

ENV APP_HOME=/code # replace with your container's root dir
COPY ./entrypoint.sh $APP_HOME
ENTRYPOINT ["/code/entrypoint.sh"]

entrypoint.sh看起来像这样:

#!/bin/sh

set -e

# python entry point commands go here
python manage.py migrate
python manage.py collectstatic --no-input

exec "$@"

还要确保你有类似的东西

STATIC_URL = "/staticfiles/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")

在你的settings.py

rest 取决于您的服务器设置(nginx、apache 或您正在使用的任何东西)但可能看起来像

location /static/ {
    root /code/static/;
    autoindex off;
}

在 nginx 中。

我发现一个非常有用的工具是whitenoise 只需按照设置指南进行操作,您就可以跳过 nginx 的内容。

按照 John Kealy 提到的Whitenoise中的设置进行操作。

设置 setting.py 文件,如下所示。

MIDDLEWARE = [
  'django.middleware.security.SecurityMiddleware',
  'whitenoise.middleware.WhiteNoiseMiddleware',
  # ...
]
INSTALLED_APPS = [
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    # ...
]
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATIC_URL = "/staticfiles/" #the folder name you want

然后在 python 解释器中执行以下命令。 或者按照 John 的描述将其写在 Dockerfile 中。

python manage.py collectstatic --no-input

然后部署镜像。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM