Muhammad Fari Madyan
Hire me
Spring Boot · part 4 of 8

Java Spring Boot + React E-Learning: Single VPS Production Deployment with Docker Compose, Host Nginx Reverse Proxy & SSL Let's Encrypt

A battle-tested, step-by-step production deployment guide for the Java 21 Spring Boot 3 & React 19 E-Learning platform on a single Ubuntu VPS: Docker Compose production topology, Host Nginx SSL termination with Certbot, Swap memory tuning, WebSocket proxying, automated daily database backups, and zero-downtime redeployment scripts.

Muhammad Fari Madyan

· 12 min read

Baca dalam Bahasa Indonesia →

Introduction: Moving from Local Containers to Production Reality

In Part 2 and Part 3 of this series, we hardened our open-source companion platform, mfarim/spring-elearning-react, against path traversal vulnerabilities and added transparent refresh token rotation, declarative method-level RBAC, and Bucket4j rate limiting.

Now comes the final operational milestone: taking the system live on a real public server.

For most independent schools, colleges, and startups, a multi-cluster Kubernetes setup or several managed AWS instances ($150–$300/month) is overkill and too expensive. A well-tuned Single Virtual Private Server (VPS) costing $6–$15/month can comfortably serve thousands of exam candidates, as long as it has proper container isolation, reverse proxying, and caching.

In this guide, I walk through the exact deployment blueprint I used to put Spring E-Learning & CBT on a single Ubuntu VPS under its dedicated production subdomain: 👉 https://spring-elearning.mfarim.com

┌─────────────────────────────────────────────────────────────────────────────┐ │ PRODUCTION DEPLOYMENT OVERVIEW │ ├──────────────────────────────────────┬──────────────────────────────────────┤ │ Target Environment │ Single Ubuntu VPS (22.04 / 24.04 LTS)│ │ Production URL │ https://spring-elearning.mfarim.com │ │ Backend Service │ Java 21 LTS + Spring Boot 3.4.3 API │ │ Frontend Service │ React 19 SPA + Vite 6 + Tailwind v4 │ │ Container Topology │ Docker Compose Production (4 Pods) │ │ Reverse Proxy & SSL │ Host Nginx + Let's Encrypt (Certbot) │ │ Internal Port Mapping │ 127.0.0.1:8088 -> Container Port 80 │ │ Database & Cache Isolation │ PostgreSQL 16 & Redis 7 (Internal) │ │ Data Persistence │ Docker Named Volumes (DB & Storage) │ │ Backup & Maintenance │ Automated Daily Cronjob (pg_dump) │ └──────────────────────────────────────┴──────────────────────────────────────┘

1. Single VPS Deployment Architecture

On a shared or single VPS, Nginx installed on the host operating system controls ports 80 (HTTP) and 443 (HTTPS), handles TLS termination via Let's Encrypt, and forwards requests internally to Docker on a dedicated loopback port (127.0.0.1:8088):

┌─────────────────────────────────────────────────────────────────────────────┐ │ HOST OPERATING SYSTEM (VPS) │ │ │ │ Public Internet │ │ │ │ │ HTTPS :443 (spring-elearning.mfarim.com) │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ HOST NGINX REVERSE PROXY │ │ │ │ • SSL Termination via Let's Encrypt (Certbot) │ │ │ │ • WebSocket Upgrade Headers (HTTP/1.1) │ │ │ │ • Request Payload Buffering (client_max_body_size 50M) │ │ │ └──────────────────────────────────┬──────────────────────────────────┘ │ │ │ │ │ Proxy Pass to │ │ 127.0.0.1:8088 │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ DOCKER CONTAINER NETWORK │ │ │ │ │ │ │ │ ┌──────────────────────┐ ┌──────────────────────────┐ │ │ │ │ │ elearning-frontend │ │ elearning-backend │ │ │ │ │ │ (Nginx + React 19) │──/api/*──▶│ (Spring Boot 3.4.3) │ │ │ │ │ │ Listening on :8088 │──/ws/*───▶│ Port 8080 (Internal) │ │ │ │ │ └──────────────────────┘ └────────────┬─────────────┘ │ │ │ │ │ │ │ │ │ ┌────────────────────────────┼───────────┐ │ │ │ │ ▼ ▼ ▼ │ │ │ │ ┌───────────────────┐ ┌───────────────┐ ┌───────┐ │ │ │ │ │ elearning-postgres│ │elearning-redis│ │Storage│ │ │ │ │ │ PostgreSQL 16 │ │ Redis 7 │ │Volume │ │ │ │ │ │ (Port 5432 Int.) │ │(Port 6379 Int)│ │/upload│ │ │ │ │ └───────────────────┘ └───────────────┘ └───────┘ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘

Key Architectural Advantages:

  1. Coexistence with Existing Websites: Ports 80 and 443 stay with the Host Nginx, so you can host your personal portfolio, blog (mfarim.com), or other APIs side by side on the same VPS without port collisions.
  2. Database Isolation: The PostgreSQL and Redis containers do not expose ports to the public internet (0.0.0.0), which blocks brute-force database attacks.
  3. Zero Data Loss on Redeploy: All uploaded PDFs, question images, and relational tables live in Docker named volumes (postgres_data, redis_data, backend_storage).

2. Server Sizing & Initial Preparation

Minimum Recommended Hardware Specifications:

  • Operating System: Ubuntu 22.04 LTS or 24.04 LTS (64-bit)
  • CPU: 2 vCPUs minimum
  • RAM: 2 GB minimum (Important: with 2 GB RAM you must enable 2–4 GB of swap, or the Linux OOM Killer may terminate Maven or JVM processes during compilation). Recommended: 4 GB RAM.
  • Storage: 25 GB+ SSD/NVMe

Step 1: System Update & Swap Memory Configuration

Connect to your VPS via SSH:

BASH
ssh root@<YOUR_VPS_PUBLIC_IP>

Update system packages and install basic utilities:

BASH
sudo apt update && sudo apt upgrade -y
sudo apt install -y curl wget git ufw htop ca-certificates gnupg lsb-release

Allocating Swap Memory (Critical for JVM on 2 GB RAM):

Compiling TypeScript with Vite and starting the Java 21 Virtual Machine can cause memory spikes during boot. Configure a 4 GB swap file:

BASH
# Check existing swap
sudo swapon --show

# Create 4 GB swapfile
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

# Make swap persistent across reboots
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# Tune swappiness for optimal memory caching
sudo sysctl vm.swappiness=10
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf

Firewall Hardening with UFW:

Block all inbound traffic except SSH, HTTP, and HTTPS:

BASH
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp      # SSH (adjust if using custom port)
sudo ufw allow 80/tcp      # HTTP
sudo ufw allow 443/tcp     # HTTPS
sudo ufw enable

3. Subdomain DNS Configuration

Before you generate SSL certificates, point your subdomain to your VPS IP address at your DNS provider (Cloudflare, Namecheap, Route 53, etc.):

Record TypeHostname / SubdomainTarget / ValueTTLNote
Aspring-elearning<YOUR_VPS_PUBLIC_IP>Auto / 300sIf using Cloudflare, set to DNS Only (Grey Cloud) during initial Certbot validation.

Verify DNS propagation:

BASH
dig +short spring-elearning.mfarim.com
# Must return your VPS public IP address

4. Installing Docker, Nginx & Certbot

Install Docker Engine & Compose via Official Docker Keyring:

BASH
# Remove outdated packages
sudo apt remove -y docker docker-engine docker.io containerd runc

# Add official Docker GPG key
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

# Add official Docker repository
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Install Docker CE and Compose plugin
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# Enable and start Docker service
sudo systemctl enable docker
sudo systemctl start docker

# Verify installation
docker compose version

Install Host Nginx & Certbot:

BASH
sudo apt install -y nginx certbot python3-certbot-nginx
sudo systemctl enable nginx
sudo systemctl start nginx

5. Repository Setup & Production Environment (.env)

Clone the repository into a standard server location, such as /var/www/spring-elearning:

BASH
sudo mkdir -p /var/www/spring-elearning
sudo chown -R $USER:$USER /var/www/spring-elearning

git clone https://github.com/mfarim/spring-elearning-react.git /var/www/spring-elearning
cd /var/www/spring-elearning

Configure Production Secrets in .env:

Create the production environment file:

BASH
cp .env.example .env
nano .env

Fill .env with strong production values:

INI
# ==============================================================================
# Production Environment Variables
# ==============================================================================

# --- Database Credentials ---
POSTGRES_DB=elearning
POSTGRES_USER=elearning_prod_user
# Generate strong 32-char password via: openssl rand -hex 16
POSTGRES_PASSWORD=replace_with_openssl_rand_hex_16_output

# --- JWT Signing Key (Must be valid 256-bit Base64 string!) ---
# Generate via: openssl rand -base64 32
JWT_SECRET=replace_with_openssl_rand_base64_32_output

# --- Container Storage Paths ---
STORAGE_UPLOAD_DIR=/app/storage/uploads

# --- Internal Port Forwarding to Host Nginx ---
FRONTEND_PORT=8088
BACKEND_PORT=8080

[!IMPORTANT] Generating a Cryptographically Secure JWT Secret: Run openssl rand -base64 32 in your terminal and paste the resulting string into JWT_SECRET= in .env.

Update (Nov 2026): The production compose file now refuses to start without JWT_SECRET and POSTGRES_PASSWORD, and a publicly known example secret is rejected. Other settings added later: APP_DEMO_MODE, APP_REGISTRATION_ENABLED, SPRINGDOC_ENABLED, LOG_LEVEL_APP (Part 5); APP_REFRESH_COOKIE_SECURE and CSP_*_SRC_EXTRA (Part 7); and APP_REALTIME_MODE, APP_RATE_LIMIT_STORE, APP_STORAGE_TYPE for running several instances.


6. Running Production Docker Compose

Use docker-compose.prod.yml, which binds the frontend to the loopback address 127.0.0.1:8088 and isolates the database:

BASH
docker compose -f docker-compose.prod.yml up -d --build

Verify Container Health:

BASH
docker compose -f docker-compose.prod.yml ps

All 4 containers must be running, and the three with healthchecks must report healthy:

  • elearning-postgres (healthy)
  • elearning-redis (healthy)
  • elearning-backend (healthy)
  • elearning-frontend (up, bound to 127.0.0.1:8088->80/tcp)

Verify Startup Logs:

BASH
docker compose -f docker-compose.prod.yml logs -f backend

Look for:

TEXT
Tomcat started on port 8080 (http) with context path '/'
Started BackendApplication in 8.412 seconds

Verify Internal Spring Boot Actuator Health:

BASH
curl -s http://127.0.0.1:8088/actuator/health
# Expected output: {"status":"UP"}

7. Host Nginx Virtual Host Configuration

Next, configure the Host Nginx reverse proxy to route traffic from spring-elearning.mfarim.com to 127.0.0.1:8088, with support for 50MB file uploads and long-lived WebSocket connections.

Create Virtual Host File:

BASH
sudo nano /etc/nginx/sites-available/spring-elearning.mfarim.com

Insert the following configuration:

NGINX
server {
    server_name spring-elearning.mfarim.com;

    # Allow up to 50MB for learning materials & syllabus PDFs
    client_max_body_size 50M;

    access_log /var/log/nginx/spring-elearning_access.log;
    error_log /var/log/nginx/spring-elearning_error.log;

    # Frontend SPA & REST API
    location / {
        proxy_pass http://127.0.0.1:8088;
        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;
    }

    # Real-Time WebSocket STOMP for CBT Proctoring Telemetry
    location /ws {
        proxy_pass http://127.0.0.1:8088/ws;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        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_read_timeout 86400s;
        proxy_send_timeout 86400s;
    }

    listen 80;
}

Update (Nov 2026): If the domain is proxied through Cloudflare (orange cloud), restore the visitor IP here and overwrite X-Forwarded-For instead of appending to it, otherwise every user shares Cloudflare's IPs for rate limiting. Since PR #6 the backend trusts X-Forwarded-For only from internal proxies (server.forward-headers-strategy: native). Details in Part 5.

NGINX
set_real_ip_from 173.245.48.0/20;   # ...add every Cloudflare IPv4/IPv6 range
real_ip_header CF-Connecting-IP;
proxy_set_header X-Forwarded-For $remote_addr;   # instead of $proxy_add_x_forwarded_for

Enable Site and Verify Syntax:

BASH
sudo ln -s /etc/nginx/sites-available/spring-elearning.mfarim.com /etc/nginx/sites-enabled/
sudo nginx -t

# If output says "syntax is ok", reload Nginx:
sudo systemctl reload nginx

8. Installing Let's Encrypt SSL (HTTPS) with Certbot

Issue a free, automatically renewed TLS/SSL certificate with an HTTP-to-HTTPS redirect:

BASH
sudo certbot --nginx -d spring-elearning.mfarim.com

Certbot prompts for:

  1. Email address: For urgent renewal notifications.
  2. Terms of Service: Accept with Y.

Certbot then solves the ACME challenge, provisions the certificate, and adds the HTTPS redirect to your Nginx config.

Test Automated SSL Renewal:

BASH
sudo certbot renew --dry-run

Output: Congratulations, all simulated renewals succeeded.


9. Production Feature Verification Checklist

Open your browser and go to: 👉 https://spring-elearning.mfarim.com

Run through this 5-point verification checklist:

Verification ItemActionExpected Result
1. SSL LockInspect browser address barValid certificate issued by Let's Encrypt, TLS 1.3 negotiated
2. Admin LoginLog in with [email protected] / passwordOpens the Admin Dashboard with statistics
3. Refresh TokenInspect Network tab during active sessionBackground /api/v1/auth/refresh keeps session alive
4. File UploadUpload a 15MB PDF module in the Teacher PanelFile uploads without an HTTP 413 error
5. Live WebSocketOpen CBT Exam Monitor (/exams/:id/monitor)Browser console confirms STOMP connected

10. Automated Redeployment Script (deploy.sh)

To make future updates painless, create a deployment script at /var/www/spring-elearning/deploy.sh:

BASH
cat << 'EOF' > /var/www/spring-elearning/deploy.sh
#!/bin/bash
set -e

echo "🚀 [1/4] Pulling latest commits from GitHub..."
cd /var/www/spring-elearning
git pull origin main

echo "📦 [2/4] Building production images and restarting containers..."
docker compose -f docker-compose.prod.yml build
docker compose -f docker-compose.prod.yml up -d --remove-orphans

echo "🧹 [3/4] Pruning dangling images..."
docker image prune -f

echo "✅ [4/4] Verifying container health..."
sleep 10
docker compose -f docker-compose.prod.yml ps

echo "🎉 Deployment successfully completed!"
EOF

chmod +x /var/www/spring-elearning/deploy.sh

Whenever you push new features or bug fixes, run:

BASH
./deploy.sh

11. Automated Database Backups & Maintenance

Protect student grades, attendance, and exam results with an automated daily compressed backup.

Create the Backup Script:

BASH
sudo mkdir -p /var/backups/elearning
cat << 'EOF' > /var/backups/elearning/backup-db.sh
#!/bin/bash
BACKUP_DIR="/var/backups/elearning"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
FILENAME="$BACKUP_DIR/elearning_db_$TIMESTAMP.sql.gz"

# Dump PostgreSQL database directly from Docker container and compress
docker exec elearning-postgres pg_dump -U elearning_prod_user elearning | gzip > "$FILENAME"

# Prune backups older than 14 days
find "$BACKUP_DIR" -type f -name "*.sql.gz" -mtime +14 -delete

echo "Database backup completed: $FILENAME"
EOF

chmod +x /var/backups/elearning/backup-db.sh

Schedule Cronjob (Runs Daily at 02:00 AM):

BASH
sudo crontab -e

Append:

CRON
0 2 * * * /var/backups/elearning/backup-db.sh >> /var/log/elearning_backup.log 2>&1

12. Troubleshooting Common Production Pitfalls

1. Bind for 0.0.0.0:80 failed: port is already allocated

  • Cause: Host Nginx is already bound to port 80.
  • Remedy: docker-compose.prod.yml binds the frontend container to 127.0.0.1:8088:80, not port 80. Ensure you run compose with -f docker-compose.prod.yml.

2. 413 Request Entity Too Large When Uploading Materials

  • Cause: The default Nginx max body size is 1MB.
  • Remedy: Make sure client_max_body_size 50M; is set in both the Host Nginx (/etc/nginx/sites-available/...) and the Container Nginx (frontend/nginx.conf). Then reload the Host Nginx with sudo systemctl reload nginx and rebuild the frontend container so it picks up the new nginx.conf: docker compose -f docker-compose.prod.yml up -d --build frontend.

3. Container Backend Exited with Code 137 (OOM Killed)

  • Cause: Linux killed the JVM because the system ran out of RAM.
  • Remedy:
    1. Make sure swap is active (swapon --show).
    2. Limit the JVM heap size in backend/Dockerfile by adding -Xms256m -Xmx512m to the ENTRYPOINT.

4. WebSocket Disconnect / Failed Handshake on CBT Proctoring

  • Cause: Host Nginx dropped the Upgrade headers.
  • Remedy: Verify that the location /ws block includes proxy_set_header Upgrade $http_upgrade; and proxy_read_timeout 86400s;.

5. Loading Demo Database Seed Data

To load realistic student candidates and question banks on a fresh server:

BASH
docker exec -i elearning-postgres psql -U elearning_prod_user -d elearning < /var/www/spring-elearning/backend/src/main/resources/db/seed/seed_demo_data.sql

Conclusion & Series Next Steps

You don't need expensive managed cloud infrastructure to deploy enterprise applications. By combining Docker Compose container isolation, Host Nginx reverse proxying with Certbot SSL, swap memory allocation, and automated backups, our Java Spring Boot 3 & React 19 E-Learning platform runs smoothly, securely, and cost-effectively on a single VPS.

The series continues after go-live. In Part 5 I audit the running system again with an attacker's eye, then cover exam integrity under concurrency (Part 6), the httpOnly refresh cookie, CSP and multi-instance scaling (Part 7), and architecture docs and testing (Part 8).

ShareLinkedInXWhatsApp

Written by Muhammad Fari Madyan

Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

Work with me
← part 3Enterprise Security Architecturepart 5 →Second Security Audit

Muhammad Fari Madyan

Senior Backend Engineer building real-time, high-concurrency systems that hold up in production. Co-founder of LampungDev. Based in Bandar Lampung, Indonesia (UTC+7), working remote.

Work

Case studiesCahTixExam platform, 4 stacksOpen source

© 2026 Muhammad Fari Madyan

Designed and built by Muhammad Fari Madyan