Documentation Frameworks and migration

Deploy a Spring Boot app

A Maven or Gradle jar from a Dockerfile on $PORT, JVM memory, PostgreSQL and Flyway migrations.

~4 min read
On this page

Gregale builds Node, Python and Go from source, but not Java. A Spring Boot app deploys from a Dockerfile that builds the jar with Maven or Gradle and copies it onto a Java runtime. Quarkus, Micronaut and other JVM servers work the same way. What every framework shares is on Deploy a web framework.

The JVM's start-up time matters less here than on other platforms: Gregale snapshots the running app after it starts, and a parked app wakes from that snapshot instead of starting Spring again.

Prepare the app

Listen on every interface and the port in PORT. In application.properties:

properties
server.address=0.0.0.0
server.port=${PORT:8080}
server.shutdown=graceful

Add a cheap health endpoint that doesn't touch the database:

java
@GetMapping("/healthz")
Map<String, Boolean> health() {
    return Map.of("ok", true);
}

Spring Boot Actuator's /actuator/health works too, but by default it checks the database, so a stopped database fails the health check. Point hosting.health at a path that answers without it.

Dockerfile

Add a Dockerfile at the project root. This one builds with Maven, then uses jlink to make a Java runtime with only the JDK modules Spring Boot and the PostgreSQL driver need. Replace notes-api with your jar's name (the finalName in pom.xml):

dockerfile
FROM maven:3.9-eclipse-temurin-25 AS build
WORKDIR /src
COPY pom.xml .
RUN mvn -B -q dependency:go-offline
COPY src src
RUN mvn -B -q -DskipTests package
RUN jlink --add-modules java.base,java.desktop,java.instrument,java.logging,java.management,java.naming,java.net.http,java.security.jgss,java.sql,jdk.crypto.ec,jdk.unsupported,jdk.zipfs \
      --strip-debug --no-man-pages --no-header-files --compress=zip-6 --output /jre

FROM debian:bookworm-slim
COPY --from=build /jre /opt/java
COPY --from=build /src/target/notes-api.jar /app/notes-api.jar
ENV PATH="/opt/java/bin:$PATH"
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75 -XX:+UseSerialGC"
EXPOSE 8080
CMD ["java", "-jar", "/app/notes-api.jar"]
  • Keep the image small. Every plan caps the app's filesystem (see Plans and pricing). This image unpacks to about 190 MB. The full eclipse-temurin JRE image is much larger once unpacked and can fail the build with app_layer_too_large, even on the Scale plan.
  • JDK modules. A library that needs a module the jlink line leaves out fails at start with NoClassDefFoundError for a java.* or javax.* class. Add the module, or list what your jar needs with jdeps --ignore-missing-deps --print-module-deps.
  • Memory. -XX:MaxRAMPercentage=75 sizes the heap from the instance's memory, not the host's. A small Spring Boot API runs in 512 MB; raise it with gregale app update my-api --ram 1024.
  • With Gradle, build with ./gradlew bootJar and copy build/libs/*.jar instead.
  • Each build gets 2 vCPU, 2048 MB of memory and 15 minutes; see Builds and framework detection.
yaml
# gregale.yaml
hosting:
  health: /healthz

Deploy

bash
gregale deploy --dry-run
gregale deploy --name my-api

If the deployment fails:

bash
gregale app health my-api --errors
gregale logs my-api

Add PostgreSQL

bash
gregale add postgres --app my-api

The connection URL arrives as DATABASE_URL, in the postgresql://user:password@host:port/db form. JDBC can't read that form directly, so turn it into a JDBC URL and credentials when you build the data source:

java
@Bean
@ConfigurationProperties("spring.datasource.hikari")
HikariDataSource dataSource() {
    URI uri = URI.create(System.getenv("DATABASE_URL"));
    String[] user = uri.getRawUserInfo().split(":", 2);
    HikariDataSource ds = new HikariDataSource();
    ds.setDriverClassName("org.postgresql.Driver");
    ds.setJdbcUrl("jdbc:postgresql://" + uri.getHost() + ":" + uri.getPort()
            + uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery()));
    ds.setUsername(URLDecoder.decode(user[0], UTF_8));
    ds.setPassword(URLDecoder.decode(user[1], UTF_8));
    return ds;
}
properties
# Start without waiting for the database, and keep each instance's pool small.
spring.datasource.hikari.initialization-fail-timeout=-1
spring.datasource.hikari.minimum-idle=0
spring.datasource.hikari.maximum-pool-size=5

DATABASE_URL goes through a connection pooler in transaction mode. The PostgreSQL JDBC driver's prepared statements work through it; see Managed PostgreSQL.

Run Flyway as a release command

Don't let Flyway or Liquibase migrate when the server starts: the serving app's credential can't change the schema. Turn it off (spring.flyway.enabled=false) and run migrations as a release command with their own credential:

bash
gregale postgres attach my-api-postgres my-api --access migration --env MIGRATION_DATABASE_URL

Have the jar migrate and exit when it's started with a migrate argument:

java
public static void main(String[] args) {
    if (args.length > 0 && args[0].equals("migrate")) {
        // Build the JDBC URL from MIGRATION_DATABASE_URL as above.
        Flyway.configure()
                .dataSource(jdbcUrl, user, password)
                .locations("classpath:db/migration")
                .load()
                .migrate();
        return;
    }
    SpringApplication.run(NotesApplication.class, args);
}
yaml
# gregale.yaml
release:
  command: java -jar /app/notes-api.jar migrate

The release command runs before the new version takes traffic; if it fails, the previous version keeps serving. Flyway holds a session lock while it migrates, which the direct migration connection supports.

Things to know

  • @Scheduled methods stop while the app is parked. Run scheduled work as a cron or a job.
  • The filesystem is ephemeral. Keep state in PostgreSQL or object storage.

Example repository

gregale-dev/spring-boot-postgres is the app on this page: a Spring Boot JSON API with JdbcClient, Flyway migrations as the release command, the DATABASE_URL parsing above, and the jlink Dockerfile. Its gregale.yaml creates the database, so one command deploys both:

bash
git clone https://github.com/gregale-dev/spring-boot-postgres
cd spring-boot-postgres
gregale deploy --name my-spring-api

Spotted a problem on this page? Tell us