You learn Jenkins by automating real projects, not by reading menus. That is why you will work on the same project throughout the entire course: TecnoShop's orders-api microservice. In this lesson you will get everything ready for the hands-on exercises: you will create the minimal (but real and working) code for orders-api, push it to your own GitHub repository and bring up the course's Jenkins controller with Docker Compose. By the end you will have an environment identical to the one used in the rest of the lessons, ready to create your first job in the next lesson.
The Course's Common Thread
TecnoShop is an online store that wants to leave behind the laptop builds and manual deployments you saw in What Is Jenkins?. Throughout the course you will step into the shoes of its team:
- Laura (platform/DevOps) administers Jenkins.
- Diego (backend) develops
orders-api. - Marta (QA) looks after quality and testing.
The projects you will automate:
| Project | Technology | When it appears |
|---|---|---|
orders-api |
Java 21, Spring Boot 3, Maven (./mvnw), JUnit 5 |
From this lesson onward |
catalog-web |
Node.js 20, npm, Jest | From module 4 onward |
In the course text we will refer to the repository as tecnoshop/orders-api, but you will create it in your own GitHub account (<your-username>/orders-api). Whenever you see tecnoshop/orders-api in an example, mentally replace it with your repository.
What You Will Build: An Overview of the Environment
flowchart LR
AL["You (student)<br/>local code"] -->|"git push"| GH["GitHub<br/>your-username/orders-api<br/>main branch"]
subgraph DK["Docker on your machine"]
JC["jenkins-controller<br/>jenkins/jenkins:lts-jdk21<br/>ports 8080 and 50000"]
V[("volume<br/>jenkins_home")]
JC --- V
end
AL -->|"browser<br/>localhost:8080"| JC
JC -->|"git clone"| GH
JC --> B["Build on the built-in node<br/>./mvnw -B verify"]
The flow is as follows: you write code on your machine and push it to GitHub; Jenkins, which runs in a Docker container on your own machine, fetches that code from GitHub and builds it. You control Jenkins from the browser at http://localhost:8080.
Tools You Need on Your Machine
| Tool | What for | How to check |
|---|---|---|
| Git | Managing the repository | git --version |
| Docker (Engine + Compose plugin, or Docker Desktop) | Running Jenkins | docker version and docker compose version |
| JDK 21 (recommended) | Building orders-api locally before pushing it |
java -version |
| GitHub account | Hosting your repository | — |
| Editor or IDE | Writing the code | — |
If you do not want to install the JDK on your machine, you will see further down how to build using a Docker container.
The orders-api Code
We are going to create a simplified version of orders-api: a REST service with two read endpoints and fictional in-memory data. It is deliberately small so that it builds in seconds, but it is a complete, real Spring Boot project.
Project Structure
orders-api/
├── .gitignore
├── .mvn/wrapper/maven-wrapper.properties (generated by the Maven Wrapper)
├── mvnw (generated by the Maven Wrapper)
├── mvnw.cmd (generated by the Maven Wrapper)
├── pom.xml
└── src/
├── main/
│ ├── java/com/tecnoshop/orders/
│ │ ├── OrdersApiApplication.java
│ │ ├── Order.java
│ │ └── OrderController.java
│ └── resources/
│ └── application.properties
└── test/
└── java/com/tecnoshop/orders/
└── OrderControllerTest.javaCreate the directory and the folder structure:
mkdir -p orders-api/src/main/java/com/tecnoshop/orders
mkdir -p orders-api/src/main/resources
mkdir -p orders-api/src/test/java/com/tecnoshop/orders
cd orders-apimkdir -p creates all the necessary intermediate directories in one go.
pom.xml
The pom.xml describes the project to Maven: its identity, its Java version and its dependencies.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.7</version>
<relativePath/>
</parent>
<groupId>com.tecnoshop</groupId>
<artifactId>orders-api</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>orders-api</name>
<description>TecnoShop order management REST microservice</description>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>What each part means:
<parent>: inherits the Spring Boot 3 configuration (mutually compatible dependency versions, UTF-8 encoding, plugin configuration). You can use any recent 3.x version; if Spring Initializr suggests a different one, that is fine.groupId,artifactId,version: identify the project. With these values, Maven will generate the filetarget/orders-api-1.0.0-SNAPSHOT.jar. TheSNAPSHOTsuffix denotes a version under development.<java.version>21</java.version>: compiles for Java 21.spring-boot-starter-web: includes Spring MVC and an embedded Tomcat server to expose the REST API.spring-boot-starter-actuator: adds operational endpoints, such as/actuator/health, which we will later use to verify deployments.spring-boot-starter-testwith<scope>test</scope>: includes JUnit 5, AssertJ, Mockito and Spring testing utilities. Thetestscope means it is only used when compiling and running tests; it is not packaged into the.jar.spring-boot-maven-plugin: turns the.jarinto a self-contained executable (java -jar ...).
OrdersApiApplication.java
Path: src/main/java/com/tecnoshop/orders/OrdersApiApplication.java
package com.tecnoshop.orders;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OrdersApiApplication {
public static void main(String[] args) {
SpringApplication.run(OrdersApiApplication.class, args);
}
}@SpringBootApplication: marks the main class. It enables Spring Boot's auto-configuration and scans for components (such as our controller) in this package and its subpackages.main: the entry point;SpringApplication.runstarts the application and the embedded web server.
Order.java
Path: src/main/java/com/tecnoshop/orders/Order.java
package com.tecnoshop.orders;
import java.math.BigDecimal;
public record Order(Long id, String customer, BigDecimal total, String status) {
}- A
recordis an immutable data class introduced in modern Java: with a single line, Java generates the constructor, the accessor methods (id(),customer()...),equals,hashCodeandtoString. - We use
BigDecimalfor the amount because thedoubleandfloattypes produce rounding errors with money. - Spring automatically converts each
Orderto JSON when the API returns it.
OrderController.java
Path: src/main/java/com/tecnoshop/orders/OrderController.java
package com.tecnoshop.orders;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/orders")
public class OrderController {
private static final List<Order> ORDERS = List.of(
new Order(1L, "Lucia Romero", new BigDecimal("59.90"), "SHIPPED"),
new Order(2L, "Pablo Ortega", new BigDecimal("124.50"), "PENDING"),
new Order(3L, "Elena Vidal", new BigDecimal("18.75"), "DELIVERED"));
@GetMapping
public List<Order> list() {
return ORDERS;
}
@GetMapping("/{id}")
public ResponseEntity<Order> get(@PathVariable Long id) {
return ORDERS.stream()
.filter(order -> order.id().equals(id))
.findFirst()
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
}@RestController: indicates that the class handles HTTP requests and that whatever its methods return is converted to JSON.@RequestMapping("/api/orders"): all the routes in this class hang off/api/orders.ORDERS: an immutable list with three fictional orders in memory. In a real service they would come from a database; here it is enough to have something to build and test.@GetMappingonlist(): responds toGET /api/orderswith the full list.@GetMapping("/{id}")onget(...): responds toGET /api/orders/{id}.@PathVariabletakes the{id}value from the URL.- The stream looks for the order with that
id. If it exists,ResponseEntity::okreturns it with HTTP status 200; if not,ResponseEntity.notFound().build()returns 404.
application.properties
Path: src/main/resources/application.properties
spring.application.name: the logical name of the application.server.port=8081: by default Spring Boot listens on 8080, but Jenkins will use that port on your machine. We move the application to 8081 so you can run both at the same time without conflicts.
OrderControllerTest.java
Path: src/test/java/com/tecnoshop/orders/OrderControllerTest.java
package com.tecnoshop.orders;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
class OrderControllerTest {
private final OrderController controller = new OrderController();
@Test
void listReturnsThreeOrders() {
assertEquals(3, controller.list().size());
}
@Test
void getExistingOrderReturns200() {
ResponseEntity<Order> response = controller.get(1L);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("Lucia Romero", response.getBody().customer());
}
@Test
void getMissingOrderReturns404() {
ResponseEntity<Order> response = controller.get(99L);
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
}
}- This is a unit test with JUnit 5: it creates an
OrderControllerdirectly without starting Spring, so it runs in milliseconds. @Testmarks each method as an independent test.assertEquals(expected, actual)makes the test fail if the values do not match. The first argument is always the expected value.- We check three behaviors: that there are three orders, that order 1 exists and belongs to "Lucia Romero", and that a nonexistent
idreturns 404.
This test class will play a starring role in the next lesson, when we deliberately cause a failure to see how Jenkins detects it.
.gitignore
Path: .gitignore (at the root of the project)
target/: Maven's output directory. It is never pushed to the repository: it is regenerated on every build.- The rest are configuration files for IDEs (IntelliJ IDEA, VS Code, Eclipse) and the operating system, which are not part of the project.
The Maven Wrapper and Local Verification
The Maven Wrapper is a small script (mvnw on Linux/macOS and mvnw.cmd on Windows) that is stored in the repository and automatically downloads the Maven version pinned for the project. Its advantages:
- Nobody needs to install Maven: not you, not your teammates, and not Jenkins.
- Everyone uses exactly the same Maven version.
Generating the Wrapper
You have two options:
Option A: with Maven installed. From the root of orders-api:
-N(non-recursive): runs the command only on the current project, without traversing submodules.wrapper:wrapper: runs thewrappergoal of the Maven Wrapper plugin, which generatesmvnw,mvnw.cmdand the.mvn/wrapper/directory with themaven-wrapper.propertiesfile (which specifies which Maven version to download).
Option B: with Spring Initializr. If you do not have Maven, generate an empty project at https://start.spring.io (Maven, Java 21, Spring Boot 3.x) and copy the mvnw and mvnw.cmd files and the .mvn/ directory into your project. Initializr projects already include the wrapper.
Verifying Locally
chmod +x mvnw: gives the script execute permission (on Linux/macOS it sometimes lacks it, especially if it was copied or generated on Windows)../mvnw: invokes the wrapper. The first time, it downloads Maven and all the dependencies, so it will take a little longer.-B(batch mode): non-interactive mode, with cleaner output. This is how Jenkins will run it.verify: goes through the Maven lifecycle phases up to verification: compiling, running the tests, packaging the.jarand checking the result.
At the end you should see something like this:
And the file target/orders-api-1.0.0-SNAPSHOT.jar will have been created. If you want to try out the API:
In another terminal:
curl http://localhost:8081/api/orders
curl http://localhost:8081/api/orders/2
curl http://localhost:8081/actuator/healthThe first command returns the JSON with the three orders, the second returns Pablo Ortega's order and the third returns {"status":"UP"}. Stop the application with Ctrl+C.
Don't have JDK 21 on your machine? You can build inside a temporary container:
--rm: removes the container when it finishes.-v "$PWD":/app: mounts the current directory inside the container at/app.-w /app: sets/appas the working directory.eclipse-temurin:21-jdk: an official image with a JDK 21.
The Git Repository
With the project working locally, it is time to put it under version control:
git init -b main
git add .
git update-index --chmod=+x mvnw
git commit -m "Initial version of orders-api"git init -b main: creates the repository with its main branch namedmain.git add .: adds all the files (except those ignored by.gitignore).git update-index --chmod=+x mvnw: records in Git thatmvnwis executable. This is especially important if you work on Windows, where the file system does not store that permission; this way, when Jenkins fetches the code on Linux, the script will be able to run.git commit -m ...: creates the first commit.
Now create the repository on GitHub:
- On GitHub, click New repository.
- Name:
orders-api. - Visibility: Public. That way Jenkins can fetch it without credentials. Working with private repositories requires configuring credentials, which we will cover in Credentials and Secrets Management in Pipelines.
- Do not check the options to create a README,
.gitignoreor license (you already have local content). - Click Create repository.
Link your local repository to the remote one and push it:
git remote add origin <url>: registers the GitHub repository under the nameorigin.git push -u origin main: pushes themainbranch and sets it to track the remote, so from then ongit pushis enough.
If GitHub asks you to authenticate, use your usual method (GitHub CLI, personal access token or SSH). That authentication is yours, on your machine; Jenkins does not need it because the repository is public.
Security note: since it is public, never push passwords, tokens or real data. Everything in
orders-apiis fictional.
The Jenkins Controller with Docker Compose
In Installing Jenkins you started Jenkins with docker run. For the course we will use Docker Compose, which stores the container definition in a YAML file: it is easier to read, to version and to modify in later modules.
Before You Start
If you still have the trial container from lesson 01-02, remove it to free up the ports:
The docker-compose.yml File
Create a directory separate from the project, for example ~/tecnoshop-jenkins, and inside it the docker-compose.yml file:
services:
jenkins-controller:
image: jenkins/jenkins:lts-jdk21
container_name: jenkins-controller
restart: unless-stopped
ports:
- "8080:8080"
- "50000:50000"
volumes:
- jenkins_home:/var/jenkins_home
volumes:
jenkins_home:
name: jenkins_homeLine by line:
services:: the list of services (containers) that Compose manages.jenkins-controller:: the name of the service. This is the one you will use in commands such asdocker compose logs jenkins-controller.image: jenkins/jenkins:lts-jdk21: the official Jenkins image, LTS line, with Java 21.container_name: jenkins-controller: a fixed name for the container, so you can use it with regulardockercommands (docker exec jenkins-controller ...).restart: unless-stopped: Docker restarts the container if it crashes or if you reboot your machine, unless you have explicitly stopped it.ports:: publishes 8080 (web interface) and 50000 (inbound agents, which we will use later).volumes: - jenkins_home:/var/jenkins_home: mounts the volume namedjenkins_homeon the Jenkins data directory.- The final
volumes: jenkins_home: name: jenkins_homeblock: declares the volume. Thenameproperty sets its actual name in Docker tojenkins_home; without it, Compose would prefix it with the directory name (tecnoshop-jenkins_jenkins_home).
This file is not part of the orders-api repository: it is your Jenkins infrastructure. You can version it in a separate repository if you like.
Startup and Initial Configuration
docker compose up -d: downloads the image (the first time), creates the volume and starts the container in the background.docker compose ps: shows the status of the service; it should appear asrunningorUp.
Get the initial password:
docker compose exec runs a command inside the container of the specified service. Then open http://localhost:8080 and complete the wizard exactly as you learned in Installing Jenkins: Install suggested plugins, create your administrator user and leave http://localhost:8080/ as the Jenkins URL.
Checking the Container
Jenkins will need Git to fetch your repository and Java to run Maven. The official image includes both; check it:
docker exec jenkins-controller git --version
docker exec jenkins-controller java -version
docker exec jenkins-controller sh -c 'java --list-modules | grep jdk.compiler'- The first should show
git version 2.x. - The second, a Java 21 version.
- The third confirms that the image's Java includes the compiler module (
jdk.compiler), which is what Maven uses to compile Java code.
Why We Can Build on the Built-in Node (for Now)
In the architecture lesson you saw that the recommended practice is for the controller not to run builds. Even so, during modules 1 to 4 we will run the orders-api builds on the built-in node of the jenkins-controller container. Why does it work, and why are we doing it?
- It works because the
jenkins/jenkins:lts-jdk21image ships with Java 21, the same versionorders-apineeds, and Git. Since we use the Maven Wrapper, there is no need to install Maven:./mvnwwill download it on the first build and store it, along with the dependencies, in/var/jenkins_home/.m2, inside the volume. That way subsequent builds will be faster. - We do it because it simplifies the environment while you learn the fundamentals: a single container and nothing else.
Warning: this is a teaching simplification. In a real Jenkins, building on the controller is a security and performance risk. In module 5 we will add the
linux-agent-01agent, set the controller to 0 executors, and move all builds to that agent.
Handy Everyday Commands
Run these commands from the directory containing docker-compose.yml:
| Command | What it does | Do you lose data? |
|---|---|---|
docker compose up -d |
Creates (if it does not exist) and starts Jenkins in the background | No |
docker compose ps |
Shows the status of the service | No |
docker compose logs -f jenkins-controller |
Shows the Jenkins log and follows it in real time (Ctrl+C to exit) |
No |
docker compose stop |
Stops the container without removing it | No |
docker compose start |
Starts a stopped container again | No |
docker compose restart |
Restarts Jenkins (useful after installing some plugins) | No |
docker compose down |
Stops and removes the container (and its network), but keeps the volume | No: the data is still in jenkins_home |
docker compose down -v |
Stops and removes the container and removes the volumes | Yes: you lose EVERYTHING |
Danger:
docker compose down -vdeletes thejenkins_homevolume along with all your jobs, users, plugins, credentials and build history. Do not use it unless you deliberately want to start from scratch. For everyday use,stop/startordown/up -dare safe.
Common Mistakes and Tips
./mvnw: Permission denied: the script does not have execute permission. Runchmod +x mvnwlocally and record the permission in Git withgit update-index --chmod=+x mvnw, then commit and push.- Forgetting to push the wrapper: if
mvnwor.mvn/are not on GitHub, Jenkins will not be able to build. Check on the GitHub website that they are there. - Port 8080 already in use: it is usually the
jenkins-trialcontainer from lesson 01-02, ororders-apiitself if you forgot to changeserver.port. Check withdocker ps. - Private repository by mistake: Jenkins will fail to clone with an authentication error. Change the visibility to public, or wait until module 4 to use credentials.
- Pushing
target/: if you do not have a.gitignorebefore the firstgit add, you may push the build directory. Remove it from the index withgit rm -r --cached targetand commit. - Mixing up the service name and the container name:
docker compose ...uses the service name;docker ...uses the container name. Here they match (jenkins-controller) to keep things simple. - Tip: always verify locally with
./mvnw -B verifybefore pushing. If it fails on your machine, it will fail in Jenkins.
Exercises
Exercise 1. Complete the environment: create the project, verify it with ./mvnw -B verify, push it to GitHub and bring up jenkins-controller with Docker Compose. Then answer: what is your repository's HTTPS clone URL? What Git and Java versions does the container show?
Exercise 2. Add a fourth fictional order to OrderController. Before running anything, predict what will happen when you run ./mvnw -B verify. Check it and then undo the change (do not push it to GitHub).
Exercise 3. A teammate runs docker compose down -v "to restart Jenkins clean" and then docker compose up -d. What will they find when they open http://localhost:8080? Which command should they have used to simply restart it?
Solutions
Solution 1. The URL will have the form https://github.com/<your-username>/orders-api.git (you can find it under GitHub's Code button). You get the versions with docker exec jenkins-controller git --version and docker exec jenkins-controller java -version; the Java version should start with 21. If everything went well, docker compose ps shows the service running and you can sign in at http://localhost:8080 with your administrator user.
Solution 2. The listReturnsThreeOrders test will fail, because it expects 3 orders and now there are 4. Maven will display a message like expected: <3> but was: <4>, the summary Tests run: 3, Failures: 1, and it will finish with BUILD FAILURE. To undo the uncommitted change: git restore src/main/java/com/tecnoshop/orders/OrderController.java.
Solution 3. They will find a freshly installed Jenkins: the Unlock Jenkins screen asking for the initial password again, with no users, plugins or jobs, because -v deleted the jenkins_home volume. To restart without losing data, they should have used docker compose restart (or docker compose down followed by docker compose up -d).
Conclusion
You now have the environment you will use throughout the course: the real orders-api code (with OrdersApiApplication, the Order record, the OrderController with GET /api/orders and GET /api/orders/{id}, and the OrderControllerTest test), verified locally with ./mvnw -B verify, versioned in your public GitHub repository on the main branch, and a jenkins-controller controller running with Docker Compose on the jenkins_home volume. You also know why we will build on the built-in node for now, and which Compose commands are safe. Everything is ready for Jenkins to do its first piece of work: in the next lesson, Your First Jenkins Job, you will create the orders-api-build job, which will build and test your repository automatically.
