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

Docker构建Node.js/TypeScript项目时.env.example文件未复制至镜像及Docker Compose报错问题求助

解决.env.example未复制到Docker镜像的问题

我来帮你排查并解决这个问题,核心问题很明确:代码在容器内尝试读取.env.example时找不到文件,这是因为这个文件没有被放到代码期望的位置。

问题分析

  1. Dockerfile复制路径不匹配:
    在builder阶段你把.env.example复制到了./dist目录,但在stage2中,你只将builder的dist目录同步到容器的./dist,导致容器里的.env.example存放在/usr/app/dist/.env.example,但你的代码是从项目根目录(/usr/app)读取这个文件,自然会提示找不到。
  2. Docker Compose的冗余挂载:
    你配置了volumes: - ./src:/src,这会把宿主机的src目录挂载到容器的/src,但你的服务是运行dist里的编译后代码,这个挂载不仅毫无作用,还可能打乱容器内的目录结构,建议移除。

解决方案

方案1:修正Dockerfile,将.env.example放到容器项目根目录

修改Dockerfile,在stage2中把.env.example放到容器的工作目录(即代码读取的路径):

# stage 1 building the code
FROM node as builder
WORKDIR /usr/app
COPY package*.json ./
RUN npm install
COPY . .
COPY .env.production .env
RUN npm run build

# stage 2
FROM node
WORKDIR /usr/app
COPY package*.json ./
RUN npm install --production
COPY --from=builder /usr/app/dist ./dist
# 新增这一步:从builder阶段复制.env.example到当前工作目录
COPY --from=builder /usr/app/.env.example ./
COPY ormconfig.docker.json ./ormconfig.json
EXPOSE 4000
CMD node dist/index.js

或者更简洁的方式:因为你的.dockerignore没有排除.env.example,可以直接在stage2从宿主机复制,省去builder阶段的多余步骤:

# stage 2部分修改
FROM node
WORKDIR /usr/app
COPY package*.json ./
COPY .env.example ./  # 直接从本地复制到容器工作目录
RUN npm install --production
COPY --from=builder /usr/app/dist ./dist
COPY ormconfig.docker.json ./ormconfig.json
EXPOSE 4000
CMD node dist/index.js

方案2:调整代码读取路径(可选)

如果你的代码可以修改,把读取.env.example的路径改为./dist/.env.example,这样不用修改Dockerfile就能解决问题,但这种方式可能会和本地开发的路径逻辑冲突,灵活性较差。

额外优化:清理Docker Compose冗余配置

修改docker-compose.yaml,移除web服务中不必要的目录挂载:

version: "3.7"
services:
  db:
    image: postgres
    environment:
      POSTGRES_PASSWORD: postgres
      POSTGRES_USER: postgres
      POSTGRES_DB: postgres
    volumes:
      - ./pgdata:/var/lib/postgresql/data
    ports:
      - "5432:5432"
  web:
    build:
      context: ./
      dockerfile: ./Dockerfile
    depends_on:
      - db
    ports:
      - "4000:4000"
    # 移除下面冗余的挂载配置
    # volumes:
    #   - ./src:/src

验证步骤

  1. 执行docker-compose build重新构建镜像
  2. 执行docker-compose up启动服务
  3. 进入容器验证文件位置:docker exec -it <你的web容器名称> ls /usr/app,应该能看到.env.example出现在根目录下

这样就能解决你遇到的“no such file or directory, open '.env.example'”错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 10:24:08