【问题标题】:deploy to docker , cannot load stylesheet and javascript部署到 docker,无法加载样式表和 javascript
【发布时间】:2025-12-31 01:55:07
【问题描述】:

这是我的docker-compose.yml

version: '2'

services:
  web:
    restart: always
    build: ./web
    expose:
      - "8000"
    volumes:
      - /usr/src/app/web/project/static
    command: /usr/local/bin/gunicorn -w 2 -b :8000 project:app
    depends_on:
      - postgres

  nginx:
    restart: always
    build: ./nginx
    ports:
      - "80:80"
    volumes:
      - /www/static
    volumes_from:
      - web
    depends_on:
      - web

  data:
    image: postgres:9.6
    volumes:
      - /var/lib/postgresql
    command: "true"

  postgres:
    restart: always
    build: ./postgresql
    volumes_from:
      - data
    expose:
      - "5432"

当我部署到 docker 容器时,网站没有样式 css,js 加载正确,请大家帮忙?

更新

# Define the parameters for a specific virtual host/server
server {
    # Define the directory where the contents being requested are stored
    # root /usr/src/app/project/;

    # Define the default page that will be served If no page was requested
    # (ie. if www.ezloan.amkcambodia.com is requested)
    # index index.html;

    # Define the server name, IP address, and/or port of the server
    listen 80;
    # server_name xxx.yyy.zzz.aaa

    # Define the specified charset to the “Content-Type” response header field
    charset utf-8;

    # Configure NGINX to deliver static content from the specified folder
    location /static {
        alias /usr/src/app/web/project/static;
    }

    # Configure NGINX to reverse proxy HTTP requests to the upstream server (Gunicorn (WSGI server))
    location / {
        # Define the location of the proxy server to send the request to
        proxy_pass http://web:8000;

        # Redefine the header fields that NGINX sends to the upstream server
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        # Define the maximum file size on file uploads
        client_max_body_size 5M;
        client_body_buffer_size 5M;
    }
}

【问题讨论】:

  • 可以显示static文件夹的内容吗? js 也是驻留在静态文件夹中还是来自网络?
  • 我将它加载到这样的模板中<link href="{{ url_for('static', filename='css/bootstrap-select.min.css') }}" rel="stylesheet">
  • 当我访问 http://0.0.0.0/static/css/bootstrap-select.min.css 时显示 404 Not Found
  • 是的,我知道css 不起作用...但是js 起作用的文件呢?它们也来自本地文件夹吗?通常docker中的volumes标签定义为src(host):dest(guest)
  • 是的 js 不能正常工作,它在静态文件夹中。

标签: docker nginx flask


【解决方案1】:

尝试将web 上的volumes 指令更改为

volumes:
   - /usr/src/app/web/project/static:<path of app on the container>

关于 Nginx

静态文件存放在哪里?在web 容器或nginx 中? 如果它们存储在nginx 中,您需要将alias 指向 nginx 容器上的位置,您可以在其中安装 nginx 的卷,例如

volumes:
    - /usr/src/app/web/project/static:/www/static

并在 nginx conf 中使用

location /static {
    alias /www/static;
}

如果web容器中存储的静态比nginx需要重定向调用到web,则不需要location /static

【讨论】:

  • 我更新了ngixn,请帮忙检查一下,是nginx的问题吗?
  • @kn3l 添加了我对 nginx conf 的回答