本示例基于golang iris的Hello World,静态编译,基于空白镜像scratch,解决了时区问题
创建一个webserver项目
go mod init webserver
main.go
package main
import (
"time"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
"github.com/kataras/iris/v12/middleware/logger"
"github.com/kataras/iris/v12/middleware/recover"
)
func newApp() *iris.Application {
app := iris.New()
app.Use(recover.New())
app.Use(logger.New())
mvc.New(app).Handle(new(ExampleController))
return app
}
func main() {
app := newApp()
app.Listen(":8080")
}
type ExampleController struct{}
func (c *ExampleController) Get() mvc.Result {
return mvc.Response{
ContentType: "text/html",
Text: "当前时间:" + time.Now().Format("2006-01-02 15:04:05"),
}
}
func (c *ExampleController) GetPing() string {
return "pong"
}
func (c *ExampleController) GetHello() interface{} {
return map[string]string{"message": "Hello Iris!"}
}
func (c *ExampleController) BeforeActivation(b mvc.BeforeActivation) {
anyMiddlewareHere := func(ctx iris.Context) {
ctx.Application().Logger().Warnf("Inside /custom_path")
ctx.Next()
}
b.Handle("GET", "/custom_path", "CustomHandlerWithoutFollowingTheNamingGuide", anyMiddlewareHere)
}
func (c *ExampleController) CustomHandlerWithoutFollowingTheNamingGuide() string {
return "hello from the custom handler without following the naming guide"
}
构建
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags -s -a -installsuffix cgo main.go
Dockerfile
FROM scratch
ENV TZ=Asia/Shanghai
ADD zoneinfo.tar.gz /
COPY main /
EXPOSE 8080
CMD ["/main"]
打包本地时区
tar -chzf zoneinfo.tar.gz /usr/share/zoneinfo
构建镜像
docker build -t webserver ./webserver
运行容器
docker run --name webserver -p 8080:8080 -d webserver
有疑问加站长微信联系(非本文作者)