spring-bootapacheubuntureverse-proxyvirtualhost

Calling Spring Boot REST controller endpoints by React on Ubuntu VPS through Apache web server


I have deployed a React.js application on my Ubuntu VPS through Apache web server. I have configured a VirtualHost file for the React application and set a domain to it and also added SSL by using LetsEncrypt. So I can access the React website through its domain name on internet.

For implementing backend, I have created a Spring Boot application with some REST endpoints (controllers). I run the Spring Boot application using java -jar spring-app.jar. So the endpoints are accessible on the VPS, for example: http://serverIpAddress:8090/students. The Spring Boot application does not need to have a domain. I want it to be accessible by the React application to call its endpoints.

VirtualHost file of the React application:

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerAdmin webmaster@localhost
    ServerName  front-end-react.com
    ServerAlias www.front-end-react.com
    DocumentRoot /var/www/front-end-react.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    

Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/front-end-react.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/front-end-react.com/privkey.pem
</VirtualHost>
</IfModule>

Do I need to define another VirtualHost file for my Spring Boot application to expose port 8090, so the React application can access it?


Solution

  • the whole point of the reverse proxy is to avoid exposing the ports.

    What you do is add a rule to your configuraiton to forward all URLs that start with for example /api to specific port:

    ProxyPass "/api" "http://localhost:8090/api"
    ProxyPassReverse "/api" "http://localhost:8090/api"
    

    so in your case, complete configuration would be:

    <IfModule mod_ssl.c>
    <VirtualHost *:443>
        ServerAdmin webmaster@localhost
        ServerName  front-end-react.com
        ServerAlias www.front-end-react.com
        DocumentRoot /var/www/front-end-react.com
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        
    # forwarding to port 8090
    ProxyPass "/api" "http://localhost:8090/api"
    ProxyPassReverse "/api" "http://localhost:8090/api"
    
    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLCertificateFile /etc/letsencrypt/live/front-end-react.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/front-end-react.com/privkey.pem
    </VirtualHost>
    </IfModule>