Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

How to pass .env file to docker image in a Go project?

My Go project heriarchy is this:

enter image description here

The main function:

func main() {
    path, _ := os.Getwd()
    err := godotenv.Load(filepath.Join(path, ".env"))
    if err != nil {
        log.Fatal("Error loading .env file")
    }
    server.Init()
}

Here is my docker file content:

FROM golang:alpine AS build-env
LABEL MAINTAINER "Amit Pal <[email protected]>"
ENV GOPATH /go
WORKDIR /go/src
COPY . /go/src/gothamcity
RUN cd /go/src/gothamcity && go build .

FROM alpine
RUN apk update && apk add ca-certificates && rm -rf /var/cache/apk*
WORKDIR /app
COPY --from=build-env /go/src/gothamcity/gothamcity /app

EXPOSE 8080

ENTRYPOINT [ "./gothamcity" ]

I ran the following command to build and run the docker image:

docker build -t gcr.io/${PROJECT_ID}/gothamcity:v1.0 .
docker run -ti gcr.io/miles-ee458/gothamcity:v1.0   

I got the error:

2021/01/28 14:34:46 Error loading .env file

What am I doing wrong here? How can I pass the .env file to docker image and execute it?

Also, isn't COPY . /go/src/gothamcity copy the entire project to docker image?

question from:https://stackoverflow.com/questions/65939284/how-to-pass-env-file-to-docker-image-in-a-go-project

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

COPY . /go/src/gothamcity only copies .env to build container. You have to explicitly copy it to your main container like this:

FROM golang:alpine AS build-env
LABEL MAINTAINER "Amit Pal <[email protected]>"
ENV GOPATH /go
WORKDIR /go/src
COPY . /go/src/gothamcity
RUN cd /go/src/gothamcity && go build .

FROM alpine
RUN apk update && apk add ca-certificates && rm -rf /var/cache/apk*
WORKDIR /app
COPY --from=build-env /go/src/gothamcity/gothamcity /app
COPY .env /app

EXPOSE 8080

ENTRYPOINT [ "./gothamcity" ]

Reason is that when you are saying "FROM alpine" this becomes a brand new blank container. That's how multi-stage builds are working.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...