Search code examples
pythonamazon-web-servicessocketsamazon-ec2amazon-elb

How to use AWS Network Load Balancer with custom python server


I am trying to set up a python server on AWS. I would like to access this server through an elastic load balancer. However, I am having some difficulties troubleshooting my issue. The steps I have taken so far are as follows.

I created a new EC2 instance, ssh-ed into it and created my server and started it.

the code for that server is as follows:

import socket
HOST = '127.0.0.1'
PORT = 3002 

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    print("listening")
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)

Then I created a new target group and registered this ec2 instance to it. The target group is set for the same port as the server (3002).

Next, I created a network load balancer. This load-balancer has a listener set on port 3002 a rule to forward to the target group I have set up.

Finally, I created a local client on my machine with python to communicate with the server.

The code for that client is as follows:

HOST = DNS name for load-balancer
PORT = 3002

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)

print('Received', repr(data))

My thoughts were the client would connect to the load-balancer on port 3002. The load-balancer, which has a listener on this port, would forward to the target group, which is also using port 3002. Therefore, the ec2 instance would receive the connection on this port and be able to handle it. However, nothing is ever received and the connection times out.

The security groups are configured to allow all TCP traffic on all ports to be allowed (for the time being while I try and figure this out)

Also, this is just me trying to learn how to use a load balancer and connect from a client. I am not planning on using this in a bigger project :) Any help on where my thinking has gone wrong would be greatly appreciated!


Solution

  • Your Python app is only listening to connections from localhost. Change this:

    HOST = '127.0.0.1'
    

    To this:

    HOST = '0.0.0.0'