google-cloud-platformproxyapache2fastapireverse-proxy

Cannot access FastAPI app behind Apache HTTPS proxy on Google Cloud


I'm struggling to serve my FastAPI app securely on forge-code.com with HTTPS.

Here's what I've done so far:

Deployed my FastAPI app on a Google Cloud instance. Successfully accessed the app using HTTPS directly through the instance's IP address. Purchased a domain forge-code.com on Hostinger and configured it to forward requests to my instance. Installed an SSL certificate from Certbot and accessed the Apache2 index.html file on my instance via https://forge-code.com. My problem: When I access https://forge-code.com, I see the Apache2 index.html instead of my FastAPI app. My 000-default.conf file looks like this:

  GNU nano 7.2                                                                                                     000-default.conf                                                                                                              
<VirtualHost *:80>
    ServerName forge-code.com

    RewriteEngine on
    RewriteCond %{SERVER_NAME} =forge-code.com
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>


00-default-le-ssl.conf

<IfModule mod_ssl.c>
<VirtualHost *:443>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        ProxyPass / http://0.0.0.0:8000/
        ProxyPassReverse / http://0.0.0.0:8000/
        SSLEngine on
        ServerName forge-code.com
        Include /etc/letsencrypt/options-ssl-apache.conf
        SSLCertificateFile /etc/letsencrypt/live/forge-code.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/forge-code.com/privkey.pem
</VirtualHost>

</IfModule>

Here is some more information These are the output of

systemctl status apache2

shivajay295@instance-20240221-193932:/etc/apache2/sites-available$ systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; preset: enabled)
     Active: active (running) since Fri 2024-02-23 18:37:43 UTC; 2h 30min ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 46449 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
    Process: 47594 ExecReload=/usr/sbin/apachectl graceful (code=exited, status=0/SUCCESS)
   Main PID: 46455 (apache2)
      Tasks: 55 (limit: 1141)
     Memory: 12.5M
        CPU: 1.008s
     CGroup: /system.slice/apache2.service
             ├─46455 /usr/sbin/apache2 -k start
             ├─47598 /usr/sbin/apache2 -k start
             └─47599 /usr/sbin/apache2 -k start

Feb 23 18:37:43 instance-20240221-193932 systemd[1]: Starting apache2.service - The Apache HTTP Server...
Feb 23 18:37:43 instance-20240221-193932 systemd[1]: Started apache2.service - The Apache HTTP Server.
Feb 23 20:56:01 instance-20240221-193932 systemd[1]: Reloading apache2.service - The Apache HTTP Server...
Feb 23 20:56:01 instance-20240221-193932 systemd[1]: Reloaded apache2.service - The Apache HTTP Server.
Feb 23 21:02:15 instance-20240221-193932 systemd[1]: Reloading apache2.service - The Apache HTTP Server...
Feb 23 21:02:15 instance-20240221-193932 systemd[1]: Reloaded apache2.service - The Apache HTTP Server.
shivajay295@instance-20240221-193932:/etc/apache2/sites-available$ 

sudo /usr/sbin/apache2ctl -S

shivajay295@instance-20240221-193932:/etc/apache2/sites-available$ sudo /usr/sbin/apache2ctl -S
VirtualHost configuration:
*:443                  forge-code.com (/etc/apache2/sites-enabled/000-default-le-ssl.conf:2)
*:80                   forge-code.com (/etc/apache2/sites-enabled/000-default.conf:1)
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex watchdog-callback: using_defaults
Mutex rewrite-map: using_defaults
Mutex ssl-stapling-refresh: using_defaults
Mutex ssl-stapling: using_defaults
Mutex proxy: using_defaults
Mutex ssl-cache: using_defaults
Mutex default: dir="/var/run/apache2/" mechanism=default 
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33
Group: name="www-data" id=33
shivajay295@instance-20240221-193932:/etc/apache2/sites-available$ 

Additional information:

I'm using Ubuntu on my Google Cloud instance. I've verified that I have read permissions for the SSL certificate and key files. I'm unsure why my FastAPI app isn't being served through forge-code.com. What do I need to do to successfully serve my FastAPI app with HTTPS on forge-code.com?


Solution

  • Deploying a FastAPI App on a Domain with Apache and SSL:

    1. Domain Purchase and DNS Configuration:

    Acquire a domain: Purchase a domain name (e.g., forge-code.com) from a reputable domain registrar. Point DNS records: In your domain's DNS settings, create an A record that maps your domain to the IP address of your GCP instance:

    Type: A
    
    Name: @ (or leave blank)
    
    Value: 34.131.190.233 (replace with your instance's IP)
    
    TTL: 14400 (or a suitable value)
    

    2. SSL Certificate Installation:

    Obtain a certificate: Use Certbot to obtain a free SSL certificate from Let's Encrypt:

    sudo apt install certbot python3-certbot-apache
    sudo certbot --apache -d forge-code.com
    

    3. Apache Configuration:

    Edit virtual hosts: Modify the following files in /etc/apache2/sites-available:

    000-default-le-ssl.conf (for HTTPS): Ensure SSLEngine is enabled.

    Set ServerName to your domain.

    Include SSL certificate and key files.

    ProxyPass and ProxyPassReverse to your FastAPI app's port (8000).

    Here is my conf file

    <IfModule mod_ssl.c>
    <VirtualHost *:443>
            ErrorLog ${APACHE_LOG_DIR}/error.log
            CustomLog ${APACHE_LOG_DIR}/access.log combined
            ProxyPass / http://0.0.0.0:8000/
            ProxyPassReverse / http://0.0.0.0:8000/
            SSLEngine on
            ServerName forge-code.com
            Include /etc/letsencrypt/options-ssl-apache.conf
            SSLCertificateFile /etc/letsencrypt/live/forge-code.com/fullchain.pem
            SSLCertificateKeyFile /etc/letsencrypt/live/forge-code.com/privkey.pem
    </VirtualHost>
    
    </IfModule>
    

    000-default.conf (for HTTP): Redirect all HTTP requests to HTTPS using a RewriteRule.

    Here is my conf file

      GNU nano 7.2                                                                                                000-default.conf                                                                                                          
    <VirtualHost *:80>
        ServerName forge-code.com
    
        # Enable proxy modules
        ProxyRequests Off
        ProxyPreserveHost On
        ProxyPass / http://0.0.0.0:8000/
        ProxyPassReverse / http://0.0.0.0:8000/
    
        # Rewrite rule to redirect HTTP to HTTPS
        RewriteEngine on
        RewriteCond %{SERVER_NAME} =forge-code.com
        SetEnv proxy-initial-not-pooled 1
            RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
    </VirtualHost>
    

    4. Apache Restart:

    Reload configuration: sudo systemctl restart apache2

    5. FastAPI App Startup:

    Run FastAPI app: venv/bin/uvicorn app:app --host 0.0.0.0 --port 8000

    Additional Considerations:

    Firewall rules: Ensure your firewall allows traffic on ports 80 and 443.

    FastAPI app configuration: Verify that your FastAPI app is configured to listen on port 8000.

    Troubleshooting: Use Apache logs (/var/log/apache2/error.log) for troubleshooting any issues.

    Process management: Consider using a process manager like systemd or supervisord to keep your FastAPI app running in the background. Alternative proxying: If Apache encounters challenges, explore Nginx or HAProxy as alternative proxy solutions.

    Key Points:

    Domain configuration: Accurate DNS settings are crucial for directing traffic to your server.

    SSL certificates: Secure communication with HTTPS requires valid SSL certificates.

    Apache configuration: Proper configuration enables Apache to proxy requests to your FastAPI app and handle SSL.

    FastAPI app startup: Ensure your app is running and listening on the correct port.

    Troubleshooting: Log files and process management are essential for identifying and resolving issues.

    And Bingo here your fastapi app is running on your domain!!!