制作超简单的go docker镜像

Posted by KingXt on October 20, 2018

制作超简单的go docker镜像

准备如下非常简单的一个http服务,假设这个文件名字叫做firstimage.go,内容如下:

package main

import (
	"fmt"
	"log"
	"net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "hellow world\n")
}

func main() {
	http.HandleFunc("/", helloHandler)
	log.Println("starting server")
	http.ListenAndServe(":8080", nil)
}

为了做一个最简单的go镜像,我们在本地(我机器是是macos环境)将这个go程序编译成linux可运行的可执行程序 CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build firstimage.go

在同一个目录下面建一个Dockerfile文件,名称就叫做Dockerfile,Dockerfile里面内容如下:

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

我们知道Dockerfile文件必须以FROM开头,这里第一行FROM scratch是一个空操作,也就是说它不会再单独占一层。下一步制作镜像:

➜  firstimage docker build -t firstimage .                                
Sending build context to Docker daemon   6.57MB
Step 1/3 : FROM scratch
 ---> 
Step 2/3 : ADD firstimage /
 ---> 83b61f08103d
Step 3/3 : CMD ["/firstimage"]
 ---> Running in c080dba7ca86
Removing intermediate container c080dba7ca86
 ---> c7c2d5ffa9f5
Successfully built c7c2d5ffa9f5
Successfully tagged firstimage:latest

查看镜像

➜  firstimage docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
firstimage          latest              c7c2d5ffa9f5        6 seconds ago       6.57MB

运行镜像

➜  firstimage docker run --name firstimage -p 8080:8080 -d firstimage
d11db43bef15fcede0c43b4b266de7f6316dac4e1a5d84f8ac35d9eccff7eec2

最后在浏览器中输入 http://localhost:8080,你将看到hellow world。