'How to secure a fastapi app hosted on EC2 instance with a self-signed SSL certificate?

I have a Fastapi app hosted on EC2 instance using docker-compose.yml. Currently, the app is not secured (HTTP & not HTTPS). I am trying to secure the app via a self-signed cert by following the tutorial Deploy your FastAPI API to AWS EC2 using Nginx.

I have the following in the fastapi_nginx file in the /etc/nginx/sites-enabled/

server {
    listen 80;
    listen 443 ssl;
    ssl on;
    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;
    server_name x.xx.xxx.xxx;
    location / {
        proxy_pass http://0.0.0.0:8000/docs;
    }
}

But it doesn't seem to work. When I do https://x.xx.xxx.xxx, I get the error:

This page isn’t working

x.xx.xxx.xxx didn’t send any data.

ERR_EMPTY_RESPONSE

But http://x.xx.xxx.xxx is working like before.

I am not sure if I am missing anything or making any mistakes.

P.S.: I also tried doing the steps mentioned in the article here and still it wasn't working.

Also, the inbound in security groups

enter image description here



Solution 1:[1]

You are redirecting https traffic to /docs, have you tried proxy_pass http://localhost:8000;?

Also 0.0.0.0 is not always a good solution, it means to all IP addresses on the local machine as referred here. Try 127.0.0.1 or localhost.

You can check any errors in /var/log/nginx/error.log.

Finally, see if your security group and route table allow the traffic.

Solution 2:[2]

Since you make use of the docker-compose.yml. You can probably configure as follows:

Extend your docker-compose.yml having nginx as well.

In the below mounts the nginx.conf is the file you have defined locally, certs are certificates. Also, it would be best to keep in the same network as per the fastapi app so that they communicate.

nginx.conf to be modified is to point to the Docker service name of the fastapi app:

location / {
    proxy_pass http://my-fastapi-app:8000/docs;
}

An example snippet below:

...
networks:
  app_net:
    services:
      my-fastapi-app:
        ...
        networks:
         - app_net
      nginx:
        image: 'bitnami/nginx:1.14.2'
        ports:
          - '80:8080'
          - '443:8443'
        volumes:
          - ./nginx.conf:/opt/bitnami/nginx/conf/nginx.conf:ro
          - ./certs:/opt/bitnami/nginx/certs/:ro
          - ./tmp/:/opt/bitnami/nginx/tmp/:rw
        networks:
         - app_net

Additionally, I could also suggest looking into caddy. The certification process and renewal is automatically done.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 halfer
Solution 2 halfer