0

I am trying to make a fastapi request to my EC2 instance from an external ip address (my VM). I started a python docker container on my EC2 instance with sudo docker run --name <container_name> -p 5000:5000 -itd python:latest bash. Then inside that container I created a main.py script:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return "Connection successful and operates on port 5000"

I then run this script with uvicorn main:app --port 5000 in the terminal of the container.

When I try to make an api request from the terminal of the container (I get inside the container using sudo docker exec -it <container_name> sh) using requests.get('http://localhost:5000') I received the response I expect ("Connection successful and operates on port 5000").

But when I try to make the same request from my VM (external ip), using requests.get('http://3.17.184.122:5000') (I replace 'localhost' with ec2 public ip), I always get the error:

Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.8/site-packages/urllib3/connection.py", line 174, in _new_conn
    conn = connection.create_connection(
  File "/home/ubuntu/.local/lib/python3.8/site-packages/urllib3/util/connection.py", line 96, in create_connection
    raise err
  File "/home/ubuntu/.local/lib/python3.8/site-packages/urllib3/util/connection.py", line 86, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 699, in urlopen
    httplib_response = self._make_request(
  File "/home/ubuntu/.local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 394, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/home/ubuntu/.local/lib/python3.8/site-packages/urllib3/connection.py", line 239, in request
    super(HTTPConnection, self).request(method, url, body=body, headers=headers)
  File "/usr/lib/python3.8/http/client.py", line 1256, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/lib/python3.8/http/client.py", line 1302, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.8/http/client.py", line 1251, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.8/http/client.py", line 1011, in _send_output
    self.send(msg)
  File "/usr/lib/python3.8/http/client.py", line 951, in send
    self.connect()
  File "/home/ubuntu/.local/lib/python3.8/site-packages/urllib3/connection.py", line 205, in connect
    conn = self._new_conn()
  File "/home/ubuntu/.local/lib/python3.8/site-packages/urllib3/connection.py", line 186, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7f8b596dbe50>: Failed to establish a new connection: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.8/site-packages/requests/adapters.py", line 439, in send
    resp = conn.urlopen(
  File "/home/ubuntu/.local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 755, in urlopen
    retries = retries.increment(
  File "/home/ubuntu/.local/lib/python3.8/site-packages/urllib3/util/retry.py", line 574, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='3.17.184.122', port=5000): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f8b596dbe50>: Failed to establish a new connection: [Errno 111] Connection refused'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ubuntu/.local/lib/python3.8/site-packages/requests/api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "/home/ubuntu/.local/lib/python3.8/site-packages/requests/api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "/home/ubuntu/.local/lib/python3.8/site-packages/requests/sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/ubuntu/.local/lib/python3.8/site-packages/requests/sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "/home/ubuntu/.local/lib/python3.8/site-packages/requests/adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='3.17.184.122', port=5000): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f8b596dbe50>: Failed to establish a new connection: [Errno 111] Connection refused'))

I tried to add an inbound rule on the default security group to allow tcp access on port 5000, which did not help. I also tried to allow access from all traffic, which also did not help:

enter image description here

Please advise on what I am missing. Thank you.

midav
  • 91
  • 2
  • 7
  • are you sure you are editing the the right security group attached to the ec2? – Jayesh Apr 08 '23 at 18:46
  • Thank you for the suggestion @Jayesh. There is only a single security group. Maybe outbound rules need to be adjusted as well? – midav Apr 08 '23 at 20:45
  • What OS? Do you have `ufw` installed and configured? – Anon Coward Apr 08 '23 at 20:59
  • Thank you for your comment @AnonCoward. AWS EC2 runs ubuntu 20.04. `ufw` is disabled (`status: inactive`). – midav Apr 08 '23 at 21:13
  • Interestingly, when I try to send an api request from the EC2 instance to my VM I also get the same error, and my VM has the necessary ports open. I changed the ports the main.py file is executed on. – midav Apr 08 '23 at 21:27
  • Someone helped me answer part of the question on AWS forum. Apparently the default interface for uvicorn is 127.0.0.1. Specifying the `--host` parameter when starting uvicorn, e.g., `uvicorn main:app --port 5000 --host 0.0.0.0` helps. I can now make requests from EC2 to my VM. I still cannot make requests from my VM to EC2 though. Original answer: https://repost.aws/questions/QUUwVBzhPyTryCpRV5yAws_g/how-to-open-port-on-ec2-to-allow-api-requests-from-external-ips – midav Apr 08 '23 at 21:53

0 Answers0