You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker容器中Nginx反向代理Express时静态文件直接服务配置问题

解决Nginx反向代理API+静态文件404问题

核心问题

你的Nginx容器与API容器相互独立,Nginx无法直接访问API容器内部的/public/images目录,这是图片请求返回404的根本原因。

解决方案步骤

1. 用Docker卷共享静态文件

修改docker-compose.yml,添加共享卷,让Nginx容器能访问到API里的图片文件:

services:
  api:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: api
    volumes:
      # 定义共享卷,映射API容器内的静态文件目录,路径需与API Dockerfile一致
      - static_files:/app/public/images

  nginx-proxy:
    build:
      context: .
      dockerfile: Dockerfile.nginx
    container_name: nginx-proxy
    ports:
      - "8080:80"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf
      # 将共享卷挂载到Nginx容器内的指定路径
      - static_files:/usr/share/nginx/html/images
    depends_on:
      - api

# 声明全局共享卷
volumes:
  static_files:

2. 调整Nginx配置

修改nginx.conf中的/images/规则,指向Nginx容器内挂载的卷路径:

server {
    listen 80;
    server_name localhost;

    location / {
        proxy_pass http://api:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    location /images/ {
        # 指向Nginx容器内挂载的共享卷路径
        alias /usr/share/nginx/html/images/;
        # 可选:添加静态文件缓存优化
        expires 30d;
        add_header Cache-Control "public, no-transform";
    }
}

3. 确认API的Dockerfile路径

确保API的Dockerfile中复制图片的路径与共享卷映射路径一致,示例:

WORKDIR /app
# 将本地图片目录复制到API容器内的指定路径
COPY ./public/images /app/public/images

验证操作

  1. 停止并重新构建容器:docker-compose down && docker-compose up --build
  2. 访问http://localhost:8080/images/test.png,确认图片正常返回
  3. 测试常规API请求(如http://localhost:8080/api/users),确认反向代理生效

内容的提问来源于stack exchange,提问作者Dev T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 14:23:10