Total Pageviews

Sunday 31 October 2021

Earthly, 一个更加强大的docker镜像构建工具

 from https://mp.weixin.qq.com/s/fDhulnfR5O_xwkodDOY8bg

一、Earthly 介绍

Earthly 是一个更加高级的 Docker 镜像构建工具,Earthly 通过自己定义的 Earthfile 来代替传统的 Dockerfile 完成镜像构建;Earthfile 就如同 Earthly 官方所描述:

Makefile + Dockerfile = Earthfile

在使用 Earthly 进行构建镜像时目前强依赖于 buildkit,Earthly 通过 buildkit 支持了一些 Dockerfile  的扩展语法,同时将 Dockerfile 与 Makefile 整合,使得多平台构建和代码化 Dockerfile 变得更加简单;使用  Earthly 可以更加方便的完成 Dockerfile 的代码复用以及更加友好的 CI 自动集成。

二、快速开始

2.1、安装依赖

Earthly 目前依赖于 Docker 和 Git,所以安装 Earthly 前请确保机器已经安装了 Docker 和 Git。

2.2、安装 Earthly

Earthly 采用 Go 编写,所以主要就一个二进制文件,Linux 下安装可以直接参考官方的安装脚本:

$ sudo /bin/sh -c 'wget https://github.com/earthly/earthly/releases/latest/download/earthly-linux-amd64 -O /usr/local/bin/earthly && chmod +x /usr/local/bin/earthly && /usr/local/bin/earthly bootstrap --with-autocomplete'

安装完成后 Earthly 将会启动一个 buildkitd 容器: earthly-buildkitd

2.3、语法高亮

目前 Earthly 官方支持 VS Code、VIM 以及 Sublime Text 三种编辑器的语法高亮,具体如何安装请参考 官方文档[1]

2.4、基本使用

本示例源于官方 Basic 教程,以下示例以编译 Go 项目为样例:

首先创建一个任意名称的目录,目录中存在项目源码文件以及一个 Earthfile 文件;

main.go

package main

import "fmt"

func main() {
    fmt.Println("hello world")
}

Earthfile

FROM golang:1.17-alpine
WORKDIR /go-example

build:
    COPY main.go .
    RUN go build -o build/go-example main.go
    SAVE ARTIFACT build/go-example /go-example AS LOCAL build/go-example

docker:
    COPY +build/go-example .
    ENTRYPOINT ["/go-example/go-example"]
    SAVE IMAGE go-example:latest

有了 Earthfile 以后我们就可以使用 Earthly 将其打包为镜像;

# 目录结构
~/t/earthlytest ❯❯❯ tree
.
├── Earthfile
└── main.go

0 directories, 2 files

# 通过 earthly 进行构建
~/t/earthlytest ❯❯❯ earthly +docker

构建完成后我们就可以直接从 docker 的 images 列表中查看刚刚构建的镜像,并运行:


三、进阶使用

3.1、多阶段构建

Earthfile 中包含类似 Makefile 一样的 target,不同的 target 之间还可以通过特定语法进行引用,每个 target 都可以被单独执行,执行过程中 earthly 会自动解析这些依赖关系。

这种多阶段构建时语法很弹性,我们可以在每个阶段运行独立的命令以及使用不同的基础镜像;从快速开始中可以看到,我们始终使用了一个基础镜像(golang:1.17-alpine),对于 Go 这种编译后自带运行时不依赖其语言 SDK 的应用,我们事实上可以将 “发布物” 仅放在简单的运行时系统镜像内,从而减少最终镜像体积:

由于使用了多个 target,所以我们可以单独的运行 build 这个 target 来验证我们的编译流程,这种多 target 的设计方便我们构建应用时对编译、打包步骤的细化拆分,同时也方便我们进行单独的验证。 例如我们单独执行 build 这个 target 来验证我们的编译流程是否正确:


在其他阶段验证完成后,我们可以直接运行最终的 target,earthly 会自动识别到这种依赖关系从而自动运行其依赖的 target:

引用链接  https://docs.earthly.dev/docs/guides

[1]

官方文档: https://earthly.dev/get-earthly

[2]

官方文档: https://docs.earthly.dev/docs/guides/auth

[3]

Earthfile reference: https://docs.earthly.dev/docs/earthfile

[4]

autobuild: https://github.com/mritd/autobuild

[5]

udcs: https://github.com/mritd/autobuild/tree/main/earthfiles/udcs

[6]































































































































































No comments:

Post a Comment