在`go build`命令中包含.env文件

I have the following Dockerfile which builds an image for my Go project.

FROM golang:1.11.2-alpine3.8 as go-compile

RUN apk update && apk add git
RUN mkdir /app
COPY src/ /app
WORKDIR /app

RUN go get github.com/joho/godotenv

RUN go build -o main .

FROM alpine:latest

RUN mkdir /app
COPY --from=go-compile /app/main /app/main

CMD ["/app/main"]

The image builds, but my ".env" file is not included in the Docker image.

I've tried to copy the ".env" from the src folder into the image using COPY src/.env /app/.env, but still the Go code can't find/read the file.

How can I include the ".env" file, or in fact any other non Go file?

You cannot include non-go files in the go build process. The Go tool doesn't support "embedding" arbitrary files into the final executable.

You should use go build to build your executable then, any non-go files, e.g. templates, images, config files, need to be made available to that executable. That is; the executable needs to know where the non-go files are on the filesystem of the host machine on which the go program is running, and then open and read them as needed. So forget about embeding .env into main, instead copy .env together with main to the same location from which you want to run main.

Then the issue with your dockerfile is the fact that the target host only copies the final executable file from go-compile (COPY --from=go-compile /app/main /app/main), it doesn't copy any other files that are present in the go-compile image and therefore your main app cannot access .env since they are not on the same host.


As pointed out in the comments by @mh-cbon, there do exist 3rd-party solutions for embedding non-go files into the go binary, one of which is gobuffalo/packr.