Gradle in CI and Docker
A build that a developer runs with ./gradlew build is a build a pipeline runs with the same command. Two files make the difference: a workflow that keeps the caches between runs, and a Dockerfile that builds in one stage and ships in another. Neither runs here, and the lesson says so at every step.
A CI workflow
.github/workflows/build.yml
name: build
on:
push:
branches: [main]
pull_request:
jobs:
gradle:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v4
- run: ./gradlew build --console=plain
Three steps do the work. checkout brings the sources and the wrapper. setup-java installs the JDK the build compiles with, which is why the version belongs in the workflow and in the toolchain block of the build. setup-gradle adds a Gradle Enterprise cache and the annotation of failing tests; a job without it still builds, only slower.
The command carries no --offline: a CI machine has a network and fills the caches from the repositories of the build. It does carry --console=plain, because a coloured log of a runner is unreadable.
./gradlew build --console=plain
A Dockerfile
Dockerfile
FROM eclipse-temurin:21-jdk AS build
WORKDIR /src
COPY gradlew settings.gradle build.gradle ./
COPY gradle ./gradle
RUN ./gradlew dependencies --console=plain
COPY src ./src
RUN ./gradlew build --console=plain -x test
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=build /src/build/libs/*.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
Two stages, and one line in the middle that matters: the build files are copied before the sources, and a run of dependencies fills the cache of the image layer. A change to a source file then rebuilds from the COPY src line, not from the download of every jar.
The -x test on the build line is a decision, not a default: a pipeline that already ran the tests does not need them inside the image, and a test that needs a database would fail there.
docker build -t shop .
=> [build 6/7] RUN ./gradlew build --console=plain -x test
What is not run here
No part of this lesson was executed in this container. A workflow needs a runner, a Dockerfile needs a Docker daemon, and this image has neither; both files are shown whole so that a reader can copy them into a repository. The two commands carry the norun mark of the checker, which counts them and never pretends they produced output.
The one thing the lesson does prove is the command inside them: ./gradlew build is the command of the first project and of every chapter after it.
Related
- The Gradle Wrapper: the four files the first line of the workflow needs.
- The daemon and faster builds: the properties a CI job sets for speed.
- Jenkins: another runner, with the Maven pipeline of the other course.
Автор статьи: Arthur Isaev