创建最小的运行Go程序的Image

go 刘宇帅 5年前 阅读量: 937

我们首先编写一个简单的Golang服务

package main

import "net/http"

func main() {

    http.HandleFunc("/", hello)
    http.ListenAndServe(":8001", nil)
}

func hello(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello world!"))
}

运行服务

$ go run main.go

访问 http://127.0.0.1:8001 页面返回

Hello world!

构建运行Go服务的最小Image

首先构建Go服务,由于服务中使用了net包,而net包含cgo代码,如果不设置CGO_ENABLED为0,则构建出来的程序是会依赖动态连接库的,并且由于我们的image是基于空白的scratch制作的,则会导致go服务无法正常运行。

$ CGO_ENABLED=0 GOOS=linux go build -a -ldflags '-extldflags "-static"'

写dockerfile文件

FROM scratch
ADD main /
CMD ["/main"]

构建image并起一个容器

$ docker build -t go-server .
$ docker run -d -p 8001:8001 go-server

我们访问http://127.0.0.1:8001即可看到相应的服务返回。
我们查看下生成的Image,可以看到大小只有6.5MB。

$ docker image ls
REPOSITORY                                      TAG                 IMAGE ID            CREATED             SIZE
go-server                                       latest              7d63403e13fc        6 minutes ago       6.47MB

提示

功能待开通!


暂无评论~