VPS Tutorials
Spring Boot on a VPS: JDK 25, JVM memory, systemd and Nginx
Deploy Spring Boot with a supported JDK 25 distribution, an executable jar, explicit JVM memory budgets, systemd and Nginx HTTPS. Configure graceful shutdown, layered images, private health checks and migration-aware rollback.

Compared with the Node.js, Python and Go deployment guides, Java deserves a separate memory budget. The JVM has heap and native overhead: class metadata, thread stacks, compiled code and direct buffers. Reserving address space does not immediately consume the same amount of physical memory, and other runtimes also have overhead.
This guide uses Ubuntu 24.04/26.04 and Spring Boot 4, with build artifacts produced outside the VPS, systemd supervision and Nginx HTTPS. Size and test the actual application rather than treating a small-machine failure as inevitable.
Memory is often an important constraint, but CPU, disk, connection pools and external dependencies can also cause failures.
| Workload | Example starting VPS | Qualification |
|---|---|---|
| One Spring Boot app | 2 vCPU / 2 GB | A practical starting point, not a guaranteed minimum |
| App and database together | 4 vCPU / 4 GB | Budget both services separately |
| Several JVM services | 4 vCPU / 8 GB+ | Each has its own overhead |
| Elasticsearch/data components | 8 GB+ | Requires a separate workload assessment |
The source illustrates why 1 GB can be tight:
- 256–512 MB of heap;
- 200–400 MB of non-heap overhead;
- 100–200 MB for OS and SSH;
- additional tens of MB for Nginx.
These ranges are estimates, not measured requirements. Leave peak headroom and use the sizing guide. Swap/ZRAM can buffer pressure, but does not replace sufficient capacity.
LTS reference releases are 17 (2021), 21 (2023) and 25 (September 2025). The source's universal October 2032 support claim is inaccurate: support depends on distributor and terms. Oracle's roadmap lists JDK 25 Premier Support through September 2030 and Extended Support through September 2033; these are not promises for every OpenJDK package. Check your distribution's actual update policy.
sudo apt update
sudo apt install -y openjdk-25-jdk
java -version
First use apt-cache policy to confirm openjdk-25-jdk exists in enabled, trusted repositories for the actual Ubuntu release. Do not assume every Ubuntu/Debian release supplies it or that the source's 25.0.4 remains current. If unavailable, use a maintained distribution such as Temurin with documented installation and updates.
The September source limited Spring Boot 4.1.1 to Java 17–26 and warned against 27. The official requirements checked for this edition describe Spring Boot 4.1.2 as Java 17–27 compatible. Check the requirements for the exact locked Boot version and integrations.
- JDK 25 LTS is a reasonable production option with a supported distributor.
- JDK 26 is non-LTS; Oracle's reference support window ended in September 2026.
- JDK 27 compatibility must be checked against your Boot version, not rejected using an old range.
The VPS needs a Java runtime, but Maven/Gradle compilation can stay in CI.
mvn package may use substantial CPU/memory; build locally or in CI:
mvn clean package -DskipTests
# 产物
ls target/*.jar
-DskipTests is an explicit test skip. Run the release's required tests in CI before using that artifact; this example is not evidence that tests were run.
Inspect the executable Boot jar:
# 能直接跑(含内嵌 Tomcat 和全部依赖)
java -jar target/myapp-0.0.1.jar
# 检查有没有 Main-Class 和 Start-Class
unzip -p target/myapp-0.0.1.jar META-INF/MANIFEST.MF
Start-Class identifies the application class, while the manifest's Main-Class selects the Boot launcher. Configure spring-boot-maven-plugin correctly; an ordinary jar may lack the launcher or dependencies.
GraalVM native images are an alternative. Check your Boot/GraalVM version requirements, including the source's 25+ example, and test reflection, proxies and native metadata. Build cost and compatibility differ; millisecond startup and tiny memory are workload-specific outcomes, not guarantees.
The source records these JVM ergonomic values:
MaxRAMPercentage = 25.0 # 最多用 25% 的内存做堆
InitialRAMPercentage = 1.5625 # 初始堆
MinRAMPercentage = 50.0
UseContainerSupport = true # 默认开启
They are historical observations, not measurements repeated for this edition. Ergonomics depend on JDK, collector, system and cgroup limits. A percentage controls the heap, not total process memory. Either explicit heap bounds or a validated percentage plus a hard process/container budget can work.
Example for a 2 GB VPS:
java \
-Xms512m -Xmx768m \
-XX:MaxMetaspaceSize=192m \
-XX:MaxDirectMemorySize=128m \
-Xss512k \
-XX:+ExitOnOutOfMemoryError \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/srv/app/shared/dumps \
-jar app.jar
-Xms/-Xmxset initial/maximum heap. Here 512m/768m is a starting example; equal bounds can reduce resizing but are not mandatory.- Keep
-Xmxbelow total capacity. Setting-Xmxto half the machine or more can still leave inadequate room for native memory and other services. -XX:MaxMetaspaceSizebounds Metaspace. Measure the actual class workload: too small a cap causes its own OOM, while an unlimited setting is constrained by available memory.-Xss512kreduces stack capacity per thread; test recursion and thread counts to avoid StackOverflowError.-XX:+ExitOnOutOfMemoryErrorexits on supported JVM OutOfMemoryError paths soRestart=alwayscan restart. It does not prevent a kernel OOM kill or diagnose the cause.-XX:+HeapDumpOnOutOfMemoryErrorcreates a sensitive, potentially heap-sized dump. Precreate a private writable dump directory, reserve space and apply retention. A kernel SIGKILL may leave no dump.
java -Xlog:gc -jar app.jar
# 启动日志第一行会打印 Using G1 / Using Serial
- G1 is common on suitable server configurations.
- SerialGC may reduce overhead with a small heap; evaluate
-XX:+UseSerialGCon 1–2-core machines rather than assuming it is best.
Compare pauses and throughput with -Xlog:gc under representative traffic.
Save /etc/systemd/system/myapp.service:
[Unit]
Description=Spring Boot App
After=network.target
[Service]
Type=simple
User=appuser
Group=appuser
WorkingDirectory=/srv/app/current
EnvironmentFile=/srv/app/shared/.env
ExecStart=/usr/bin/java \
-Xms512m -Xmx768m \
-XX:MaxMetaspaceSize=192m \
-XX:+ExitOnOutOfMemoryError \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/srv/app/shared/dumps \
-Duser.timezone=Asia/Shanghai \
-Dspring.profiles.active=prod \
-jar /srv/app/current/app.jar
SuccessExitStatus=143
Restart=always
RestartSec=5
KillSignal=SIGTERM
TimeoutStopSec=30
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp
MemoryMax=1500M
LimitNOFILE=65535
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/srv/app/shared
[Install]
WantedBy=multi-user.target
Create appuser, releases/shared directories, a real current target and mode-600 environment file before starting. Keep writable dumps/uploads separate from code. This unit does not include every bound from the standalone JVM command; add approved direct-memory/stack settings deliberately.
SuccessExitStatus=143accepts128+15, a conventional SIGTERM exit value. Behavior depends on actual exit handling; it avoids misclassifying that exit insystemctl status.MemoryMax=1500Mmust accommodate-Xmxplus native overhead and margin, not equal-Xmx.-Duser.timezone=Asia/Shanghaiselects Asia/Shanghai; replace it with the required IANA zone or UTC. An eight-hour offset is regional, not universal, and the JDK normally includes timezone rules.WorkingDirectoryaffects relativeconfig/application.yml. Put production values inshared/.envor explicit external paths.
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
sudo systemctl status myapp
Inspect journalctl -u myapp -n 50 --no-pager and the service-start checklist.
systemctl restart sends SIGTERM to the old process. Current Boot documentation says graceful shutdown is enabled by default for supported embedded servers; the source's claim that Boot 4 always stops immediately is outdated. Make policy explicit in application.yml:
server:
shutdown: graceful
spring:
lifecycle:
timeout-per-shutdown-phase: 20s
The 20-second value is per shutdown phase, not necessarily a global total. Allow enough room under TimeoutStopSec for all phases, background workers and cleanup; increase the source's 30-second service deadline if necessary. A single restart still has a listening gap.
Set the application to bind 127.0.0.1 explicitly, for example SERVER_ADDRESS=127.0.0.1 in its environment. Spring Boot's default 8080 does not imply a loopback-only address.
upstream springapp {
server 127.0.0.1:8080;
keepalive 32;
}
server {
listen 80;
listen [::]:80;
server_name app.example.com;
client_max_body_size 20m;
access_log /var/log/nginx/app.access.log;
error_log /var/log/nginx/app.error.log warn;
location / {
proxy_pass http://springapp;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
}
}
sudo nginx -t && sudo systemctl reload nginx
Configure server.forward-headers-strategy so request.getScheme() reflects forwarded HTTPS instead of http:
server:
forward-headers-strategy: framework
Trust only the proxy and keep the backend private; otherwise clients can spoof forwarded values. See redirect loops. Add Certbot after checking DNS, ports and renewal, or use Caddy. Low ports require privileges/capabilities; using the proxy avoids granting those to the Java application.
Layered jars allow unchanged dependencies to reuse Docker cache. They do not guarantee a particular build time:
FROM eclipse-temurin:25-jre AS builder
WORKDIR /app
COPY target/*.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --destination extracted
FROM eclipse-temurin:25-jre
WORKDIR /app
RUN useradd -r -u 1001 appuser
COPY --from=builder /app/extracted/dependencies/ ./
COPY --from=builder /app/extracted/spring-boot-loader/ ./
COPY --from=builder /app/extracted/snapshot-dependencies/ ./
COPY --from=builder /app/extracted/application/ ./
USER appuser
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=70", "-jar", "app.jar"]
Ensure the COPY selects exactly the intended executable jar and that the packaged tools mode/layer index exists. The extracted app.jar references extracted dependencies; this differs from launching an arbitrary ordinary jar.
- Prefer a maintained
jreruntime to ajdktoolchain when compilation is unnecessary;eclipse-temurinis one option. Size savings vary. -XX:MaxRAMPercentage=70needs a real--memoryor Compose memory limit. A 70% heap can still leave insufficient native headroom.- Retain
USER appuser, private secrets and restrictive mounts. Non-root helps but is not complete host isolation. - Use a tested concrete version/digest rather than
latest.
See Compose limits and Docker disk cleanup.
Add Actuator:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
management:
endpoints:
web:
exposure:
include: health,info
endpoint:
health:
show-details: never
Keep show-details: never unless authenticated operators have a specific need. Details may reveal internal component information. Restrict /actuator/: the source's catch-all Nginx proxy also forwards it publicly. Add a deny/404 location before proxy routing, or bind management to a separate private port with appropriate authorization. Check health locally; systemd active status alone is not an application health probe.
- OOM: compare
-Xmxplus native usage to the process and VPS budgets, evaluate-XX:MaxMetaspaceSize, and use-XX:+ExitOnOutOfMemoryErrorfor JVM OOM exits. Inspectdmesg | grep -i oomfor kernel kills. - Slow startup: examine phase timings and retries to database, Redis or external APIs. Thirty seconds alone does not identify the cause.
- Changing settings: environment/command-line values can override packaged
application.yml. Supply production configuration throughEnvironmentFile:
SPRING_DATASOURCE_URL=jdbc:postgresql://127.0.0.1:5432/appdb
SPRING_PROFILES_ACTIVE=prod
SPRING_DATASOURCE_URL maps to spring.datasource.url. Restart after editing environment files. The unit's explicit -Dspring.profiles.active can override the corresponding environment value; remove or align it when changing profiles.
- Uncollectable memory: use
jcmd <pid> GC.heap_dumpwith a JDK diagnostic tool and private output path, or the OOM dump. Inspect unbounded caches/collections, unclosed connections and ThreadLocal retention. Swap does not fix a leak. - Logs fill disk: the source console output goes into the journal:
sudo journalctl --vacuum-size=500M
sudo sed -i 's/^#\?SystemMaxUse=.*/SystemMaxUse=500M/' /etc/systemd/journald.conf
sudo systemctl restart systemd-journald
Vacuum removes archived logs; persistent limits need an effective journald setting. Prefer a reviewed drop-in, and verify that the original sed command actually finds the setting. Separate application files need their own rotation.
- 502: inspect
systemctl status myappandlocalhost/127.0.0.1address-family differences; see 502/504. - Port occupied: identify the owner using
sudo ss -lntp 'sport = :8080'; see port conflicts and logs.
Original artifact-transfer workflow:
#!/usr/bin/env bash
set -euo pipefail
HOST=deploy@your-vps
RELEASE=$(date +%Y%m%d-%H%M%S)
TARGET=/srv/app/releases/$RELEASE
# 1. 本地打包
mvn clean package -DskipTests
JAR=$(ls target/*.jar | grep -v original | head -1)
# 2. 传输
ssh "$HOST" "mkdir -p $TARGET"
scp "$JAR" "$HOST:$TARGET/app.jar"
# 3. 切换并重启
ssh "$HOST" "ln -sfn $TARGET /srv/app/current && sudo systemctl restart myapp"
# 4. 清理旧版本,保留最近 5 个
ssh "$HOST" "ls -1dt /srv/app/releases/* | tail -n +6 | xargs -r rm -rf"
grep -v original filters the original artifact emitted by spring-boot-maven-plugin: app.jar is the repackaged jar, app.jar.original the original. Prefer one explicit verified artifact over ls/head selection when several jars exist. Run release tests before using the test-skipping build, retain set -euo pipefail and never switch current after a failed build.
Save the previous symlink target, back up data/secrets/uploads, verify checksum and ownership, switch and restart, then check the running commit and local/public health. On failure restore the old target and restart. Clean old directories only after verification, keeping both active and rollback artifacts. Database migrations must be compatible: jar rollback neither restores data nor guarantees immediate availability. Use a tested two-instance proxy switch for continuous service.
See PostgreSQL and Redis. Bind same-host services to 127.0.0.1 and use an SSH tunnel when needed; follow database exposure guidance.
HikariCP's usual maximum of 10 connections is a default to review, not a sizing rule. Budget the sum of pools across instances and other clients against max_connections, memory and actual throughput.
- RackNerd annual plans are options to verify for a small app; the 2 GB example still needs measurement.
- Vultr offers hourly flexibility; check whether resizing needs downtime or disk migration.
- Contabo memory offers require actual I/O and renewal-price checks.
- DMIT CN2 GIA products address mainland-China routing; stability and worldwide speed must not be assumed.
Ubuntu/Debian can both host Java, but verify openjdk-25-jdk availability and support for the exact release. See distribution selection.
- Node.js for a frontend/BFF;
- Go deployment for artifact comparison;
- VPS sizing for JVM budgeting;
- Production Compose for limits and rollback;
- Restore drills for recovery beyond the jar.