Linux Server

How I Fixed a Spring Boot Application That Kept Getting Killed by the Linux OOM Killer

Recently, my personal blog started going offline several times a day. The application was built with Spring Boot and deployed on a small Ubuntu VPS with 2GB RAM.

At first, I thought the problem was related to Java memory settings or PostgreSQL. However, the real reason was different.

The Problem

The application suddenly stopped responding. Nginx returned 502 Bad Gateway errors because the Java process was no longer running.

I checked the system logs and found many messages like this:

Out of memory: Killed process xxxx (java)

Linux was automatically killing my Spring Boot application.

Checking Memory Usage

The first thing I did was check memory usage.

free -h

The output looked similar to this:

Mem: 1.9Gi total
Used: 1.1Gi
Available: 569Mi

Swap: 0B

At first glance, memory usage did not look terrible. The server still had available memory.

However, one detail immediately stood out.

The server had no swap space.

Investigating OOM Events

To confirm my suspicion, I checked kernel logs.

journalctl -k | grep -i oom

The output showed multiple entries:

oom-kill: task=java
Out of memory: Killed process xxxx (java)

This confirmed that Linux was terminating the Java process because the system ran out of memory.

My Spring Boot Configuration

The application already had memory limits configured.

java -Xms256m -Xmx512m -XX:+UseG1GC -jar app.jar

Systemd also limited the service:

MemoryLimit=1200M

At this point, I realized that the problem was not an unlimited Java heap.

The real issue was that the VPS had only 2GB RAM and no swap.

The Fix

I created a 2GB swap file.

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

To make it permanent:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

After that:

free -h

showed:

Swap: 2.0G

Result

The difference was immediate.

The Spring Boot application stopped crashing and remained stable.

No new OOM events appeared in the kernel logs.

Lessons Learned

If you run Spring Boot on a small VPS:

  • Always configure a maximum heap size.
  • Always create swap space.
  • Check kernel OOM logs before changing application code.
  • Do not assume Java is leaking memory.
  • Monitor memory usage regularly.

Sometimes the simplest infrastructure issue causes the biggest production problem.

In my case, adding a 2GB swap file solved days of instability in less than five minutes.