Skip to content

Deploy a Spring Boot app

Your Spring Boot jar on a server of its own. git push to deploy.

Deploy on exe.dev

Shelley handles the setup. About 15 minutes.

Prefer a terminal?
curl -fsSL https://exe-staging.dev/deploy/spring-boot/prompt.txt | ssh exe.dev new --prompt=/dev/stdin

Spring Boot turns your app into one executable jar; this page gives it a server. An exe.dev VM builds that jar on every git push, runs it on Java 25 under systemd, and keeps its PostgreSQL database on a real disk that is still there tomorrow. exe.dev puts it on HTTPS, behind its own login until you decide otherwise.

The VM is a whole machine, not a container that's rebuilt on each deploy: no cold starts, no request time limits, scheduled tasks keep running, and you can SSH in and read the logs. exe.dev also signs people in for you, with a header Spring Security can trust, and its LLM gateway lets Spring AI call a model with no API key on the VM. Bring a repository from GitHub, or start from a small guestbook with JPA, Flyway, and exe.dev sign-in.

What you get#

  • Your app from GitHub (REPO), or a new Spring Boot 4 guestbook, running on Java 25 as app.service on port 8000, enabled to come back after a reboot.
  • PostgreSQL 18 on the VM with a database and a generated password for the app, passed in through ~/app.env (mode 600), with the JVM's memory flags.
  • A ~/app.git repository whose pre-receive hook builds each push to main with the project's Maven or Gradle wrapper, backs up the database, and rejects the push if the new version doesn't report ready.
  • Actuator's health and readiness on 127.0.0.1:8081, off the app's port, and the proxy's X-Forwarded headers trusted, so redirects and cookies use HTTPS.
  • For a new app, a guestbook that signs people in through exe.dev's X-ExeDev-Email header with Spring Security, and an /admin page for the emails in APP_ADMINS.
  • A nightly backup timer, and a first backup whose database dump is restored into a scratch database and counted.
What's running, and where
Private https://my-spring-boot.exe.xyz/ Your app, until you make it public
Private https://my-spring-boot.exe.xyz:8081/actuator/health Actuator's health check, for you, even once the app is public
Private my-spring-boot.exe.xyz:app.git git push exe main deploys
my-spring-boot.exe.xyz exe.dev VM
Your Spring Boot app one executable jar, built by Maven or Gradle from your repository, as app.service under systemd :8000~/app → the current release in ~/releases
Java 25 OpenJDK 25, the current LTS, from Ubuntu's packages
PostgreSQL 18 the app's database, migrated by Flyway when the app starts; settings in ~/app.env /var/lib/postgresql/18/main
git push deploys A pre-receive hook in ~/app.git builds, backs up, switches, and waits for readiness
Actuator health and readiness on 127.0.0.1:8081, apart from the app's port :8081
Nightly backup app-backup.timer; a database dump, settings, and the repository ~/backups

Deploy with Shelley#

Click Deploy and Shelley will set up Spring Boot on a new VM, then check that it works. No config-file wrangling required.

Have these ready; Shelley asks for them:

  • REPO: the GitHub repository to deploy, as owner/name or a URL, or new to start a fresh Spring Boot app
Prefer a terminal?
curl -fsSL \
  https://exe-staging.dev/deploy/spring-boot/prompt.txt \
  | ssh exe.dev new --prompt=/dev/stdin

When it's done, run this on your computer (only you can):

git clone -o exe my-spring-boot.exe.xyz:app.git    # if you started fresh
git remote add exe my-spring-boot.exe.xyz:app.git  # if you brought your app: in your checkout
What Shelley is told
REPO=<fill-this-in>

Set up Spring Boot on this VM by following the exe.dev recipe at https://exe-staging.dev/deploy/spring-boot.md?via=deploy from top to bottom.

The values at the top of this message are mine:
- REPO: the GitHub repository to deploy, as owner/name or a URL, or `new` to start a fresh Spring Boot app
Ask me for any that still say <fill-this-in> before you need them.

The recipe's example VM name is my-spring-boot. This VM's name is the output of `hostname`: use it wherever the recipe writes my-spring-boot. Skip the step that creates the VM; you are on it.

You are done when all of these are true. Check each one yourself:
- Your app from GitHub (REPO), or a new Spring Boot 4 guestbook, running on Java 25 as app.service on port 8000, enabled to come back after a reboot.
- PostgreSQL 18 on the VM with a database and a generated password for the app, passed in through ~/app.env (mode 600), with the JVM's memory flags.
- A ~/app.git repository whose pre-receive hook builds each push to main with the project's Maven or Gradle wrapper, backs up the database, and rejects the push if the new version doesn't report ready.
- Actuator's health and readiness on 127.0.0.1:8081, off the app's port, and the proxy's X-Forwarded headers trusted, so redirects and cookies use HTTPS.
- For a new app, a guestbook that signs people in through exe.dev's X-ExeDev-Email header with Spring Security, and an /admin page for the emails in APP_ADMINS.
- A nightly backup timer, and a first backup whose database dump is restored into a scratch database and counted.

Read the whole recipe, including the closed details. Follow "Set up by
hand" from "Install Java" to the end of it, as exedev; the walkthrough
above it is for the owner afterwards. Do not run Restore or Update, and
do not reboot. Leave public sharing off.
REPO picks one path in "Get the code": `new` starts a fresh app;
anything else is a GitHub repository (turn URLs into owner/name). Never
commit to a repository you cloned: its settings go in ~/app.env. If a
clone fails, follow the private-repository steps, and if that fails
too, give the owner the integration command and wait for them.
For a cloned app, follow "Bring your app": fill ~/app.env from its
application.properties or application.yml and README, generate secrets
with openssl, ask the owner for keys to outside services, and never
invent values. If a build fails, read its output, fix what you can
without editing the code, and redeploy with
~/app.git/hooks/pre-receive HEAD.
Keep the deploy hook and backup script as written, since the page
documents how they behave; if one looks wrong, say so at the end.
Finish with the app's URL; only the one git command from `after` that
fits; and what you set in ~/app.env for their app.

Finish with the URLs I should open and these commands, which only I can run, from my own computer (with this VM's name in them):
  git clone -o exe my-spring-boot.exe.xyz:app.git    # if you started fresh
  git remote add exe my-spring-boot.exe.xyz:app.git  # if you brought your app: in your checkout

Also at /deploy/spring-boot/prompt.txt. The recipe it follows is /deploy/spring-boot.md.

Open your app#

When setup finishes, open https://my-spring-boot.exe.xyz/ and sign in to exe.dev if asked. A new app shows a guestbook; sign it. Your message is signed with your exe.dev name, saved in PostgreSQL, and still there after a redeploy or a reboot. /admin opens for you, and for no one else until you list them.

Deploy with git push#

Your VM holds a git repository, ~/app.git, and deploys whatever you push to its main branch, like git push heroku main used to. Set it up once on your computer.

If Shelley started a new app, clone it from the VM:

git clone -o exe my-spring-boot.exe.xyz:app.git my-spring-boot
cd my-spring-boot

If you brought a GitHub repository, add the VM as a second remote in your usual checkout. GitHub stays your source of truth; exe is where you deploy:

git remote add exe my-spring-boot.exe.xyz:app.git

Then change something, commit, and push:

git push exe main

Use your default branch's name if it isn't main. The build streams back into your terminal and ends with ==> Deployed abc1234: ... answers HTTP 200. If ssh can't find the VM that way, use vm+my-spring-boot@vm.exe.xyz:app.git as the remote's address (why).

Each push builds the jar in a new release directory with the project's Maven or Gradle wrapper (tests skipped: they run on your computer or in CI), backs up the database, switches ~/app to the new release, restarts app.service, and waits for Actuator to say the app is ready. If any step fails, including a new version that exits or never gets ready, the old version comes back and git rejects the push (pre-receive hook declined), so the VM's main stays at the commit that's running.

The first build downloads Spring Boot's dependencies into ~/.m2 and takes a minute; later ones take about 20 seconds, plus the JVM's start. To roll back, push an older commit: git push -f exe <good-sha>:main.

Build on your computer or in CI#

To ship the exact jar you tested, build it anywhere with Java 25 or older and hand it to the hook, which deploys it with the same backup, readiness check, and rollback. On your computer:

./mvnw -DskipTests package       # or: ./gradlew bootJar
ssh my-spring-boot.exe.xyz app.git/hooks/pre-receive --jar - < target/app-0.0.1-SNAPSHOT.jar

A jar runs the same on any machine, so there's nothing to cross-compile. The next git push builds from source again.

From GitHub Actions, give the workflow an SSH key that opens this VM and nothing else. On your computer, make one, register it as a VM-scoped SSH key, and record the VM's host key:

ssh-keygen -t ed25519 -N '' -C spring-ci -f spring-ci
cat spring-ci.pub | ssh exe.dev ssh-key add --vm=my-spring-boot
ssh-keyscan -t rsa my-spring-boot.exe.xyz | tee known_hosts | ssh-keygen -lf -

The fingerprint must be SHA256:JJOP/lwiBGOMilfONPWZCXUrfK154cnJFXcqlsi6lPo, the same for every exe.dev VM. In the repository's Settings → Secrets and variables → Actions, add the contents of spring-ci as the secret DEPLOY_SSH_KEY and the line in known_hosts as the variable DEPLOY_KNOWN_HOSTS, then delete both files. This workflow runs the tests against a throwaway PostgreSQL and deploys the jar from main:

name: deploy
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:18
        env:
          POSTGRES_PASSWORD: test
        ports: ["5432:5432"]
        options: --health-cmd pg_isready --health-interval 2s --health-retries 20
    env:
      SPRING_DATASOURCE_URL: jdbc:postgresql://localhost:5432/postgres
      SPRING_DATASOURCE_USERNAME: postgres
      SPRING_DATASOURCE_PASSWORD: test
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-java@v5
        with:
          distribution: temurin
          java-version: 25
          cache: maven
      - run: ./mvnw -B verify
      - name: Deploy
        env:
          KEY: ${{ secrets.DEPLOY_SSH_KEY }}
          KNOWN_HOSTS: ${{ vars.DEPLOY_KNOWN_HOSTS }}
        run: |
          install -d -m 700 ~/.ssh
          printf '%s\n' "$KEY" > ~/.ssh/id_ed25519 && chmod 600 ~/.ssh/id_ed25519
          printf '%s\n' "$KNOWN_HOSTS" >> ~/.ssh/known_hosts
          ssh my-spring-boot.exe.xyz app.git/hooks/pre-receive --jar - < target/app-0.0.1-SNAPSHOT.jar

ssh exe.dev ssh-key remove spring-ci revokes the key. A failed deploy fails the job, and the running version stays.

Settings and secrets#

Environment variables live in one file on the VM, ~/app.env, as KEY=value lines (single-quote values with spaces or $). Spring Boot reads them as properties through relaxed binding: SPRING_DATASOURCE_PASSWORD is spring.datasource.password, SERVER_PORT is server.port. They beat application.properties, so keep defaults in the repository and secrets and per-VM values here. After a change, on the VM:

nano ~/app.env
sudo systemctl restart app

The file is mode 600 and in every backup. To hand a secret from your computer to the VM without pasting it into a chat, see agent secrets.

Java's memory on the VM#

The JVM sizes its heap from the VM's memory. Left alone it takes a quarter; ~/app.env sets JAVA_OPTS='-XX:MaxRAMPercentage=40 -XX:+ExitOnOutOfMemoryError', which leaves the rest for PostgreSQL, the JVM's own memory outside the heap (classes, threads, buffers), and the page cache:

VM memory Heap at 40% Notes
4 GB 1.6 GB plenty for the starter and most CRUD apps
8 GB 3.2 GB room for caches and a busy connection pool
16 GB 6.4 GB large in-memory work; tune PostgreSQL too

The heap follows the VM's memory at each start, so it grows when you resize the VM. With the database on another machine, 60 to 70 is safe. VMs have no swap, so a JVM that outgrows the VM is killed rather than slowed; ExitOnOutOfMemoryError makes a full heap end the process too, and systemd starts a clean one three seconds later. Check what you're using on the VM:

ps -o rss=,args= -C java | cut -c1-80
jcmd $(pgrep -f app.jar) VM.flags | tr ' ' '\n' | grep -E 'MaxHeapSize|Use.*GC'

The first number is the JVM's resident memory in KB. For PostgreSQL's share, see PostgreSQL.

Behind exe.dev's proxy#

exe.dev's HTTPS proxy handles TLS and talks plain HTTP to port 8000, adding X-Forwarded-Proto, X-Forwarded-Host, and X-Forwarded-For. SERVER_FORWARD_HEADERS_STRATEGY=native in ~/app.env tells Tomcat to believe them from localhost, which is where the proxy connects from. Then request.isSecure() is true, redirects and links built by Spring point at https://my-spring-boot.exe.xyz/, the session cookie gets Secure, and request.getRemoteAddr() is the visitor's address, not one they put in X-Forwarded-For themselves.

Don't configure TLS (server.ssl.*) or a port other than 8000 for the app. SERVER_ADDRESS=127.0.0.1 keeps Tomcat off the VM's network, so the proxy is the only way in from outside.

Your database#

PostgreSQL 18 runs on the VM, with a database and a role named app whose password the setup generated into ~/app.env, as SPRING_DATASOURCE_URL, _USERNAME, and _PASSWORD. Spring Data JPA and Hibernate talk to it; Flyway owns the schema. When the app starts, Flyway runs the new files in src/main/resources/db/migration in order, and spring.jpa.hibernate.ddl-auto=validate makes the start fail if an entity doesn't match the tables. To add a column, on your computer:

echo 'ALTER TABLE message ADD COLUMN likes INT NOT NULL DEFAULT 0;' > src/main/resources/db/migration/V2__likes.sql
git add src/main/resources/db/migration && git commit -m "Add likes" && git push exe main

The hook backs up the database before each switch. A migration that fails rolls back (PostgreSQL runs DDL in transactions), the app doesn't start, and the hook puts the old version back. A migration that succeeds stays, even if the deploy is rolled back later, so add columns rather than renaming or dropping them in the same release.

Open a SQL shell with psql app on the VM. For tuning, extensions such as pgvector, and upgrades, see PostgreSQL. MySQL works the same way with spring-boot-starter-flyway and flyway-mysql; see MySQL. For caching and sessions, add Redis.

Let exe.dev handle sign-in#

exe.dev signs visitors in for you. For each request from someone signed in to exe.dev, the proxy adds X-ExeDev-Email and X-ExeDev-UserID (login with exe), and it removes any X-ExeDev-* header the visitor sent. The starter's ExeDevSecurity turns that header into a Spring Security user with Spring's own pre-authentication filter, so @PreAuthorize, hasRole, Principal parameters, and Thymeleaf's sec:authorize work as usual:

@Configuration
public class ExeDevSecurity {

    /** Turns an X-ExeDev-Email into a user: ROLE_USER, plus ROLE_ADMIN for APP_ADMINS. */
    @Bean
    UserDetailsService exeDevUsers(@Value("${app.admins}") List<String> admins) {
        return email -> User.withUsername(email.strip().toLowerCase(Locale.ROOT))
                .password("")
                .roles(admins.stream().anyMatch(email.strip()::equalsIgnoreCase)
                        ? new String[] {"USER", "ADMIN"} : new String[] {"USER"})
                .build();
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http, UserDetailsService exeDevUsers)
            throws Exception {
        var provider = new PreAuthenticatedAuthenticationProvider();
        provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<>(exeDevUsers));
        var exeDevLogin = new RequestHeaderAuthenticationFilter();
        exeDevLogin.setPrincipalRequestHeader("X-ExeDev-Email");
        exeDevLogin.setExceptionIfHeaderMissing(false); // no header: anonymous
        exeDevLogin.setAuthenticationManager(new ProviderManager(provider));

        http.addFilter(exeDevLogin)
            // Read the header on every request; don't remember logins in a session.
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/admin/**", "/admin").hasRole("ADMIN")
                .anyRequest().permitAll())
            // Visitors who aren't signed in go to exe.dev's login page, then come back.
            .exceptionHandling(e -> e.authenticationEntryPoint((request, response, ex) ->
                response.sendRedirect("/__exe.dev/login?redirect="
                    + URLEncoder.encode(request.getRequestURI(), StandardCharsets.UTF_8))));
        return http.build();
    }
}

APP_ADMINS in ~/app.env lists the emails that get ROLE_ADMIN, comma-separated; setup put yours there. A visitor who isn't signed in and opens /admin goes to exe.dev's login page and comes back; a signed-in visitor who isn't an admin gets a 403. Spring Security's CSRF protection stays on, and Thymeleaf forms carry the token.

Warning

Trusting a header is only safe when nobody can send it but the proxy. On this VM that holds: the app listens on 127.0.0.1, the proxy is the only way in from outside, and it strips X-ExeDev-* from what visitors send. Anything that reaches port 8000 another way, such as another program on the VM, an SSH tunnel, or the same code deployed behind some other proxy, can claim to be anyone. Don't ship this filter anywhere exe.dev's proxy isn't in front.

To sign people out, post a form to /__exe.dev/logout.

Health checks#

Actuator answers on its own port, 8081, bound to 127.0.0.1, so /actuator isn't part of your public site at all. The deploy hook polls /actuator/health/readiness there, which says UP once the app has started, migrated, and is ready for traffic. On the VM:

curl -s http://127.0.0.1:8081/actuator/health; echo

You can open https://my-spring-boot.exe.xyz:8081/actuator/health in your browser too: exe.dev's ports other than 8000 stay private even when the app is public. Only health is exposed by default. If you expose more, such as metrics with MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE=health,metrics, keep them on this port.

Call an LLM with Spring AI#

exe.dev's LLM integration answers at https://llm.int.exe.xyz from your VM, with no API key: the VM is the credential, and usage is billed to your exe.dev account. Spring AI's OpenAI starter talks to it unchanged. Add it to pom.xml:

<!-- in <properties> -->
<spring-ai.version>2.0.2</spring-ai.version>

<!-- in <dependencies> -->
<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>

<!-- after </dependencies> -->
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.ai</groupId>
      <artifactId>spring-ai-bom</artifactId>
      <version>${spring-ai.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

Point it at the gateway in src/main/resources/application.properties. These aren't secrets, and they're the same on every exe.dev VM. The key must be set, or the app won't start, but nothing checks it:

spring.ai.openai.base-url=https://llm.int.exe.xyz/v1
spring.ai.openai.api-key=unused
spring.ai.openai.chat.model=gpt-5.4-mini

Then inject a ChatClient.Builder:

@RestController
public class AskController {
    private final ChatClient chat;

    public AskController(ChatClient.Builder chat) {
        this.chat = chat.build();
    }

    @GetMapping("/ask")
    public String ask(@RequestParam String q) {
        return chat.prompt().user(q).call().content();
    }
}

curl -s https://llm.int.exe.xyz/v1/models | jq -r '.data[].id' lists the models. For Claude, use spring-ai-starter-model-anthropic with spring.ai.anthropic.base-url=https://llm.int.exe.xyz, spring.ai.anthropic.api-key=unused, and a model such as spring.ai.anthropic.chat.model=claude-sonnet-4-6. Push, and /ask?q=hello answers. Other services' keys can stay off the VM too: the HTTP proxy integration adds them on the way out.

Make it public, add a domain#

The app is private: only people you've shared it with can open it, after signing in to exe.dev. When you're ready for the world, on your computer:

ssh exe.dev share set-public my-spring-boot

ssh exe.dev share set-private my-spring-boot closes it again. To serve it on your own domain, point a CNAME at my-spring-boot.exe.xyz and run ssh exe.dev domain add my-spring-boot app.example.com; exe.dev issues the certificate (custom domains). The app needs no change. Once it's public, visitors aren't signed in until they click Sign in, and /admin still sends them to exe.dev's login first.

Scheduled jobs#

The VM never sleeps, so Spring's own scheduler is enough: add @EnableScheduling to a configuration class and @Scheduled(cron = "0 0 4 * * *") to a method. For a job that should run even when the app is down, copy app-backup.service and .timer under a new name and point ExecStart at it.

Keep your data#

Every night, ~/bin/app-backup saves the database with pg_dump, plus ~/data (for uploads and other files your app writes; releases are replaced on each deploy), ~/app.env, and the whole ~/app.git repository into ~/backups/app-nightly-<time>.tar.gz. Each deploy saves an app-deploy- backup first. It keeps the 14 newest of each kind. A backup on a lost VM won't help much, so copy them off now and then. On your computer:

scp -r my-spring-boot.exe.xyz:backups ./my-spring-boot-backups

The files hold your secrets; keep them private. To make an extra backup before something risky, run ~/bin/app-backup on the VM; it prints the archive's name.

For staging, ssh exe.dev cp my-spring-boot my-spring-boot-staging copies the whole VM, database included; push there first (dev, test, prod).

Ask Shelley#

Shelley, at https://my-spring-boot.shelley.exe.xyz/, works on this VM with you, with Java, Maven, and the database at hand. Try: "The last deploy failed; read the output and tell me why", "Show me today's exceptions from journalctl -u app", "Add a REST API for the guestbook with a Flyway migration", or "Why does the app use 2 GB of memory?"

The nuts and bolts#

Happy with what Deploy set up? You can stop here. These are the setup steps Shelley follows, which you can run by hand, and the commands for later.

Set up by hand

Create the VM#

On your computer (pick another name if my-spring-boot is taken):

ssh exe.dev new --name=my-spring-boot
ssh my-spring-boot.exe.xyz

Everything else runs on the VM, as exedev.

Install Java#

Java 25 is the current long-term-support release, and Ubuntu 24.04 carries it. The JDK, not just the runtime, because the VM builds the jar:

sudo apt-get update
sudo apt-get install -y openjdk-25-jdk-headless
java -version

Expect openjdk version "25.0.x". Ubuntu's security updates keep it patched; Maven and Gradle come with each project, as wrappers. A project that targets Java 21 or 17 builds and runs on 25 unchanged.

Install PostgreSQL#

PostgreSQL 18, from the PostgreSQL project's apt repository (PGDG), with an en_US.UTF-8 cluster, as the PostgreSQL page sets it up:

sudo apt-get install -y postgresql-common jq
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y
sudo apt-get install -y postgresql-common
sudo pg_conftool /etc/postgresql-common/createcluster.conf set create_main_cluster off
sudo apt-get install -y postgresql-18
locale -a | grep -qx en_US.utf8 || sudo locale-gen en_US.UTF-8
[ -e /etc/postgresql/18/main/postgresql.conf ] || sudo pg_createcluster 18 main --locale=en_US.UTF-8 --start
pg_lsclusters

Expect 18 main 5432 online. Make exedev a superuser with its own database, so psql, pg_dump, and the backups work with no options:

sudo -u postgres createuser --superuser exedev
sudo -u postgres createdb --owner=exedev exedev
systemctl is-enabled postgresql

Expect enabled. PostgreSQL listens on localhost only.

Create the database and settings#

Create the app's role and database with a generated password, and the settings file the service and the deploy hook read. This leaves an existing ~/app.env alone:

mkdir -p ~/data ~/releases ~/backups ~/bin
if [ ! -e ~/app.env ]; then
  pass=$(openssl rand -hex 24)
  psql -X -q -d postgres -v ON_ERROR_STOP=1 -v pass="$pass" <<'SQL'
SELECT 'CREATE ROLE app LOGIN' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'app') \gexec
ALTER ROLE app PASSWORD :'pass';
SELECT 'CREATE DATABASE app OWNER app' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'app') \gexec
SQL
  install -m 600 /dev/null ~/app.env
  cat >> ~/app.env <<EOF
# Settings and secrets for the Spring Boot app: KEY=value, one per line.
# Read by app.service and the deploy hook. Spring Boot maps each variable
# to a property: SERVER_PORT is server.port. After a change:
#   sudo systemctl restart app

# The JVM: heap at 40% of the VM's memory; exit on OutOfMemoryError so
# systemd restarts a clean process.
JAVA_OPTS='-XX:MaxRAMPercentage=40 -XX:+ExitOnOutOfMemoryError'

# exe.dev's HTTPS proxy sends https://$(hostname).exe.xyz/ to port 8000 and
# says the request was HTTPS in X-Forwarded-Proto.
SERVER_ADDRESS=127.0.0.1
SERVER_PORT=8000
SERVER_FORWARD_HEADERS_STRATEGY=native

# Actuator on its own port, on localhost only: never reachable from outside.
MANAGEMENT_SERVER_PORT=8081
MANAGEMENT_SERVER_ADDRESS=127.0.0.1
MANAGEMENT_ENDPOINT_HEALTH_PROBES_ENABLED=true
# What the deploy hook polls before it calls a deploy good.
HEALTH_URL=http://127.0.0.1:8081/actuator/health/readiness

# PostgreSQL on this VM.
SPRING_DATASOURCE_URL=jdbc:postgresql://localhost:5432/app
SPRING_DATASOURCE_USERNAME=app
SPRING_DATASOURCE_PASSWORD=$pass

# exe.dev accounts that may open /admin in the starter app.
APP_ADMINS=$(curl -fsS https://reflection.int.exe.xyz/email | jq -r .email)
EOF
fi
stat -c '%a %n' ~/app.env
PGPASSWORD=$(sed -n 's/^SPRING_DATASOURCE_PASSWORD=//p' ~/app.env) psql -XAt -h localhost -U app -d app -c 'SELECT current_user'
grep '^APP_ADMINS' ~/app.env

Expect 600 /home/exedev/app.env, app (the password works), and your email.

Run the app with systemd#

The service runs the jar the hook builds, ~/app/app.jar, with the settings in ~/app.env. $JAVA_OPTS is split into separate flags:

sudo tee /etc/systemd/system/app.service >/dev/null <<'EOF'
[Unit]
Description=Spring Boot app (~/app/app.jar)
After=network-online.target postgresql.service
Wants=network-online.target

[Service]
User=exedev
WorkingDirectory=/home/exedev/app
EnvironmentFile=/home/exedev/app.env
ExecStart=/usr/bin/java $JAVA_OPTS -jar /home/exedev/app/app.jar
# The JVM exits with 143 after SIGTERM: a clean stop, not a failure.
SuccessExitStatus=143
Restart=always
RestartSec=3
# Spring Boot finishes requests in flight for up to 30 seconds on SIGTERM.
TimeoutStopSec=45

[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable app.service

It starts with the first deploy.

Back up every night#

~/bin/app-backup saves everything that isn't in a release: the database as a pg_dump archive (consistent while the app writes, and checked by listing it), ~/data, ~/app.env, and the repository in ~/app.git as a git bundle. A new app's only copy lives there until you clone it. It keeps the 14 newest backups of each kind: nightly, deploy (the hook takes one before each switch), and manual.

cat > ~/bin/app-backup <<'EOF'
#!/usr/bin/env bash
# Back up the app database, ~/data, ~/app.env and ~/app.git to
# ~/backups/app-<kind>-<time>.tar.gz. Keeps the 14 newest of each kind.
# Usage: app-backup [nightly|deploy|manual]
set -euo pipefail
umask 077
kind=${1:-manual}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mkdir -p "$HOME/backups"
pg_dump --dbname=app --format=custom --file="$work/app.dump"
pg_restore --list "$work/app.dump" >/dev/null
cp -a "$HOME/data" "$work/data"
cp "$HOME/app.env" "$work/"
if git -C "$HOME/app.git" rev-parse -q --verify HEAD >/dev/null; then
  git -C "$HOME/app.git" bundle create -q "$work/app.bundle" --all
fi
out="$HOME/backups/app-$kind-$(date -u +%Y%m%d-%H%M%S).tar.gz"
tar -czf "$out.part" -C "$work" .
mv "$out.part" "$out"
ls -1t "$HOME/backups/app-$kind-"*.tar.gz | tail -n +15 | xargs -r rm --
echo "$out"
EOF
chmod +x ~/bin/app-backup

Run it every night with a systemd timer:

sudo tee /etc/systemd/system/app-backup.service >/dev/null <<'EOF'
[Unit]
Description=Back up the app's database, files, settings and repository
After=postgresql.service

[Service]
Type=oneshot
User=exedev
ExecStart=/home/exedev/bin/app-backup nightly
EOF
sudo tee /etc/systemd/system/app-backup.timer >/dev/null <<'EOF'
[Unit]
Description=Back up the app every night

[Timer]
OnCalendar=*-*-* 03:00:00 UTC
RandomizedDelaySec=30m
Persistent=true

[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now app-backup.timer
systemctl list-timers app-backup.timer

Expect the next run, tonight. You'll take the first backup once the app is deployed.

Get the code#

The VM deploys from a bare git repository, ~/app.git. Create it one of two ways.

Start a new app (REPO=new): an empty repository whose branch is main.

git init --bare -b main ~/app.git

Bring your GitHub repository: a copy of it. A public repository clones directly; replace OWNER/NAME:

git clone --bare https://github.com/OWNER/NAME.git ~/app.git
git -C ~/app.git symbolic-ref --short HEAD

The last line prints the branch that will deploy: your default branch.

For a private repository, connect GitHub to exe.dev once (on the Integrations page) and attach the repository to this VM. On your computer:

ssh exe.dev integrations add github --name spring-repo --repository OWNER/NAME --readonly --attach vm:my-spring-boot

Then clone through the integration on the VM. No token lands on the disk (GitHub integration):

git clone --bare https://github.int.exe.xyz/OWNER/NAME.git ~/app.git

If that clone fails with "not found" or a 403, the integration isn't attached to this VM yet. If the build needs packages from a private Maven repository, put its credentials in ~/.m2/settings.xml (mode 600).

Add the deploy hook#

Git runs hooks/pre-receive before it accepts a push, as Heroku does. This one builds the pushed commit in its own directory under ~/releases with the project's mvnw or gradlew (or BUILD_COMMAND from ~/app.env, if set), backs up the database, switches ~/app to the new release, restarts the service, and waits up to two minutes for HEALTH_URL to answer. If any step fails, it switches back and rejects the push, so main on the VM is always what's running.

cat > ~/app.git/hooks/pre-receive <<'EOF'
#!/usr/bin/env bash
# Deploys the app. Git runs this before accepting a push to ~/app.git;
# if the deploy fails, the push is rejected and the running version stays.
# To redeploy the branch by hand:  ~/app.git/hooks/pre-receive HEAD
# To deploy a jar built elsewhere: ~/app.git/hooks/pre-receive --jar FILE (- for stdin)
set -euo pipefail
export GIT_DIR=$HOME/app.git
branch=$(git symbolic-ref --short HEAD)  # the branch that deploys
rev= jar=
if [ "${1:-}" = --jar ]; then
  jar=${2:?usage: pre-receive --jar FILE}
elif [ $# -gt 0 ]; then
  rev=$(git rev-parse --verify "$1^{commit}")
else
  while read -r _ new ref; do
    [ "$ref" = "refs/heads/$branch" ] || continue
    case $new in
      *[!0]*) rev=$new ;;
      *) echo "==> Refusing to delete $branch: it's what deploys."; exit 1 ;;
    esac
  done
  [ -n "$rev" ] || exit 0  # other branches are kept, not deployed
fi

exec 9>"$HOME/.deploy.lock" && flock 9  # one deploy at a time
release=$HOME/releases/$(date -u +%Y%m%d-%H%M%S)-${rev:0:7}${jar:+jar}
previous=$(readlink "$HOME/app" || true)
fail() {  # put the previous release back and reject the push
  trap - ERR
  echo "==> Deploy FAILED${1:+: $1}. Still running: ${previous:-nothing}"
  if [ -n "$previous" ] && [ "$(readlink "$HOME/app")" != "$previous" ]; then
    ln -sfn "$previous" "$HOME/app.new" && mv -T "$HOME/app.new" "$HOME/app"
    sudo systemctl restart app
  fi
  rm -rf "$release"
  exit 1
}
trap fail ERR

mkdir -p "$release"
if [ -n "$jar" ]; then
  echo "==> Installing a prebuilt jar in $release"
  if [ "$jar" = - ]; then cat > "$release/app.jar"; else cp "$jar" "$release/app.jar"; fi
else
  echo "==> Building ${rev:0:7} in $release"
  git archive "$rev" | tar -x -C "$release"
fi
unset GIT_DIR GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_QUARANTINE_PATH
cd "$release"
set -a; . "$HOME/app.env"; set +a
if [ -z "$jar" ]; then
  # Tests run on your computer or in CI: on the VM they'd use the live database.
  if [ -n "${BUILD_COMMAND:-}" ]; then bash -c "$BUILD_COMMAND"
  elif [ -f mvnw ]; then sh ./mvnw -B -ntp -DskipTests package
  elif [ -f gradlew ]; then sh ./gradlew --no-daemon -x test bootJar
  else fail "no mvnw or gradlew in the repository"
  fi
  if [ ! -f app.jar ]; then  # a BUILD_COMMAND may leave app.jar itself
    built=$(ls -1 target/*.jar build/libs/*.jar 2>/dev/null |
      grep -v -e '-plain\.jar$' -e '-sources\.jar$' -e '-javadoc\.jar$' | head -n 1 || true)
    [ -n "$built" ] || fail "the build made no jar in target/ or build/libs/"
    cp "$built" app.jar
  fi
fi
"$HOME/bin/app-backup" deploy >/dev/null  # the new version may migrate when it starts

echo "==> Starting the new version"
ln -sfn "$release" "$HOME/app.new" && mv -T "$HOME/app.new" "$HOME/app"
sudo systemctl restart app
url=${HEALTH_URL:-http://localhost:8000/}
deadline=$((SECONDS + 120))  # the JVM takes a few seconds to start
while [ $SECONDS -lt $deadline ]; do
  code=$(curl -s -o /dev/null -m 5 -w '%{http_code}' "$url" || true)
  case $code in 000|5??) sleep 2 ;; *) break ;; esac
  # systemd counts restarts since ours: one means the new version exited.
  [ "$(systemctl show -p NRestarts --value app)" = 0 ] ||
    fail "the new version exited (journalctl -u app -n 80)"
done
case $code in
  000|5??) fail "$url answers HTTP $code (journalctl -u app -n 80)" ;;
esac
trap - ERR
ls -1d "$HOME"/releases/*/ | head -n -3 | xargs -r rm -rf  # keep 3
echo "==> Deployed ${rev:0:7}${jar:+a prebuilt jar}: $url answers HTTP $code"
EOF
chmod +x ~/app.git/hooks/pre-receive

It keeps the three newest releases. Expect no output; the hook runs on the first push.

Start a new app#

For REPO=new: generate a project on start.spring.io with Java 25, Maven, and the starters the guestbook uses, then add its own files with starter.sh: the settings, the first Flyway migration, the Message entity and its repository, the controller, ExeDevSecurity, and two Thymeleaf templates.

rm -rf /tmp/new-app && mkdir /tmp/new-app && cd /tmp/new-app
curl -fsS https://start.spring.io/starter.tgz \
  -d type=maven-project -d javaVersion=25 \
  -d groupId=com.example -d artifactId=app -d name=app -d packageName=com.example.app \
  -d dependencies=web,thymeleaf,security,data-jpa,flyway,postgresql,actuator |
  tar -xzf - --warning=no-unknown-keyword
curl -fsS https://exe-staging.dev/deploy/spring-boot/starter.sh | bash
grep -A1 '<artifactId>spring-boot-starter-parent' pom.xml | grep -o '<version>.*</version>'
ls src/main/java/com/example/app

Expect Spring Boot 4.1.x (or newer) and AppApplication.java, ExeDevSecurity.java, GuestbookController.java, Message.java, and MessageRepository.java. Commit and push to the VM's repository. The push builds and deploys; the first build downloads the dependencies and takes about a minute:

cd /tmp/new-app
rm -f HELP.md
git init -q -b main
git add .
git -c user.name="$(hostname)" -c user.email="exedev@$(hostname).exe.xyz" commit -qm "A guestbook: Spring Boot, JPA, Flyway and exe.dev sign-in"
git push ~/app.git HEAD:main 2>&1 | grep -E '==>|ERROR'

The output ends with ==> Deployed and a commit. The code now lives in ~/app.git (the owner clones it from there), so remove the scratch copy:

cd ~ && rm -rf /tmp/new-app

Bring your app#

For a GitHub repository, read its application.properties or application.yml, its README, and its build file, then adapt ~/app.env, not the code:

  • Build. It needs mvnw or gradlew at the top. For a multi-module build, set BUILD_COMMAND to build the web module and copy its jar to app.jar, such as BUILD_COMMAND='./mvnw -B -ntp -DskipTests -pl web -am package && cp web/target/*.jar app.jar'.
  • Database. The SPRING_DATASOURCE_* lines already point at the app database. If the app uses Flyway or Liquibase, it migrates on start; if it relies on spring.jpa.hibernate.ddl-auto=update, that works too.
  • Settings. Add every property it needs without a default as an environment variable (app.mail.from is APP_MAIL_FROM). Generate secrets with openssl rand -hex 32; ask the owner for outside services' keys.
  • Actuator. Without spring-boot-starter-actuator, set HEALTH_URL=http://127.0.0.1:8000/ (or a page that answers without signing in): the hook accepts any status below 500.
  • Port. Leave SERVER_PORT=8000; the variable beats the app's own server.port.

Then deploy its default branch:

~/app.git/hooks/pre-receive HEAD

Deploy and check#

Check, for either kind of app:

systemctl is-enabled app; systemctl is-active app
readlink ~/app
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8000/
curl -s http://127.0.0.1:8081/actuator/health; echo

Expect enabled, active, the release directory, 200 (or your home page's usual status), and {"groups":["liveness","readiness"],"status":"UP"} (or nothing, for an app without Actuator). For a new app, check that the guestbook read the database, that Flyway migrated it, and that sign-in and /admin behave:

curl -s http://localhost:8000/ | grep -o -E 'No messages yet|Not signed in'
psql -XAt -d app -c 'SELECT version, success FROM flyway_schema_history'
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8000/admin
curl -s -o /dev/null -w '%{http_code}\n' -H 'X-ExeDev-Email: someone@example.com' http://localhost:8000/admin
curl -s -o /dev/null -w '%{http_code}\n' -H "X-ExeDev-Email: $(sed -n 's/^APP_ADMINS=//p' ~/app.env | cut -d, -f1)" http://localhost:8000/admin

Expect Not signed in, No messages yet, 1|t, then 302 (to exe.dev's login), 403, and 200. The headers work here because curl talks to the app directly, from inside the VM; from outside, only exe.dev's proxy can set them.

Check the backup#

Take the first backup by hand, then restore its database into a scratch database, never over app, to check that it holds what a restore needs:

latest=$(~/bin/app-backup manual)
rm -rf /tmp/restore-check && mkdir /tmp/restore-check
tar -xzf "$latest" -C /tmp/restore-check
ls -A /tmp/restore-check
git -C ~/app.git bundle verify /tmp/restore-check/app.bundle 2>&1 | grep -o 'complete history'
dropdb --if-exists restore_check && createdb restore_check
pg_restore --no-owner --dbname=restore_check /tmp/restore-check/app.dump
psql -XAt -d restore_check -c 'SELECT count(*) FROM flyway_schema_history'
dropdb restore_check && rm -rf /tmp/restore-check

Expect app.bundle, app.dump, app.env, and data; complete history; and a count of at least 1 (for an app without Flyway, count rows in one of its own tables instead).

Setup is done. Continue with Open your app.

Restore a backup

On the same VM#

On the VM, pick the archive (ls -lt ~/backups), unpack it, and swap the database while the app is stopped. The current database is kept under another name:

backup=~/backups/app-nightly-20261116-030512.tar.gz   # the one you want
rm -rf /tmp/restore && mkdir /tmp/restore && tar -xzf "$backup" -C /tmp/restore
sudo systemctl stop app
psql -X -q -d postgres -c "ALTER DATABASE app RENAME TO app_before_restore_$(date +%s)"
createdb --owner=app app
pg_restore --no-owner --role=app --dbname=app /tmp/restore/app.dump
sudo systemctl start app

Open the app and check your data. Files from ~/data and the old app.env are in /tmp/restore too, if you need them. When you're sure, drop the old copy: psql -d postgres -c 'DROP DATABASE app_before_restore_<number>' (psql -l lists it). If the backup is older than the code's migrations, Flyway applies the missing ones when the app starts.

On a new VM#

Create the VM and follow Set up by hand up to, but not including, "Get the code". Copy the archive over from your computer (scp app-nightly-20261116-030512.tar.gz my-spring-boot.exe.xyz:), then on the VM put back the repository, the settings, the files, and the database, and give the app role the password the old settings use:

rm -rf /tmp/restore && mkdir /tmp/restore && tar -xzf ~/app-nightly-20261116-030512.tar.gz -C /tmp/restore
git clone --bare /tmp/restore/app.bundle ~/app.git && git -C ~/app.git remote remove origin
install -m 600 /tmp/restore/app.env ~/app.env
rm -rf ~/data && cp -a /tmp/restore/data ~/data
pass=$(sed -n 's/^SPRING_DATASOURCE_PASSWORD=//p' ~/app.env)
echo "ALTER ROLE app PASSWORD :'pass'" | psql -X -q -d postgres -v ON_ERROR_STOP=1 -v pass="$pass"
dropdb app && createdb --owner=app app
pg_restore --no-owner --role=app --dbname=app /tmp/restore/app.dump

Then follow Add the deploy hook and deploy with ~/app.git/hooks/pre-receive HEAD. If the new VM has a different name, nothing in ~/app.env needs to change. On your computer, point the exe remote at it: git remote set-url exe <new-vm>.exe.xyz:app.git.

Update Spring Boot, Java, and the VM
  • Spring Boot and dependencies travel through Git. On your computer, raise the spring-boot-starter-parent version in pom.xml (or the org.springframework.boot plugin in build.gradle), run your tests, commit, and push. Read the release notes before a new minor version; Spring Boot 4.1 gets open-source fixes until mid-2027.
  • Maven or Gradle: ./mvnw wrapper:wrapper -Dmaven=<version> or ./gradlew wrapper --gradle-version <version>, then commit the wrapper files.
  • Java updates come with Ubuntu's: sudo apt-get update && sudo apt-get upgrade -y, then sudo systemctl restart app to run the new JVM. For Java 29, the next LTS, install openjdk-29-jdk-headless when Ubuntu carries it and switch with sudo update-alternatives --config java.
  • PostgreSQL minor releases come with the same apt-get upgrade; for major versions, see PostgreSQL.

Dependencies pile up in ~/.m2/repository (or ~/.gradle/caches); deleting them is safe, and the next build downloads what it needs.

Something not working?

On the VM, the app's logs:

journalctl -u app -n 100 --no-pager
  • git push says Deploy FAILED and pre-receive hook declined. The lines above it are the error: a compile error from Maven or Gradle, or a new version that wouldn't start. The running version didn't change; fix it and push again.
  • Deploy FAILED: the new version exited. Spring Boot refused to start. journalctl -u app -n 80 shows the cause under APPLICATION FAILED TO START, often a missing setting, a Flyway migration that failed, or Schema-validation: missing column (an entity changed without a migration).
  • Could not transfer metadata ... HTTP Status: 401 warnings in the build. Flyway's POM lists repositories that need a login; Maven falls back to Maven Central, and the build goes on. Ignore them.
  • no mvnw or gradlew in the repository. Commit the wrapper (mvn wrapper:wrapper or gradle wrapper on your computer), or set BUILD_COMMAND.
  • Redirects go to http:// or to localhost:8000. The app isn't reading the proxy's headers: check that SERVER_FORWARD_HEADERS_STRATEGY=native is in ~/app.env, and that the app doesn't set server.forward-headers-strategy=none itself.
  • 403 Forbidden on a form post. Spring Security's CSRF check: the form needs the _csrf field, which Thymeleaf adds to th:action forms, and JavaScript fetch calls need the token in a header.
  • The app gets slower, then restarts. It's running out of heap: journalctl -u app | grep -i OutOfMemory. Raise -XX:MaxRAMPercentage, resize the VM, or find what's holding memory with jcmd $(pgrep -f app.jar) GC.class_histogram | head -20.
  • Disk filling up. du -sh ~/releases/* ~/backups ~/.m2 ~/.gradle 2>/dev/null; the hook keeps three releases and fourteen backups of each kind.

Frequently asked questions#

Maven or Gradle?

Either. The deploy hook runs the wrapper your repository has, ./mvnw package or ./gradlew bootJar, so the VM needs no build tool of its own and builds with the version the project pins. The starter uses Maven; a Gradle project from start.spring.io deploys unchanged.

Should I build on the VM or in CI?

On the VM, to start with: git push is the whole deploy and rebuilds reuse the dependencies in ~/.m2 or ~/.gradle. Tests belong on your computer or in CI, because the VM's only database is the live one. To ship the jar CI tested, see Build on your computer or in CI.

Does a deploy drop requests?

For a few seconds. The old version finishes requests in flight, then the new JVM starts, which takes the starter about 12 seconds on a 2-CPU VM; requests in that gap get an error page from exe.dev's proxy. Spring Boot's AOT cache shortens the start. Zero-downtime deploys need two copies behind a proxy of your own, which is more than most apps need.

How much memory does it need?

The starter uses about 350 MB at rest. JAVA_OPTS in ~/app.env caps the heap at 40% of the VM's memory, so PostgreSQL and the rest of the JVM fit beside it; see Java's memory on the VM.

Can I use a GraalVM native image?

Yes, but you don't need one on a VM that's always on. A native image starts in a fraction of a second and uses less memory; it takes minutes and several GB of memory to build, and libraries that use reflection may need hints. Build it on your computer or in CI, for Linux x86-64, and change ExecStart to run the binary.

Do I need Docker?

No. Spring Boot builds one jar that runs on any Java 25, and systemd starts it at boot, restarts it if it crashes, and keeps its logs. If your project ships a docker-compose.yml, see Docker Compose.

Does it sleep, or have cold starts?

No. The VM is always on, so the JVM stays warm, @Scheduled methods run on time, and WebSocket connections stay open. You pay for the VM, not per request; see exe.dev plans.

Updated Nov 16, 2026 · tested end to end Nov 16, 2026 · Markdown · manifest.json · Something wrong? Tell us