go和docker打造最小docker image

1. 生成go的binary

go 1.7.3中生成的程序是full static的方式,对于其他的so库没有依赖

# go version
go version go1.7.3 linux/amd64

在go src路径下新建hello目录,在目录下创建hello.go

package main

import "fmt"

func main() {
    fmt.Printf("hello, world\n")
}

生成go的可执行程序

# go build 
# file hello
hello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped

# ldd hello
not a dynamic executable

# ls hello
-rwxr-xr-x. 1 root root 1.6M Nov  4 14:39 hello

2. 创建最小镜像

docker version
Client:
 Version:         1.10.3
 API version:     1.22
 Package version: docker-common-1.10.3-44.el7.centos.x86_64
 Go version:      go1.4.2
 Git commit:      9419b24-unsupported
 Built:           Fri Jun 24 12:09:49 2016
 OS/Arch:         linux/amd64

Server:
 Version:         1.10.3
 API version:     1.22
 Package version: docker-common-1.10.3-44.el7.centos.x86_64
 Go version:      go1.4.2
 Git commit:      9419b24-unsupported
 Built:           Fri Jun 24 12:09:49 2016
 OS/Arch:         linux/amd64

2.1 创建 scratch 镜像

官方地址参考:https://hub.docker.com/r/_/scratch/
scratch见:https://docs.docker.com/engine/userguide/eng-image/baseimages/

scratch images是docker保留的,

While scratch appears in Docker’s repository on the hub, you can’t pull it, run it, or tag any image with the name scratch. Instead, you can refer to it in your Dockerfile. For example, to create a minimal container using scratch:

不过可以用显示的命令来创建它,docker file中 From scratch可以不需要显示创建出来scatch

tar cv --files-from /dev/null | docker import - scratch
#docker images
REPOSITORY                            TAG                 IMAGE ID            CREATED             SIZE
scratch                               latest              20fb683d987a        37 minutes ago      0 B

2.2 构建go hello image

# more Dockerfile
FROM scratch
ADD hello /hello
CMD ["/hello"]
#docker build -t go_docker ./
# docker images
REPOSITORY                            TAG                 IMAGE ID            CREATED             SIZE
go_docker                             latest              d32a46a2438b        37 minutes ago      1.642 MB
scratch                               latest              20fb683d987a        37 minutes ago      0 B

2.3 运行image镜像

#docker run --rm go_docker
WARNING: IPv4 forwarding is disabled. Networking will not work.
hello, world

2.4 存出镜像

# docker save -o go_docker.tar go_docker:latest

2.5 载入镜像

# docker load < go_docker.tar

然后使用docker run在mac上成功运行。

发表评论

电子邮件地址不会被公开。 必填项已用*标注