Skip to main content

Deploy Spring Boot Application to Fly.io

Since I haven't had an experience in Spring Boot application along with database(in my case PostgreSQL), I had hard time dockerizing it and deploying this for as development server. So I'm leaving this record of deploying Spring Boot application to fly.io with PostgreSQL database setup.


Previous Setup

1. Before start, suppose you're using followings:

  • JDK 11 (Java 11)
  • Gradle
  • PostgreSQL

2. fly.io Account

Register your account at https://fly.io/app/sign-in.


Dockerfile Setup

Generate Build File

$ ./gradlew clean build

then, build/ folder would be completely removed and then re-created.


Dockerfile

# Setup build file(.jar)
FROM adoptopenjdk/openjdk11 AS builder

WORKDIR /usr/src/app
ARG JAR_FILE=build/libs/*.jar
COPY ${JAR_FILE} app.jar

# Run .jar file copied from `builder` stage
FROM adoptopenjdk/openjdk11 AS runner

WORKDIR /usr/src/app
COPY --from=builder /usr/src/app/app.jar app.jar
EXPOSE 8080
CMD java -jar app.jar

Fly.io PostgreSQL Setup

You need to set PostgreSQL database in your application.yml (or application.properties) file.

server:
port: 8080

spring:
datasource:
# url: jdbc:postgresql://<host_name>:<port>/<database_name>
url: jdbc:postgresql://localhost:5432/the_survey_dev
username: the_survey_dev # user's name
password: the_survey_dev # user's password
jpa:
database-platform: org.hibernate.dialect.PostgreSQLDialect
hibernate:
ddl-auto: create

and then run followings

$ flyctl postgres create

# If you need any preset, then connect direct to created database by running
# `flyctl postgres connect -a <YOUR_APP_NAME>`

Mount PostgreSQL machines (≤ flyctl==v0.0.530)

flyctl-prev-error-message

Before flyctl version 0.0.531, you had to setup mounts with <machine id>s as follows:

$ fly machine list # check machine list and get `id`s
$ fly machine update --metadata fly_platform_version=v2 <machine id>

But the last command guide <machine id> was missing so I've requested a Pull Request and was accepted from flyctl pull request #2093 and reflected on v0.0.531.

And after v0.0.531 update, you'll see it's been updated by automatically adding machine's id when you create HA(High Availability) cluster.


Deploy to fly.io

After you're all set, you could just deploy your application by running

$ fly launch
# Or if you already have Dockerfile and fly.toml config, you could just run `fly deploy`
Related Links