登录
首页 >  Golang >  Go问答

Go Webapp 的 Dockerfile 目录结构

来源:stackoverflow

时间:2024-04-03 22:33:36 265浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《Go Webapp 的 Dockerfile 目录结构》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我正在用 go 开发一个测试 hello 应用程序,它将可以访问 postgres db。这将使用有状态集在 kubernetes 中发布,并有一个 pod 和两个容器镜像(一个用于 pgsql,一个用于 goapp)。

├── hello-app
|   ├── templates
|       ├── file1.gohtml
|       ├── file2.gohtml
|       └── file3.gohtml
|   ├── dockerfile
|   └── hello-app.go
├── psql
|   ├── dockerfile
|   ├── createuser.sh
|   └── createdb.sql
├── yaml
|   └── statefulset.yaml

我无法将 dockerfile 和 go 应用程序结合起来。在我的第一段 go 代码中,我使用“template.must”函数来引用“templates”目录。显然,当我将其作为容器运行时,目录结构是不同的。

我还没有完全弄清楚如何在 dockerfile 中执行此操作,并且正在寻找一些指导。

/app/hello-app.go

package main

import (

        "database/sql"
        "fmt"
        "os"
        _ "github.com/lib/pq"
        "html/template"
        "net/http"
        "strconv"
)

var db *sql.db
var tpl *template.template

func init() {
        host := os.getenv("variable")
        var err error
        db, err = sql.open("postgres", "postgres://user:password@"+host+"/dbname?sslmode=disable")
        if err != nil {
                panic(err)
        }

        if err = db.ping(); err != nil {
                panic(err)
        }
        fmt.println("you connected to your database.")

        tpl = template.must(template.parseglob("templates/*.gohtml"))

/app/dockerfile

FROM golang:1.8-alpine
RUN apk add --update go git
RUN go get github.com/lib/pq/...
ADD . /go/src/hello-app
RUN go install hello-app
Add templates templates/
ENV USER=username \
    PASSWORD=password \
    DB=dbname \
    HOST=hostname \
    PORT=5432

FROM alpine:latest
COPY --from=0 /go/bin/hello-app/ .
ENV PORT 4040
CMD ["./hello-app"]

当我在 kubernetes (gcp) 中运行它时,我在 hello-app 容器上收到以下日志条目。

恐慌:html/template:模式不匹配文件:templates/*.gohtml goroutine 1 [运行]: html/template.must


解决方案


在 dockerfile 的第二阶段,您仅复制前一阶段的 go 二进制文件。您还必须将 templates 目录复制到第二阶段,以便 go 二进制文件可以引用您的 html 模板:

from golang:1.8-alpine
run apk add --update go git
run go get github.com/lib/pq/...
add . /go/src/hello-app
run go install hello-app
env user=username \
    password=password \
    db=dbname \
    host=hostname \
    port=5432

from alpine:latest
copy --from=0 /go/bin/hello-app/ .
copy --from=0 /go/src/hello-app/templates ./templates
env port 4040
cmd ["./hello-app"]

我不确定这是否是常见的做法,但是当我对构建过程中哪个文件夹中的内容感到困惑时,我只需 ls 相关目录即可更好地了解构建过程中可能发生的情况构建过程:

RUN ls

显然,一旦完成 dockerfile,您就可以删除这些行。

该错误是因为 template.parseglob 在模板目录中找不到任何匹配的文件。尝试使用 copy 复制整个目录,而不是 copy --from=0 /go/bin/hello-app/ .。此外,当您构建应用程序时,您的模板文件夹仍将位于源文件夹中,因此这也可能导致问题。解决方案是在应用程序目录中运行 go buildin 并使用我拥有的 copy 命令。

理论要掌握,实操不能落!以上关于《Go Webapp 的 Dockerfile 目录结构》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>