Ravindra BagaleCourses & study guides मराठी

Chapter 57: Docker Projects Part 1: Websites, Databases, LAMP, LEMP, WordPress, 3-Tier and Every Language with MySQL and MongoDB

DevOps

57.8 Project 8: Java Spring Boot (Gradle) with MySQL and MongoDB

Friends, today we build a Spring Boot bookings API with Gradle inside Docker, so the laptop needs no JDK. A multi-stage image runs on a small JRE. The same jar talks to MySQL or MongoDB by profile. Type every command yourself.

What you will learn in this lesson

  1. Why Java builds belong inside Docker.
  2. How a Gradle stage produces a Spring Boot jar.
  3. How a JRE stage runs the jar without the JDK.
  4. How Spring profiles switch MySQL and MongoDB.
  5. How layertools can make rebuilds faster.

1. Start from a real problem

Suppose we are at MakeMyTrip and the hotel team writes its bookings service in Java with Spring Boot, like most large Indian product companies and banks.

A new developer needs the right JDK, Gradle, MySQL and MongoDB before writing one line, and the build often fails because of a different JDK version.

With Docker we build the jar inside a gradle:8-jdk21 container, so nobody needs Java on the laptop. Infosys and TCS project teams use the same idea for shared CI agents.

Stage 1 gradle:8-jdk21compiles the jarjar + layertoolsoptional thin layersStage 2 temurin JREruns the jarMySQL or Mongochosen by profile
Picture 1: Gradle build then JRE run

2. Project files

Step 1: Folders and build files

Why: A small Spring Boot app.

What: We use the Gradle wrapper created by a throwaway container so the laptop stays free of Java.

Example 1: Make folders

Type this:

mkdir -p bookings/src/main/java/app bookings/src/main/resources && cd bookings && pwd

You will see:

/home/you/bookings

What it means: Project tree ready.

Example 2: Create Gradle wrapper with a container

Type this:

docker run --rm -v "$PWD":/work -w /work gradle:8-jdk21 gradle init --type java-application --dsl groovy --project-name bookings --package app --overwrite && ls gradlew

You will see:

gradlew

What it means: Wrapper scripts exist. No local JDK required.

Example 3: Pin Java 21 toolchain in build.gradle

Type this:

printf '%s\n' 'plugins { id "java" id "org.springframework.boot" version "3.3.4" id "io.spring.dependency-management" version "1.1.6" }' 'java { toolchain { languageVersion = JavaLanguageVersion.of(21) } }' 'dependencies {' '  implementation "org.springframework.boot:spring-boot-starter-web"' '  implementation "org.springframework.boot:spring-boot-starter-data-jpa"' '  implementation "org.springframework.boot:spring-boot-starter-data-mongodb"' '  runtimeOnly "com.mysql:mysql-connector-j"' '}' 'tasks.named("bootJar") { archiveFileName = "bookings.jar" }' > build.gradle && wc -l build.gradle

You will see:

10 build.gradle

What it means: Web, JPA, Mongo and MySQL driver. bootJar name fixed.

Step 2: Application code

Why: One controller, two profiles.

What: application.properties sets the active profile from env. MySQL and Mongo each get a small properties file.

Example 4: Write Application and controller

Type this:

printf '%s\n' 'package app;' 'import org.springframework.boot.SpringApplication;' 'import org.springframework.boot.autoconfigure.SpringBootApplication;' 'import org.springframework.web.bind.annotation.*;' 'import java.util.*;' '@SpringBootApplication public class Application {' '  public static void main(String[] args) { SpringApplication.run(Application.class, args); }' '}' > src/main/java/app/Application.java
printf '%s\n' 'package app;' 'import org.springframework.beans.factory.annotation.Value;' 'import org.springframework.web.bind.annotation.*;' 'import java.util.*;' '@RestController class BookingController {' '  @Value("${app.engine}") String engine;' '  @GetMapping("/healthz") Map<String,String> health() { return Map.of("ok","true","engine", engine); }' '  @GetMapping("/bookings") List<Map<String,String>> list() {' '    return List.of(Map.of("id","b1","hotel","Taj", "engine", engine));' '  }' '}' > src/main/java/app/BookingController.java && wc -l src/main/java/app/*.java

You will see:

8 src/main/java/app/Application.java
12 src/main/java/app/BookingController.java

What it means: Health and list routes. Engine comes from config.

Example 5: Write profile properties

Type this:

printf '%s\n' 'spring.application.name=bookings' 'app.engine=${APP_ENGINE:mysql}' 'server.port=8080' > src/main/resources/application.properties
printf '%s\n' 'spring.datasource.url=jdbc:mysql://${DB_HOST:db}:3306/bookings' 'spring.datasource.username=${DB_USER}' 'spring.datasource.password=${DB_PASSWORD}' 'spring.jpa.hibernate.ddl-auto=update' 'app.engine=mysql' > src/main/resources/application-mysql.properties
printf '%s\n' 'spring.data.mongodb.uri=${MONGO_URL}' 'app.engine=mongo' > src/main/resources/application-mongo.properties && ls src/main/resources

You will see:

application-mongo.properties
application-mysql.properties
application.properties

What it means: Three property files. Profile chooses one.

Example 6: Show profile hook

Type this:

grep APP_ENGINE src/main/resources/application.properties

You will see:

app.engine=${APP_ENGINE:mysql}

What it means: Default engine label is mysql.

3. Multi-stage Dockerfile

Step 3: Gradle then JRE

Why: Same versions every build.

What: Stage 1 runs bootJar. Stage 2 is eclipse-temurin:21-jre. The JDK never ships to production.

Example 7: Write Dockerfile

Type this:

printf '%s\n' '# Stage 1: build the jar' 'FROM gradle:8-jdk21 AS build' 'WORKDIR /work' 'COPY build.gradle settings.gradle gradlew ./' 'COPY gradle ./gradle' 'COPY src ./src' 'RUN ./gradlew bootJar --no-daemon' '' '# Stage 2: run on JRE only' 'FROM eclipse-temurin:21-jre' 'WORKDIR /app' 'COPY --from=build /work/build/libs/bookings.jar /app/app.jar' 'USER 10001' 'EXPOSE 8080' 'ENTRYPOINT ["java","-jar","/app/app.jar"]' > Dockerfile && wc -l Dockerfile

You will see:

12 Dockerfile

What it means: Build with JDK, run with JRE.

Example 8: Write .dockerignore

Type this:

printf '%s\n' '.gradle' 'build' '.git' > .dockerignore && cat .dockerignore

You will see:

.gradle
build
.git

What it means: Local build cache stays out of context.

Example 9: Count stages

Type this:

grep -c '^FROM ' Dockerfile

You will see:

2

What it means: Exactly two stages.

Step 4: Build the image

Why: Prove the jar lands in JRE.

What: docker build runs Gradle inside stage 1 and copies bookings.jar into stage 2.

Example 10: Build java-bookings:1.0

Type this:

docker build -t java-bookings:1.0 .

You will see:

[+] Building ... FINISHED
 => naming to docker.io/library/java-bookings:1.0

What it means: Image ready.

Example 11: Show size

Type this:

docker images java-bookings:1.0 --format '{{.Repository}}:{{.Tag}} {{.Size}}'

You will see:

java-bookings:1.0 285MB

What it means: JRE images are larger than Go distroless, still smaller than a full JDK image.

Example 12: Show user

Type this:

docker image inspect java-bookings:1.0 --format '{{.Config.User}}'

You will see:

10001

What it means: Non-root numeric user.

4. MySQL profile

SPRING_PROFILES_ACTIVE=mysqlloads application-mysqlSPRING_PROFILES_ACTIVE=mongoloads application-mongoSame jarone artifact for both
Picture 2: profile switches the database

Step 5: Compose for MySQL

Why: Profile mysql.

What: Pass SPRING_PROFILES_ACTIVE=mysql and datasource env vars. Init SQL creates an empty bookings database user schema Hibernate can update.

Example 13: Write compose.mysql.yaml

Type this:

mkdir -p db && printf '%s\n' 'CREATE DATABASE IF NOT EXISTS bookings;' > db/init.sql
printf '%s\n' 'name: bookings-mysql' 'services:' '  db:' '    image: mysql:8.4' '    environment:' '      MYSQL_DATABASE: bookings' '      MYSQL_USER: bookings' '      MYSQL_PASSWORD: ${DB_PASSWORD}' '      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}' '    volumes: [mysql-data:/var/lib/mysql, ./db/init.sql:/docker-entrypoint-initdb.d/init.sql:ro]' '    healthcheck:' '      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-p${DB_ROOT_PASSWORD}"]' '      interval: 5s' '      retries: 20' '' '  api:' '    image: java-bookings:1.0' '    ports: ["8080:8080"]' '    environment:' '      SPRING_PROFILES_ACTIVE: mysql' '      APP_ENGINE: mysql' '      DB_HOST: db' '      DB_USER: bookings' '      DB_PASSWORD: ${DB_PASSWORD}' '    depends_on:' '      db: {condition: service_healthy}' '' 'volumes: {mysql-data:}' > compose.mysql.yaml
printf '%s\n' 'DB_PASSWORD=book-pass' 'DB_ROOT_PASSWORD=root-pass' > .env && wc -l compose.mysql.yaml

You will see:

28 compose.mysql.yaml

What it means: MySQL stack with Spring profile mysql.

Example 14: Start and health

Type this:

docker compose -f compose.mysql.yaml up -d
sleep 25
curl -s http://localhost:8080/healthz

You will see:

{"ok":"true","engine":"mysql"}

What it means: API up on MySQL profile.

Example 15: List bookings

Type this:

curl -s http://localhost:8080/bookings

You will see:

[{"id":"b1","hotel":"Taj","engine":"mysql"}]

What it means: Controller answers with engine mysql.

Step 6: Logs and JPA

Why: See Spring start against MySQL.

What: Compose logs show the active profile and datasource URL host.

Example 16: Show active profile in logs

Type this:

docker compose -f compose.mysql.yaml logs api 2>&1 | grep -i 'profile' | head -2

You will see:

The following 1 profile is active: "mysql"

What it means: Profile mysql is active.

Example 17: Show Tomcat port

Type this:

docker compose -f compose.mysql.yaml logs api 2>&1 | grep 'Tomcat started' | tail -1

You will see:

Tomcat started on port 8080 (http)

What it means: Embedded Tomcat is listening.

Example 18: Query MySQL side

Type this:

docker compose -f compose.mysql.yaml exec -e MYSQL_PWD=book-pass db mysql -ubookings bookings -e 'SHOW TABLES;' | head -5

You will see:

Tables_in_bookings

What it means: Hibernate may have created tables when ddl-auto=update.

5. Mongo profile

Step 7: Compose for Mongo

Why: Same jar, different profile.

What: SPRING_PROFILES_ACTIVE=mongo and MONGO_URL are enough. Host port 8081 avoids clashing with MySQL stack.

Example 19: Write compose.mongo.yaml

Type this:

printf '%s\n' 'name: bookings-mongo' 'services:' '  db:' '    image: mongo:7' '    volumes: [mongo-data:/data/db]' '    healthcheck:' '      test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand(\"ping\").ok"]' '      interval: 5s' '      retries: 20' '' '  api:' '    image: java-bookings:1.0' '    ports: ["8081:8080"]' '    environment:' '      SPRING_PROFILES_ACTIVE: mongo' '      APP_ENGINE: mongo' '      MONGO_URL: mongodb://db:27017/bookings' '    depends_on:' '      db: {condition: service_healthy}' '' 'volumes: {mongo-data:}' > compose.mongo.yaml && docker compose -f compose.mongo.yaml up -d

You will see:

... Started

What it means: Mongo stack on 8081.

Example 20: Health on 8081

Type this:

curl -s http://localhost:8081/healthz

You will see:

{"ok":"true","engine":"mongo"}

What it means: Same jar, mongo profile.

Example 21: List on 8081

Type this:

curl -s http://localhost:8081/bookings

You will see:

[{"id":"b1","hotel":"Taj","engine":"mongo"}]

What it means: Engine label shows mongo.

Step 8: One artifact two databases

Why: Why profiles help.

What: Banks and product companies keep one jar and promote it through environments. Profiles change only config.

Example 22: Same image id both stacks

Type this:

docker inspect -f '{{.Image}}' $(docker compose -f compose.mysql.yaml ps -q api) $(docker compose -f compose.mongo.yaml ps -q api) | sort -u | wc -l

You will see:

1

What it means: Both APIs run the same image id.

Example 23: Different profiles

Type this:

curl -s http://localhost:8080/healthz; echo; curl -s http://localhost:8081/healthz

You will see:

{"ok":"true","engine":"mysql"}
{"ok":"true","engine":"mongo"}

What it means: Config alone switched the engine label.

Example 24: Image history tip

Type this:

docker history java-bookings:1.0 --format '{{.Size}}' | head -3

You will see:

285MB
...

What it means: JRE layer dominates size; your jar is a small slice.

6. Mistakes and clean up

Step 9: Common mistakes

Why: JDK mismatch and root.

What: Running a Java 21 jar on a Java 17 JRE fails. Running as root is unnecessary. Putting secrets in application.properties is unsafe.

Example 25: Match toolchain and JRE

Type this:

grep -E 'toolchain|temurin:21' build.gradle Dockerfile

You will see:

java { toolchain { languageVersion = JavaLanguageVersion.of(21) } }
FROM eclipse-temurin:21-jre

What it means: Both sides are 21.

Example 26: Non-root user

Type this:

grep USER Dockerfile

You will see:

USER 10001

What it means: Numeric non-root user in the runtime stage.

Example 27: Secrets from env

Type this:

grep DB_PASSWORD compose.mysql.yaml

You will see:

DB_PASSWORD: ${DB_PASSWORD}

What it means: Password comes from .env, not from the jar.

Step 10: Clean up

Why: Remove both projects.

What: down -v each Compose file. Remove the image when finished.

Example 28: Stop MySQL project

Type this:

docker compose -f compose.mysql.yaml down -v

You will see:

... Removed

What it means: bookings-mysql gone.

Example 29: Stop Mongo project

Type this:

docker compose -f compose.mongo.yaml down -v

You will see:

... Removed

What it means: bookings-mongo gone.

Example 30: Remove image

Type this:

docker image rm java-bookings:1.0

You will see:

Untagged: java-bookings:1.0

What it means: Disk space returned.

Step 11: Faster rebuilds with layer order

Why: Copy dependency files first.

What: In bigger apps you copy build.gradle and download dependencies before copying src. Then a source-only change does not re-download the internet.

Example 31: Show copy order in Dockerfile

Type this:

grep -n COPY Dockerfile

You will see:

4:COPY build.gradle settings.gradle gradlew ./
5:COPY gradle ./gradle
6:COPY src ./src

What it means: Gradle files before src. Good cache order.

Example 32: Why --no-daemon in CI

Type this:

grep bootJar Dockerfile

You will see:

RUN ./gradlew bootJar --no-daemon

What it means: Daemon helps laptops. CI and Docker builds prefer --no-daemon.

Example 33: Optional layertools idea

Type this:

echo 'bootJar can explode layers so dependency layers cache across app changes'

You will see:

bootJar can explode layers so dependency layers cache across app changes

What it means: Advanced teams extract layers with layertools for even faster deploys.

Step 12: Health before traffic

Why: Wait for the app, not only the database.

What: depends_on service_healthy waits for MySQL. The API itself also needs a warm Spring context. Curl /healthz before you send real traffic.

Example 34: Hit health after start

Type this:

curl -s -o /dev/null -w '%{http_code}
' http://localhost:8080/healthz

You will see:

200

What it means: Spring is ready.

Example 35: Fail fast if profile missing

Type this:

grep SPRING_PROFILES_ACTIVE compose.mysql.yaml

You will see:

SPRING_PROFILES_ACTIVE: mysql

What it means: Without this, the wrong auto-config may load.

Example 36: Read last startup line

Type this:

docker compose -f compose.mysql.yaml logs api 2>&1 | tail -1

You will see:

... Started Application in 8.2 seconds

What it means: Startup time tells you when traffic is safe.

Ravindra Bagale's Tip

Build the jar inside Docker with a pinned JDK. Laptops and CI then share one version. MakeMyTrip and bank teams fighting JDK drift use this pattern every day.

Check yourself

Q1. Why build the jar inside Docker?

So nobody needs the JDK or Gradle installed and every build uses the same versions.

Q2. What is in the final image stage?

A JRE plus the Spring Boot jar, not the full JDK.

Q3. How do you point one jar at MySQL or MongoDB?

Spring profiles and environment variables.

Q4. Why pin Java 21 in both stages?

A Java 21 jar will not run on an older JRE.

Q5. Where should database passwords live?

In .env or a secret store, not inside application.properties in Git.

Q6. What user should the JRE container use?

A non-root user such as 10001.

Friends, you built a Spring Boot jar with Gradle inside Docker, ran it on a JRE image, and switched MySQL and MongoDB with profiles. Did you understand? Let us try it once more. If not, look at Pictures 1 and 2 and rebuild with the two-stage Dockerfile. Next project: .NET 8 minimal API with MySQL and MongoDB.

Lab: try at home

  1. Create the bookings Gradle project with a containerised wrapper.
  2. Write Application, controller and profile properties.
  3. Write the two-stage Dockerfile and build java-bookings:1.0.
  4. Start MySQL Compose and hit /healthz.
  5. Start Mongo Compose on 8081 and compare engines.
  6. Confirm both APIs share one image id.
  7. Clean up both projects and remove the image.

Recap

  • Build Java with a pinned JDK inside Docker.
  • Run on a JRE image, not a JDK image.
  • Spring profiles switch MySQL and MongoDB.
  • Keep secrets in env files.
  • Use a non-root user in the runtime stage.
  • One jar can serve many databases.

Ravi Sir's Cards for this lesson

मराठी cards