iTranslated by AI
Introducing Earthly: The "Just Right" Build Tool
Introduction to Earthly: The "Just Right" Build Tool
Build tools have been used from the old days to the present, with famous examples being Make, Gradle (common in Java and Kotlin), and Bazel (the OSS version of what was used at Google). While there are various other build tools, I would like to introduce Earthly, a tool that has recently caught my attention despite its relatively low name recognition.
First, let me briefly introduce the characteristics of Earthly by comparing it with other build tools like Bazel and Gradle.
Dockerfile + Makefile-style DSL
Almost every build tool requires writing build configurations in its own DSL, but Earthly uses a DSL that feels like a combination of a Dockerfile and a Makefile. Compared to other build tools, I think it is quite easy to understand. I will discuss this DSL in more detail later, but you can get a feel for it from this sample code.
Language-Agnostic
Unlike Gradle, which is a build tool specialized for specific languages (mainly JVM languages), Earthly can be used for builds in any language, similar to Bazel or Docker builds.
Builds Run Inside Containers
By building inside a container, the build process takes place in a safe environment isolated from the host machine. This is a feature not found in Bazel or Gradle.
Build Cache Concept is Simple and Similar to Docker
The build cache basically follows the same logic as Docker builds, so you can directly apply your knowledge of Dockerfile best practices, such as the importance of command order. In Bazel or Gradle, understanding the DSL syntax and options is necessary to make the build cache work correctly[1], but Earthly's build cache is a relatively straightforward concept.
What is Most Important for Speeding Up Builds?
Before a detailed introduction to Earthly itself, I would like to explain what is important for achieving "fast builds."
The features required of a build tool can be broadly categorized into these three:
- Build script writing experience
- Build speed
- Build reproducibility
Among these, build speed is probably the factor most people look for. So, what is important for speeding up builds? Actually, build reproducibility is the most important.
Build Cache and Reproducibility
The first way that comes to mind for speeding up builds is simply increasing machine specs, but there is a more effective method. That is not building at all.
It sounds like a riddle, but the reason increasing machine specs speeds up builds is because you are performing tasks that require machine power, such as compilation. If you can complete a build without using machine power in the first place, that should be the fastest. This is what a build cache realizes.
Generally, a build cache saves the results of a previous build in memory or a file and uses those results for the next build instead of repeating the same work. If the source files are edited, a rebuild is naturally required without using the cache, but as long as the files are not edited, using the cache allows the build itself to finish in an instant.
On the other hand, many people have likely experienced running make clean or gradle clean after encountering mysterious behavior caused by the build cache. This happens because build results are not identical despite using the same build scripts and machines—in other words, the build reproducibility is low.
However, this is inherently strange; programs only move as they are written, so if the programs are identical, they should behave exactly the same. Applying this to builds, if the "inputs" such as the files used for the build are the same, the "output" build results should also be the same. This is the logic that allows us to use a build cache.
For more details, you may find these helpful: an article I wrote in the past explaining how Bazel works, and the explanation of inputs and outputs in the Gradle documentation regarding incremental builds.
Factors Inhibiting Reproducibility
The most obvious reasons why build results change even with the same build script are environment variables and differences in installed tool versions. It is unlikely that these two will match perfectly between your machine and a colleague's machine. Especially regarding tools, since everyone installs various things for development work other than the build process, a completely identical environment is almost impossible.
To address this problem, Bazel handles it by, in principle, installing all tools used for the build specifically for Bazel. Not only versions but even sha256 hashes are strictly specified.
Gradle is generally more relaxed compared to Bazel; for example, it will use a JDK if one is already installed. However, if necessary, it is also possible to operate strictly by explicitly downloading a specific version of a JDK provided by various vendors.
The Solution: Building Inside Containers
Looking at Bazel's approach, increasing build reproducibility boils down to how well you can isolate the build environment from the host machine running the build. Bazel achieves this isolation through a mechanism called sandboxing, whereas Earthly achieves isolation from the host machine by executing the build inside a container.
One of the benefits of containers is that they can be run as environments isolated from the host machine. I felt that the technical choice to use widely-used containers, rather than creating a proprietary mechanism like Bazel, was a sound approach.
Earthly's Features
Up to this point, I have explained the important elements of builds before introducing Earthly. Now, I will finally introduce Earthly's features.
Easy-to-understand Build Scripts Like Makefile or Dockerfile
First, I will show you a sample Earthly build script from the official documentation.
VERSION 0.6
FROM golang:1.15-alpine3.13
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
From https://docs.earthly.dev/basics/part-1-a-simple-earthfile.
It is a DSL that feels like a combination of a Makefile and a Dockerfile. Since commands are basically executed from top to bottom, it should be much easier to understand compared to Bazel or Gradle. Even if it is your first time seeing it, you can probably get the gist of it if you are familiar with Dockerfiles.
Build tools have two different philosophies: task-based and artifact-based. The linked Bazel documentation has more details, but here is a brief explanation of each.
Task-based (shell script, Dockerfile)
- Describes the steps (How) required for the build.
- Easy to understand because you can see which commands are executed in what order by reading from top to bottom.
- If there are artifacts that depend on other artifacts, you must explicitly state the order to build correctly.
- Example: To build artifact C, if A and B are required, you must specify that they are built in the order (A, B) -> C.
- In reality, tools like Make, Gradle, and Dockerfile have features where you describe that C depends on A and B, and the tool automatically determines the build order.
Artifact-based (Bazel)
- Describes what (What) to build.
- Details are hard to understand because the build tool determines which commands are executed in what order.
- Instead of build steps, you must explicitly state all dependencies required to generate the artifact.
- Example: To build artifact C, you explicitly state that A and B are required.
- Since the build tool understands all dependencies, it can calculate the build steps backward from the final artifact. This makes it easier for the tool to perform optimizations, such as parallel builds where possible.
While Dockerfiles and Earthly are task-based, Bazel is artifact-based. Bazel's build scripts might be difficult to understand at first glance, but that is because the underlying philosophy is completely different. Although Bazel's documentation describes Gradle as task-based, I personally think Gradle is a build tool that combines both philosophies.
Language-Agnostic
Earthly is a language-agnostic build tool, so it can be used for builds in any language. Similar to a Dockerfile, you can perform builds for most languages by specifying a container for the target language in the FROM instruction.
On the other hand, it does not provide special support from the build tool side, such as project structure analysis like Gradle (which excels at JVM languages) or Turborepo (which excels at monorepo Node.js configurations). Therefore, Earthly's position is not to replace build tools specialized for specific languages.
Instead, the common approach is to coexist by using these language-specific build tools within an Earthly build.
Can Directly Output Container Images
Since Earthly can handle builds for any language, it doesn't have strengths or weaknesses for specific languages, but it can be said to be a build tool that excels at outputting container images. For example, below is an example of an Earthfile for building a Node.js app. The final SAVE IMAGE multistage_nodejs:latest allows you to save the state of the container at that point as an image, just like docker build.
Also, by splitting the build into stages like build and prod as in this example, it is possible to create a lightweight image (prod) where only the minimum required packages are installed, similar to a multi-stage Dockerfile build.
VERSION 0.6
FROM node:16
build:
COPY package.json package-lock.json .
RUN npm ci
COPY . .
RUN npm run build
SAVE ARTIFACT dist
prod:
FROM node:16-alpine
WORKDIR /app
COPY package.json package-lock.json .
RUN npm ci --production && rm -rf ~/.npm
COPY +build/dist ./dist
ENTRYPOINT ["npm", "run", "start"]
SAVE IMAGE multistage_nodejs:latest # The image at this point is saved
Can Export Files to Local
This is an advantage over Dockerfiles. While I mentioned that Earthly performs builds inside containers, if that were all, it would be the same as a standard docker build. Earthly's convenience lies in its unique SAVE ARTIFACT feature, which allows files generated inside the container to be easily exported to the host side.
For example, to compile TypeScript files into JS within Earthly and export them to the host side, you simply add AS LOCAL to SAVE ARTIFACT.
VERSION 0.6
FROM node:16
build:
COPY package.json package-lock.json .
RUN npm ci
COPY . .
RUN npm run build
SAVE ARTIFACT AS LOCAL dist # Also output to the dist directory on the host side
Convenient for Code Generation Tasks
One convenient use case for this feature is code generation tasks. You might prepare a Makefile to generate code from some DSL, but the commands executed from the Makefile usually need to be installed by each user via tools like Homebrew. With Earthly, everything—including the installation of necessary tools—is described in the Earthfile, so there's no need to worry about differences in tool versions or operating systems[2].
As an example, in my tool called CIAnalyzer, I use Earthly to generate TypeScript type definition files and BigQuery schema JSON from proto files. It was difficult to set up the environment every time the development machine or CI environment changed because it required installing protoc and setting up plugins for TypeScript and BigQuery. However, since migrating to Earthly, I can now generate files in any environment using just the command earthly +proto.
Easy-to-understand Cache Concepts
As mentioned earlier, the use of caching is indispensable for achieving high-speed builds, and it's no exaggeration to say that whether or not you can utilize the cache determines the build speed.
The caching mechanism is often hidden by build tools to keep users from having to worry about it, and a deep understanding of the build tool itself is often required to determine why a cache was hit or missed.
On the other hand, the Dockerfile realized this build cache in a way that is relatively easy for everyone to understand. Most people likely already understand the simple cache model where commands following a line that has changed since the previous execution are re-executed.
Earthly's cache is almost the same as this Dockerfile cache. If you change the Earthfile, the cache remains effective up to the same command as the previous execution, and only the commands after the changed part are actually executed.
If you perform a second build using the previous Node.js Earthfile without changing anything, it will look like this, where everything becomes cached and the build completes instantly.
node:16 | --> Load metadata linux/amd64
context | --> local context .
+base | --> FROM node:16
context | --> local context .
+base | [ ] 0% resolve docker.io/library/node:16@sha256:59eb4e9d6a344ae1161e7d6d8af831cb50713cc631889a5a8c2d438d6ec6aa0f [██████████] 100% resolve docker.io/library/node:16@sha256:59eb4e9d6a344ae1161e7d6d8af831cb50713cc631889a5a8c2d438d6ec6aa0f
ongoing | context (5 seconds ago), context (5 seconds ago)
context | [ ] 0% transferring .:
context | [██████████] 100% transferring .:
context | transferred 1 file(s) for context . (1.0 MB, 15077 file/dir stats)
context | [██████████] 100% transferring .:
+build | *cached* --> COPY package.json package-lock.json .
+build | *cached* --> RUN npm ci
+build | *cached* --> COPY . .
+build | *cached* --> RUN npm run build
output | --> exporting output
This caching method might not be considered the best in terms of cache efficiency compared to Bazel or Gradle, but I value it because it prevents the build results from changing (breaking) due to caching, and most people already understand this cache model thanks to Dockerfiles.
Remote Cache
Generally, build caches are saved on the machine that executed the build, but there is a concept of sharing this over a network so that other machines can also use the cache.
Sharing the cache within a team via a remote cache can provide the following benefits:
Builds on the main branch complete faster
- Since the main branch is frequently executed on CI and by many developers, the cache is highly likely to be up to date.
- It is possible to complete builds simply by retrieving results from the cache.
Builds for local verification during pull request reviews become faster
- Since the build should have already been performed at least once in the environment of the person who created the pull request, using that cache allows the build to finish faster.
No need to set up caching mechanisms for CI
- Generally, you need to write code to save packages and build artifacts as cache using the features provided by each CI service.
- If the remote cache feature is built into the build tool itself, there's no need to write cache-specific code for every CI service.
Recent build tools often include remote cache features by default, which shows how useful they are considered to be. In other words, when evaluating a new build tool, a good point of comparison is whether it has a remote cache feature.
Bazel
Perhaps because Bazel originated as an open-source version of Google's internal tools, it has included remote cache functionality since at least version 0.10.0, according to the official documentation.
The cache server can be a standard HTTP server, such as one built with Nginx, or there are specialized OSS solutions for caching. While there aren't many managed cache services, being a Google product, it is possible to use GCS (Google Cloud Storage) directly as a cache server.
I have actually used GCS as a cache server back in the Bazel v3 era. If you are interested, please refer to the following article.
Gradle
It might not be very well known, but Gradle also has a remote cache feature.
Gradle provides a remote cache server in its paid Enterprise version and highlights in various parts of its documentation how this service can speed up builds.
Does this mean you can't use remote caching without a paid service? Not exactly. Since the interface for this remote cache plugin is public, several OSS plugins have been released that implement this interface to use S3 or GCS as cache servers. (In fact, there are so many forks that it's hard to tell which one to use.)
I have previously used a plugin called https://github.com/rpalcolea/gradle-gcs-build-cache to use GCS as a remote cache, and it worked fine. However, as of this writing, the last commit was in 2018, so it's uncertain if it's still maintained; it might be better to look for a different plugin today.
Emerging Node.js Build Tools
The Node.js build tool ecosystem, including Nx, Turborepo, and Rush, has seen remarkable development in recent years. Unfortunately, I haven't actually used these myself yet, so I will leave the explanation to external sites.
Based on my brief research, it seems that the developers of these tools often provide cache servers, such as Vercel for Turborepo and Azure for Rush. Like Gradle, this seems to be an area that is easy to monetize.
On the other hand, a Google search will reveal OSS for hosting your own cache server for each tool, or OSS that uses S3 as a cache server. When choosing which Node.js build tool to use, you might want to consider the level of support for cache servers provided by the developers or the community.
Earthly
Now, let me finally introduce the remote cache situation for Earthly. I explained earlier that caching in Earthly is almost the same as in docker build, and the same applies to remote caching. In fact, since it uses the same BuildKit under the hood, the remote cache functionality likely follows the same mechanism.
This is the documentation for remote caching. There are two remote cache methods, Inline cache and Explicit cache, and AWS ECR, Google Artifact Registry, and GitHub Container Registry are introduced as storage destinations. In other words, remote caching in Earthly involves pushing and pulling the aforementioned layer cache to and from some container registry.
In my understanding, inline and registry explained in docker buildx's --cache-to correspond to Earthly's inline and explicit, respectively. If you are familiar with buildx in recent versions of Docker, you can probably get the gist of it, but if not, please refer to the various buildx cache methods in this article.
Using a remote cache in Earthly is very simple, just like with Docker. It's enough to authenticate so that your CI environment and each person's local machine can push to and pull from the container registry of the cloud service your team uses most. Since these are almost Docker layers, the remote cache size tends to be large, so it's a good idea to use the same cloud service as your CI[3] or choose a nearby region.
As an example, for an OSS project where I use Earthly, I publish the final image on GHCR, and I also use GHCR for the remote cache. By performing docker login to GHCR and adding --push --max-remote-cache --remote-cache=ghcr.io/ORG/CACHE_IMAGE_NAME to Earthly's options, you can realize exporting to the remote cache during builds in CI.
Summary
Originally, I intended to introduce Earthly's various features more simply, but I felt that explaining Earthly's characteristics required explaining other build tools like Bazel and Gradle, as well as how build caching works. As a result, the explanation of Earthly itself ended up being only about half of the article. I will introduce detailed features at another time.
I feel that Earthly is a "just right" build tool that has more modern features than a Makefile, requires less learning cost than Bazel, and unlike Gradle, can be used for languages other than JVM languages. Above all, the DSL is almost identical to a Dockerfile, making it incredibly approachable.
Since it is still under active development, detailed features may be added or changed in the future, but I believe the fundamental parts I introduced this time will remain the same. If you are looking for a build tool with more features than a Makefile but feel Bazel is too high a hurdle, please give it a try.
-
That said, the build cache concepts in Bazel and Gradle are essential for efficient builds and are worth understanding. ↩︎
-
Since the container used for the build is specified, there's no need for conditional branching in the tool installation process to account for macOS/Linux, apt/yum, etc. ↩︎
-
A combination such as GHCR for GitHub Actions, ECR for AWS, or Artifact Registry for GCP. ↩︎
Discussion