【问题标题】:NGINX serving flask static filesNGINX 服务烧瓶静态文件
【发布时间】:2026-02-10 04:20:02
【问题描述】:

我的任务是创建 3 层架构,其中包括:

  • NGINX 服务器
  • Flask 服务器
  • 数据库的弹性搜索

我在直接从 nginx 提供所有静态文件(包括 index.html)时遇到问题

现在我可以访问 localhost:5000 上的 Flask 服务器了 但我在 localhost:80 上得到 404

码头工人撰写:

version: "3.3" 
services: 
    ngnix_my:
        build: ./nginx/.
        ports:
            - "80:80"
        links: 
            - app
        depends_on: 
            - app
        networks: 
            - front_net
    app: 
        build: . 
        ports: 
            - "5000:5000" 
        links: 
            - es 
        depends_on: 
            - es 
        networks: 
            - front_net
            - back_net
    es: 
        image: elasticsearch:7.13.1 
        environment: 
            - discovery.type=single-node
        networks: 
            - back_net  
        
networks: 
    front_net:
        driver: bridge
    back_net:
        driver: bridge

NGINX Dockerfile:

FROM nginx:1.21.0-alpine
COPY ./nginx.conf /etc/nginx/nginx.conf
COPY ./to_serve /
RUN sudo chmod -R 777 /templates/index.html

ngnix.conf:

events {} # event context needs to be defined to consider config valid

http {
  server {
    listen 80 default_server;
  
    location /static {
      root /templates/index.html; 
    }

    location / {
      proxy_pass         http://app:5000;
      proxy_redirect     off;

      proxy_set_header   Host             $host;
      proxy_set_header   X-Real-IP        $remote_addr;
      proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
    }
  }
}

【问题讨论】:

    标签: html docker nginx flask docker-compose


    【解决方案1】:

    好吧,根据您的日志和 docker 文件,我认为您的静态文件位于 /to_serve/templates/static 而不是 /templates/index.html
    因此,将/static 位置的 nginx 配置更改为:

    location /static {
      root /to_serve/templates/index.html; 
    }
    

    然后再次测试

    【讨论】:

    • root directive 需要是一个目录。在问题和这个答案中,“目录”不存在,因此是 404。我建议打开错误日志并阅读 nginx 在哪里寻找文件。
    • 是的,正如 AD7six 所说,我在更改后的 omid 时遇到了同样的错误,建议尝试打开错误日志但无法理解..感觉迷失了 -_-