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

多阶段Docker构建下Go程序无法读取容器内已存在的CSV文件问题求助

多阶段Docker构建下Go程序无法读取容器内已存在的CSV文件问题求助

大家好,我碰到了一个挺费解的问题:用Docker多阶段构建部署Go项目时,明明能在容器里看到项目根目录下的promotions.csv文件,但Go代码里调用readCSVFile("promotions.csv")却一直返回错误:open promotions.csv: no such file or directory。但如果不用多阶段构建,程序就能正常读取这个文件,实在搞不清哪里出问题了,想请教下各位大佬。

我的多阶段构建Dockerfile

# Start from a base Go image
FROM golang:1.19 as builder

# Set the working directory inside the container
WORKDIR /app

# Copy the Go module files
COPY go.mod go.sum ./

# Download the dependencies
RUN go mod download

# Copy the rest of the application code
COPY . .

# Copy the promotions.csv into the container
RUN chmod +r /app/promotions.csv
COPY promotions.csv /app/promotions.csv

# Run with disabled cross-compilation
RUN CGO_ENABLED=0 GOOS=linux go build -o app .

# Final stage
FROM alpine:3.18

RUN apk --no-cache add ca-certificates

WORKDIR /root/

COPY --from=builder --chown=${USERNAME}:${USERNAME} /app/app .

EXPOSE 1321

CMD ["./app"]

问题细节

我已经确认promotions.csv确实存在于容器的文件系统中,但Go程序执行时就是找不到这个文件。

单阶段构建(可正常运行)的Dockerfile

# Start from a base Go image
FROM golang:1.19 as builder

# Set the working directory inside the container
WORKDIR /app

# Copy the Go module files
COPY go.mod go.sum ./

# Download the dependencies
RUN go mod download

#COPY promotions.csv ./

# Copy the rest of the application code
COPY . .

# Copy the promotions folder into the container
# Run with disabled cross-compilation
RUN go build -o main

EXPOSE 1321

CMD ["./main"]

配套的docker-compose.yml

version: '3'

services:
  postgres:
    image: postgres:15.3-alpine
    restart: always
    ports:
      - 5432:5432
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password
      POSTGRES_DB: vrstore
  app:
    build:
      context: .
      dockerfile: Dockerfile
    restart: always
    ports:
      - 1321:1321
    depends_on:
      - postgres
    volumes:
      - .:/app
    environment:
      DATABASE_HOST: postgres
      DATABASE_PORT: 5432
      DATABASE_NAME: vrstore
      DATABASE_USER: postgres
      DATABASE_PASSWORD: password

有没有可能我漏掉了什么很明显的配置?麻烦各位帮忙排查下,谢谢啦!

备注:内容来源于stack exchange,提问作者Avag Sargsyan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 12:39:36