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

基于HTML/CSS/JS构建可用Docker镜像及资源缺失问题排查

问题分析与解决:Docker部署静态网站资源找不到的问题

我是Docker新手,大学任务要开发HTML/CSS/JS网站并提供Docker Compose配置。看了很多教程也问过ChatGPT,一开始构建镜像启动后跳转到Nginx默认页面;后来手动把index.html复制到镜像里,启动容器又找不到styles.css和scripts.js,现在完全懵了。

我用到的配置文件:

Dockerfile

FROM nginx:latest
RUN rm /etc/nginx/conf.d/default.conf

COPY nginx.conf /etc/nginx/conf.d/nginx.conf

COPY index.html /var/www/html/index.html
COPY styles.css /var/www/html/style.css
COPY scripts.js /var/www/html/script.js

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

nginx.conf

server {
    listen 80;
    server_name test.local;
    index index.html;
    root /var/www/html;
}

docker-compose.yml

version: '3'
services:
    web:
    image: nginx:latest
    volumes:
        - "./nginx.conf:/etc/nginx/conf.d/default.conf"
        - "./code:/var/www/html"
    ports:
        - "80:80"

Docker Desktop错误日志

2023/06/30 11:09:37 [error] 20#20: *1 open() "/var/www/html/styles.css" failed (2: No such file or directory)
2023/06/30 11:09:37 [error] 21#21: *2 open() "/var/www/html/scripts.js" failed (2: No such file or directory)

问题根源

  1. Dockerfile与docker-compose.yml冲突:你在Dockerfile里把静态文件打包进了镜像,但docker-compose里用./code:/var/www/html卷挂载直接覆盖了镜像里的目录。如果本地./code里没有对应资源,容器自然找不到。同时docker-compose用的是官方nginx镜像,根本没用到你构建的自定义镜像,这也是一开始出现默认页面的原因。
  2. 文件名复制错误:Dockerfile里把styles.css复制成了style.css,scripts.js复制成了script.js,但网页引用的是原文件名,导致路径不匹配。
  3. docker-compose缩进错误:web服务的配置没有正确缩进,YAML语法对缩进敏感,会导致配置失效。

两种解决方案

方案一:用自定义镜像部署(适合提交任务/生产环境)

这种方式把所有资源打包进镜像,不依赖本地文件,部署更稳定。

  1. 修正Dockerfile的文件名复制错误:
FROM nginx:latest
RUN rm /etc/nginx/conf.d/default.conf

COPY nginx.conf /etc/nginx/conf.d/nginx.conf

COPY index.html /var/www/html/index.html
COPY styles.css /var/www/html/styles.css  # 修正文件名
COPY scripts.js /var/www/html/scripts.js  # 修正文件名

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]
  1. 修改docker-compose.yml,使用自己构建的镜像:
version: '3'
services:
  web:
    build: .  # 基于当前目录的Dockerfile构建镜像
    ports:
      - "80:80"
  1. 本地文件结构保持:
当前目录/
├── Dockerfile
├── nginx.conf
├── index.html
├── styles.css
└── scripts.js
  1. 启动命令:
docker-compose up --build

方案二:卷挂载方式(适合开发时实时改代码)

这种方式本地代码修改后会同步到容器,不用重新构建镜像。

  1. 整理本地文件结构,确保code目录包含所有静态资源:
当前目录/
├── docker-compose.yml
├── nginx.conf
└── code/
    ├── index.html
    ├── styles.css
    └── scripts.js
  1. 修正docker-compose.yml的缩进错误:
version: '3'
services:
  web:
    image: nginx:latest
    volumes:
      - "./nginx.conf:/etc/nginx/conf.d/default.conf"
      - "./code:/var/www/html"
    ports:
      - "80:80"
  1. 启动命令:
docker-compose up

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:12:56