使用 Docker 容器部署 Golang Web 应用程序静态文件

Deploying Golang web app static files with Docker container

我正在开发一个包含一些静态文件(配置和 html 模板)的小型 Web 应用程序:

├── Dockerfile
├── manifest.json
├── session
│   ├── config.go
│   ├── handlers.go
│   └── restapi_client.go
├── templates
│   ├── header.tmpl
│   └── index.tmpl
└── webserver.go

例如,代码中的模板是通过本地路径发现的(这是一个好习惯吗?):

func init() {
    templates = template.Must(template.ParseGlob("templates/*.tmpl"))
}

Docker 容器用于应用部署。正如你在Dockerfile中看到的那样,我必须复制/go/bin目录中的所有静态文件:

FROM golang:latest

ENV PORT=8000

ADD . /go/src/webserver/
RUN go install webserver
RUN go get webserver

# Copy static files
RUN cp -r /go/src/webserver/templates /go/bin/templates
RUN cp -r /go/src/webserver/manifest.json /go/bin/manifest.json

EXPOSE $PORT
ENTRYPOINT cd /go/bin && PORT=$PORT REDIRECT=mailtest-1.dev.search.km /go/bin/webserver -manifest=manifest.json

我认为这个变通办法应该被认为是不正确的,因为它违反了标准 Linux 约定(可执行文件和各种数据文件的单独存储)。如果有人也使用 Docker 进行 Golang web 应用程序部署,请分享您的经验:

由于您将相对路径名传递给 template.ParseGlob,它将查找与当前工作目录相关的模板,您在 ENTRYPOINT 中将其设置为 /go/bin

我建议修改您的 Dockerfile 以使用 WORKDIR 指令将工作目录设置为 /go/src/webserver,这样就无需将文件复制到 /go/bin ,例如:

FROM golang:latest
ADD . /go/src/webserver
WORKDIR /go/src/webserver
RUN go get
RUN go install
ENV PORT=8000
ENV REDIRECT=mailtest-1.dev.search.km
EXPOSE 8000
ENTRYPOINT /go/bin/webserver -manifest=manifest.json

您还可以考虑使用 Flynn to deploy and manage your application (see here 部署 Go 网络应用程序的演练)。