一、 golang:latest 基礎(chǔ)鏡像
mkdir gotest touch main.go touch Dockerfile
示例代碼:
package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { fmt.Fprint(writer, "Hello World") }) fmt.Println("3000!!") log.Fatal(http.ListenAndServe(":3000", nil)) }
Dockerfile配置
#源鏡像 FROM golang:latest #設(shè)置工作目錄 WORKDIR $GOPATH/src/github.com/gotest #將服務(wù)器的go工程代碼加入到docker容器中 ADD . $GOPATH/src/github.com/gotest #go構(gòu)建可執(zhí)行文件 RUN go build . #暴露端口 EXPOSE 3000 #最終運(yùn)行docker的命令 ENTRYPOINT ["./gotest"]
打包鏡像
docker build -t gotest .
golang:latest 編譯過程,其實(shí)就是在容器內(nèi),構(gòu)建了一個(gè)go開發(fā)環(huán)境這種源鏡像打包大概800M左右,比較大。
二、 alpine:latest 基礎(chǔ)鏡像
-
使用此鏡像大概過程就是,在linux機(jī)器,先把go程序打包成二進(jìn)制文件,再丟到apine環(huán)境,執(zhí)行編譯好的文件。
-
默認(rèn)情況下,Go的runtime環(huán)境變量CGO_ENABLED=1,即默認(rèn)開始cgo,允許你在Go代碼中調(diào)用C代碼。通過設(shè)置CGO_ENABLED=0就禁用CGO了。所以需要執(zhí)行:CGO_ENABLED=0 go build .即可。
-
此基礎(chǔ)鏡像打包只有13M,特別小。
#源鏡像 FROM alpine:latest #設(shè)置工作目錄 WORKDIR $GOPATH/src/github.com/common #將服務(wù)器的go工程代碼加入到docker容器中 ADD . $GOPATH/src/github.com/common #暴露端口 EXPOSE 3002 #最終運(yùn)行docker的命令 ENTRYPOINT ["./common"]
打包鏡像:
docker build -t common .
推薦教程:docker