Skip to content

Tech Docs

Rplex-saas Production Deployment Guide

🏗️ Architecture Overview

Container Architecture

The application runs in a multi-container Docker environment with the following services:

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Angular SPA   │    │ Spring Boot API │    │  PostgreSQL DB  │
│   (Frontend)    │    │   (Backend)     │    │   (Database)    │
│   Port: 4200    │    │   Port: 8080    │    │   Port: 5432    │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         └───────────────────────┼───────────────────────┘
                                 │
      ┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
      │     Redis       │    │    PgAdmin      │    │ Redis Insight   │
      │   (Cache)       │    │  (DB Admin)     │    │ (Monitoring)    │
      │   Port: 6379    │    │   Port: 8080    │    │   Port: 5540    │
      └─────────────────┘    └─────────────────┘    └─────────────────┘

Port Mapping

Service Internal Port External Port Purpose
Angular Frontend 80 4200 Web Application UI
Mobile Apps N/A N/A Client-side (no direct port)
Gateway/BFF 8081 7000 API Gateway and BFF routing
Messaging API 8080 7001 Backend REST API for emails and communications (via Gateway)
Accounts API 8080 7002 Backend REST API for viewing accounts and users api (via Gateway)
PostgreSQL 5432 N/A (internal) Primary Database (via API)
Redis 6379 N/A (internal) Caching & Sessions (via API)
PgAdmin 80 8082 Database Administration
Redis Insight 5540 5540 Cache Monitoring

🐳 Docker Configuration

Container Specifications

Frontend Container (Angular + Nginx)

  • Base Image: node:18-alpine → nginx:alpine (multi-stage)
  • Build Process:
  • Installs npm dependencies
  • Builds Angular app for production
  • Serves via nginx on port 80
  • Volume Mounts: None (stateless)
  • Health Check: HTTP response validation
# Multi-stage build for optimized production image
FROM node:18-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build -- --configuration production

FROM nginx:alpine
COPY --from=build /app/dist/Rplex-saas.frontend/browser/ /usr/share/nginx/html/
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80

Backend Container (Spring Boot API)

  • Base Image: openjdk:21-jdk-slim
  • Runtime: Spring Boot 3.x with OAuth2 Resource Server
  • Security: Runs as non-root user (appuser)
  • Volumes:
  • /app/logs, /app/temp for file operations
  • /app/uploads → api_uploads volume (persistent file storage)
  • Health Check: Spring Boot Actuator health endpoints
  • File Storage:
  • Images: /app/uploads/images/ (persistent)
  • PDFs: /app/uploads/storage/pdfs/ (persistent)
# Multi-stage build for Spring Boot
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /src
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src ./src
RUN mvn clean package -DskipTests

FROM openjdk:21-jdk-slim
RUN groupadd -r appuser && useradd -r -g appuser appuser
WORKDIR /app
COPY --from=build /src/target/*.jar app.jar
RUN mkdir -p /app/logs /app/temp /app/uploads && chown -R appuser:appuser /app
USER appuser
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

Database Container (PostgreSQL)

  • Base Image: postgres:17.4
  • Authentication: SCRAM-SHA-256
  • Persistent Storage: Named volume postgres_data
  • Health Check: pg_isready command
  • Configuration: Optimized for production workloads

Docker Compose Services

services:
  postgres:
    image: postgres:17.4
    container_name: Rplex-saas-postgres
    environment:
      POSTGRES_HOST_AUTH_METHOD: scram-sha-256
      POSTGRES_INITDB_ARGS: --auth-host=scram-sha-256 --auth-local=scram-sha-256
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: Rplex-saas_db
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - Rplex-saas-network
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 30s
      timeout: 10s
      retries: 3

  redis:
    image: redis:7.4
    container_name: Rplex-saas-redis
    environment:
      REDIS_PASSWORD: ${REDIS_PASSWORD}
    volumes:
      - redis_data:/data
    networks:
      - Rplex-saas-network

  api:
    build:
      context: .
      dockerfile: Rplex-saas.Backend/Dockerfile
    container_name: Rplex-saas-api
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/Rplex-saas_db
      SPRING_DATASOURCE_USERNAME: postgres
      SPRING_DATASOURCE_PASSWORD: ${POSTGRES_PASSWORD}
      SPRING_REDIS_HOST: redis
      SPRING_REDIS_PORT: 6379
      SPRING_REDIS_PASSWORD: ${REDIS_PASSWORD}
      SERVER_PORT: 8080
      JWT_SECRET_KEY: ${JWT_SECRET_KEY}
      CORS_ALLOWED_ORIGINS: http://${SERVER_IP}:4200
    volumes:
      - api_uploads:/app/uploads # Persistent file storage
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    networks:
      - Rplex-saas-network
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/actuator/health"]
      interval: 30s
      timeout: 10s
      retries: 3

  angular:
    build:
      context: ./Rplex-saas.Frontend
    container_name: Rplex-saas-angular
    ports:
      - "4200:80"
    depends_on:
      - api
    networks:
      - Rplex-saas-network

volumes:
  postgres_data:
  redis_data:
  api_uploads:

networks:
  Rplex-saas-network:
    driver: bridge

⚙️ Nginx Configuration

Reverse Proxy Setup

The nginx configuration in the frontend container handles:

  1. Static Asset Serving: Serves Angular build files
  2. API Proxying: Routes /api/ to Spring Boot backend for REST API
  3. File Serving: Routes /uploads/ to backend for file serving
  4. SPA Routing: Handles Angular router with fallback to index.html
  5. Caching: Optimized cache headers for static assets
server {
    listen 80;
    server_name localhost;
    root /usr/share/nginx/html;
    index index.html;

    # Proxy API requests to Spring Boot backend
    location /api/ {
        proxy_pass http://Rplex-saas-api:8080;
        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 30s;
        proxy_connect_timeout 30s;
    }

    # Proxy uploaded images and files to the backend API
    location /uploads/ {
        proxy_pass http://Rplex-saas-api:8080;
        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;

        # Cache images for better performance
        expires 1y;
        add_header Cache-Control "public, immutable";

        # Handle errors gracefully
        proxy_intercept_errors on;
        error_page 404 = @missing_file;
    }

    # Handle static assets (JS, CSS, fonts)
    location ~* \.(js|css|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        try_files $uri =404;
    }

    # Handle image files from frontend static assets
    location ~* \.(png|jpg|jpeg|gif)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        try_files $uri =404;
    }

    # SPA routing - serve index.html for all unmatched routes
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Fallback for missing files
    location @missing_file {
        return 404;
    }
}

Key Routing Rules

  • /api/ → Proxied to Rplex-saas-api:8080 for Spring Boot REST API
  • /uploads/ → Proxied to Rplex-saas-api:8080 for dynamic file serving
  • Static Assets → Served directly from nginx with aggressive caching (1 year)
  • Angular Routes → All unmatched routes fallback to index.html for SPA routing

🔧 Start.sh Script Features

Interactive .env Configuration

The script now interactively handles the .env file to prevent accidental overwrites.

  • Existing .env File: If an .env file is found, the script will prompt you to either use the existing file or create a new one.

bash # Excerpt from start.sh if [ -f "$ENV_FILE" ]; then echo -e "${YELLOW}🤔 An existing .env file was found.${NC}" read -p "Do you want to use the existing .env file? (y/n) " -n 1 -r echo if [[ $REPLY =~ ^[Yy]$ ]]; then echo -e "${GREEN}👍 Using existing .env file.${NC}" # ... (uses existing file) else echo -e "${YELLOW}✨ Creating a new .env file...${NC}" create_env_file fi else create_env_file fi

  • New .env File: If no .env file exists or you choose to create a new one, the script will:

  • Back up the old .env file (if it exists).

  • Generate a new .env file with secure, random credentials for the database, Redis, and JWT.
  • Dynamically set the server IP for CORS and other configurations.

Intelligent IP Detection

The script uses multiple methods to detect the server IP:

get_local_ip() {
    local ip=""

    # Method 1: ip route (Linux - most reliable)
    if command -v ip >/dev/null 2>&1; then
        ip=$(ip route get 8.8.8.8 2>/dev/null | awk '{print $7}' | head -n1)
    fi

    # Method 2: hostname -I (fallback)
    if [ -z "$ip" ] && command -v hostname >/dev/null 2>&1; then
        ip=$(hostname -I | awk '{print $1}')
    fi

    # Method 3: ifconfig (macOS/BSD fallback)
    if [ -z "$ip" ] && command -v ifconfig >/dev/null 2>&1; then
        ip=$(ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1' | head -n1)
    fi

    # Default fallback
    if [ -z "$ip" ]; then
        ip="localhost"
    fi

    echo "$ip"
}

Secure Configuration Generation

Automatically generates:

  • Database passwords: Cryptographically secure random passwords
  • Redis passwords: 32-character random passwords
  • JWT keys: 64-character signing keys
  • CORS origins: Dynamic based on detected IP
  • Database migrations: Using Spring Data JPA Flyway/Liquibase

Automated Health Checks

Post-deployment validation:

  • Spring Boot Actuator health endpoint verification
  • Frontend accessibility check
  • Container status monitoring
  • Service dependency validation

📁 File Storage Architecture

Image Service (ImageService)

  • Storage Location: uploads/images/
  • Persistence: Docker volume api_uploads ensures files survive container restarts
  • Supported Formats: JPG, PNG, GIF, BMP (max 5MB)
  • Access Pattern:
  • Upload via API: POST /api/images with multipart form
  • Access via URL: GET /uploads/images/{filename}
  • Nginx proxy: Frontend → API for dynamic serving
  • Security: File validation, size limits, MIME type checking
  • Implementation: Spring Boot RestController with multipart file handling

PDF Service (PdfService)

  • Storage Location: uploads/storage/pdfs/
  • Persistence: Docker volume api_uploads ensures files survive container restarts
  • Generation: On-demand report generation using iText or Apache PDFBox
  • Caching: SHA-256 content hashing for deduplication
  • Database Integration: Metadata stored in saved_pdfs table
  • Access Pattern: API-only access with OAuth2 authentication required

File URL Generation

Images are served with fully qualified URLs:

// Example from Todo.java:
String baseUrl = helper.getBaseUrl();
if (imagePath != null && !imagePath.isEmpty()) {
    this.imageUrl = baseUrl + "/uploads/images/" + imagePath;
} else {
    this.imageUrl = null;
}

🗄️ Database Configuration

PostgreSQL Setup

  • Version: PostgreSQL 17.4
  • Authentication: SCRAM-SHA-256 (secure password hashing)
  • Database: Rplex-saas_db
  • Schema: Managed with Spring Data JPA and Flyway/Liquibase
  • Persistence: Docker volume postgres_data

Migration Process

Automatic migration on startup with error handling:

// application.yml Spring Boot configuration
spring:
  jpa:
    hibernate:
      ddl-auto: validate
    show-sql: false
  flyway:
    enabled: true
    locations: classpath:db/migration
    out-of-order: false

// Application.java startup logic with enhanced logging
@SpringBootApplication
public class Rplex-saasApplication {
    private static final Logger logger = LoggerFactory.getLogger(Rplex-saasApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(Rplex-saasApplication.class, args);
        logger.info("Application started successfully");
    }

    @Bean
    public CommandLineRunner init(UserRepository userRepository, 
                                   RoleRepository roleRepository, 
                                   TodoRepository todoRepository) {
        return args -> {
            try {
                logger.info("Starting database seeding...");
                seedData(userRepository, roleRepository, todoRepository);
                logger.info("Database seeding completed successfully.");
            } catch (Exception ex) {
                logger.error("An error occurred while seeding the database.", ex);
                throw ex;
            }
        };
    }

    private void seedData(UserRepository userRepository, 
                         RoleRepository roleRepository, 
                         TodoRepository todoRepository) {
        // Seeding logic here
    }
}

Seeded Data

  • Admin User: [email protected] / Admin123!
  • Roles: ADMIN, USER, MANAGER, VIEWER
  • Default Configuration: System settings and initial todos
  • OAuth2: Resource Server configuration with JWT tokens

🔒 Security Configuration

Authentication & Authorization

  • OAuth2 Resource Server: JWT-based token validation
  • Spring Security: Comprehensive security filters and handlers
  • Role-based Access: Multiple user roles with @PreAuthorize annotations
  • CORS Policy: Dynamic origin configuration based on deployment IP
// Spring Security Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
            .authorizeHttpRequests(authz -> authz
                .requestMatchers("/api/public/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .requestMatchers("/api/todos/**").authenticated()
                .anyRequest().authenticated())
            .cors(Customizer.withDefaults())
            .csrf(AbstractHttpConfigurer::disable);
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of("http://localhost:4200"));
        configuration.setAllowedMethods(List.of("*"));
        configuration.setAllowedHeaders(List.of("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

Container Security

  • Non-root Execution: API runs as dedicated appuser
  • Network Isolation: Internal Docker network communication
  • Secret Management: Environment variable based configuration
  • File Permissions: Restricted file system access

Data Protection

  • Password Hashing: Spring Security PasswordEncoder (BCrypt)
  • Database Encryption: PostgreSQL SCRAM-SHA-256 authentication
  • Session Security: Redis-based session management via Spring Session
  • Input Validation: Bean Validation (@Valid, @NotNull, etc.)
  • JWT Tokens: Secure signing with RS256 algorithm

📊 Monitoring & Administration

Available Interfaces

  • Application: http://{IP}:4200 - Main application
  • API Documentation: http://{IP}:8080/swagger-ui.html - Swagger UI (Spring Doc OpenAPI)
  • PgAdmin: http://{IP}:8080 - Database administration
  • Redis Insight: http://{IP}:5540 - Cache monitoring
  • Health Check: http://{IP}:8080/actuator/health - Spring Boot Actuator

Log Management

# View all logs
docker-compose logs -f

# View specific service logs
docker-compose logs -f api
docker-compose logs -f angular
docker-compose logs -f postgres

# View logs with timestamps
docker-compose logs -f -t

# View Spring Boot application logs
docker-compose logs -f api | grep -E "INFO|ERROR|WARN"

Health Monitoring

Health checks configured for all critical services:

  • PostgreSQL: pg_isready check every 30s
  • Redis: Connection validation
  • Spring Boot API: Actuator /health endpoint every 30s
  • Frontend: HTTP response validation every 30s

🚀 Deployment Commands

Initial Deployment

# Clone repository
git clone <repository-url>
cd NERBA-Backoffice

# Make start script executable
chmod +x start.sh

# Deploy application
./start.sh

Ongoing Operations

# View status
docker-compose ps

# Stop application
docker-compose down

# Update and restart
git pull origin main
docker-compose down
docker-compose up -d --build

# Reset everything (careful!)
docker-compose down -v
docker system prune -f
./start.sh

Backup Operations

# Backup database
docker exec Rplex-saas-postgres pg_dump -U postgres Rplex-saas_db > backup.sql

# Backup uploaded files (from persistent volume)
docker run --rm -v Rplex-saas-api-uploads:/source -v $(pwd):/backup ubuntu tar czf /backup/file_backup.tar.gz -C /source .

# Restore database
docker exec -i Rplex-saas-postgres psql -U postgres Rplex-saas_db < backup.sql

# Restore uploaded files (to persistent volume)
docker run --rm -v Rplex-saas-api-uploads:/target -v $(pwd):/backup ubuntu tar xzf /backup/file_backup.tar.gz -C /target

🔍 Troubleshooting

Common Issues

Migration Failures:

  • Check PostgreSQL container health: docker-compose ps
  • Verify database connection: Check Spring Boot logs for connection errors
  • Check Flyway migration status: Review logs for migration script failures
  • Check disk space: Migrations require temporary storage

File Upload Issues:

  • Verify nginx proxy configuration points to Rplex-saas-api
  • Check container networking: docker network ls
  • Validate file permissions: /app/uploads ownership
  • Confirm volume mount: docker inspect Rplex-saas-api | grep Mounts
  • Check persistent storage: docker volume ls | grep Rplex-saas-api-uploads

Performance Issues:

  • Monitor Redis cache hit rate via Redis Insight
  • Check PostgreSQL connection pooling in application.yml
  • Review nginx access logs for static file serving
  • Monitor Spring Boot Actuator metrics: http://{IP}:8080/actuator/metrics

Debug Mode

Enable detailed logging by setting environment variables:

# In .env file or docker-compose.yml
SPRING_PROFILES_ACTIVE=dev
LOGGING_LEVEL_ROOT=DEBUG
LOGGING_LEVEL_COM_Rplex-saas=DEBUG

📈 Production Considerations

Scaling

  • Database: Configure connection pooling (HikariCP) and read replicas
  • API: Use container orchestration (Docker Swarm/Kubernetes) with Spring Cloud Config
  • Frontend: CDN distribution for static assets
  • Cache: Redis clustering for high availability

SSL/TLS

For production internet deployment:

  1. Obtain SSL certificates (Let's Encrypt recommended)
  2. Configure nginx SSL termination
  3. Update CORS origins to HTTPS
  4. Set secure cookie flags in Spring Security
  5. Enable HTTPS in application.yml

Backup Strategy

  • Database: Regular pg_dump exports with rotation
  • Files: Docker volume backups of api_uploads persistent storage
  • Configuration: Version control for docker-compose.yml and .env templates
  • Volume Management: Consider named volume backup strategies for production

🛠️ Spring Boot Todo API Overview

REST Endpoints

GET    /api/todos               - List all todos
GET    /api/todos/{id}          - Get specific todo
POST   /api/todos               - Create new todo
PUT    /api/todos/{id}          - Update existing todo
DELETE /api/todos/{id}          - Delete todo
POST   /api/todos/{id}/complete - Mark todo as complete

Todo Model

@Entity
@Table(name = "todos")
public class Todo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    private String title;

    private String description;

    private String imagePath;

    private Boolean completed = false;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @CreationTimestamp
    private LocalDateTime createdAt;

    @UpdateTimestamp
    private LocalDateTime updatedAt;
}

This comprehensive setup provides a robust, scalable foundation for the Rplex-saas application with Spring Boot, production-ready security, monitoring, and maintenance capabilities.