在NGINX Docker容器中用JavaScript读取本地文件出现404错误
问题原因
Nginx默认仅对外暴露/usr/share/nginx/html目录下的静态资源,你挂载到容器的/log目录不在Nginx的资源映射范围内,因此前端请求/log/example.log时,Nginx无法定位到文件,返回404错误。
解决步骤
1. 创建自定义Nginx配置文件
在本地项目根目录新建conf文件夹,在其中创建default.conf文件,内容如下:
server { listen 80; server_name localhost; # 原有静态资源访问配置 location / { root /usr/share/nginx/html; index index.html index.htm; } # 添加日志目录的访问映射 location /log/ { root /; # 指向容器根目录,使请求/log/example.log对应容器内的/log/example.log autoindex off; # 关闭目录索引,避免泄露目录结构 add_header Cache-Control no-cache; # 禁止缓存日志,确保获取实时内容 } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }
2. 修改Dockerfile
更新Dockerfile,将自定义配置文件复制到Nginx默认配置目录,替换原有配置:
FROM nginx:latest COPY ./index.html /usr/share/nginx/html/index.html COPY ./script.js /usr/share/nginx/html/script.js # 复制自定义Nginx配置 COPY ./conf/default.conf /etc/nginx/conf.d/default.conf
3. 重新构建并启动容器
执行以下命令重新构建镜像并启动容器:
docker build -t webserver . docker run -it --rm -d -p 8088:80 --name web --mount type=bind,source=/Users/username/projects/website,target=/log,readonly webserver
额外注意事项
- 确认主机
/Users/username/projects/website目录下存在example.log文件,且文件权限允许容器内Nginx进程读取(可临时执行chmod o+r /Users/username/projects/website/example.log测试)。 - 若日志更新后前端未获取到最新内容,可在请求URL后添加时间戳参数(如
/log/example.log?t=${Date.now()})强制绕过浏览器缓存。
内容的提问来源于stack exchange,提问作者0xDEADBEEF
相关产品推荐
相关产品推荐

