英文:
Golang parsefiles not working when run in a docker setup in kubernetes
问题
我有以下的目录结构:
templates/
a.tmpl
services/
service.go
main.go
现在在service.go
文件中,我调用了下面的函数:
dir, err := filepath.Abs(filepath.Dir("./templates/"))
if err != nil {
return nil, err
}
baseFile := filepath.Join(dir, "a.tmpl")
tmpl, err := template.New("base").ParseFiles(baseFile)
现在上述函数按预期解析了我的a.tmpl
文件。
但是一旦这个服务在Docker和Kubernetes上运行起来,我就无法打开这个文件,因为文件不存在。
为什么会这样?
更新:
FROM golang:1.16-buster AS builder
# 从主机复制代码并进行编译
WORKDIR $GOPATH/src/github.com/me/report
COPY . ./
# 将模板打包到二进制文件中
RUN CGO_ENABLED=0 GOOS=linux go build -mod vendor -ldflags "-X github.com/me/report/cmd.version=$(cat .VERSION)" -o /app .
FROM xyz.amazonaws.com/common/platform/base:latest as prod
COPY --from=builder /app ./
ADD ./migrations /migrations
ENTRYPOINT ["/app"]
英文:
I have the following directory structure:
templates/
a.tmpl
services/
service.go
main.go
Now inside the service.go
file i am calling the below function:
dir, err := filepath.Abs(filepath.Dir("./templates/"))
if err != nil {
return nil, err
}
baseFile := filepath.Join(dir, "a.tmpl")
tmpl, err := template.New("base").ParseFiles(baseFile)
now the above function is parsing my a.tmpl
file as expected.
but once this service is up on docker and kubernetes, i am no longer able to open the file since the file does not exists
why is that?
UPDATE:
FROM golang:1.16-buster AS builder
# Copy the code from the host and compile it
WORKDIR $GOPATH/src/github.com/me/report
COPY . ./
# pack templates to binary
RUN CGO_ENABLED=0 GOOS=linux go build -mod vendor -ldflags "-X github.com/me/report/cmd.version=$(cat .VERSION)" -o /app .
FROM xyz.amazonaws.com/common/platform/base:latest as prod
COPY --from=builder /app ./
ADD ./migrations /migrations
ENTRYPOINT ["/app"]
答案1
得分: 3
当你构建二进制文件时,go只包含必要的go文件以使程序正常工作。它不知道你的templates
目录对程序的运行是必要的。
有几种解决方案可以解决你的问题:
- 创建一个指向模板所在位置的环境变量,并在运行时使用它。
- 使用embed包将
templates
目录嵌入到二进制文件中,以便在运行时访问文件。
英文:
When you build your binary, go only includes the necessary go files to have your program work. It does not know that your templates
directory is necessary to the running of the program.
There is several solutions to your problem :
- Create an environment variable pointing to were the templates are and use it on runtime.
- Embed the
templates
directory into your binary using the embed package so that you can access the files at runtime
答案2
得分: 3
只需从构建器中复制templates文件夹,例如:
COPY --from=builder /app ./
ADD ./migrations /migrations
COPY --from=builder ./templates /templates
或者像这样添加文件夹:
COPY --from=builder /app ./
ADD ./migrations /migrations
ADD ./templates /templates
英文:
Just copy the templates folder from the builder, like:
COPY --from=builder /app ./
ADD ./migrations /migrations
COPY --from=builder ./templates /templates
or add the folder like:
COPY --from=builder /app ./
ADD ./migrations /migrations
ADD ./templates /templates
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论