当通过Docker多级构建复制到容器中时,无法从位于项目根目录的Golang打开简单文件。但是我可以看到容器中的文件。
下面是我的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
文件存在于容器文件系统中:
但是,main.go
中的records, err := readCSVFile("promotions.csv")
代码返回错误:
打开促销.csv:没有这样的文件或目录
更奇怪的是,当我不使用多阶段构建时,一切都工作得很好:
# 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
在第一种情况下,错误的原因可能是什么?也许我错过了一些明显的东西。谢谢
1条答案
按热度按时间nsc4cvqm1#
该文件不存在于映像中,因为您没有将其复制到映像中。
在容器中,将文件作为卷挂载到
/app
中:但是,您正在运行来自
/root
的二进制文件:所以二进制文件正在寻找
/root/promotions.csv
,但找不到它。您需要将目录更改为/app
或使用完全限定路径打开文件。