Search code examples
amazon-web-servicesflaskamazon-ec2deploymentcloud

unable to send http requests to simple flask app on ec2 instance


I am trying to deploy a simple flask app on ec2 instance but unable to send any http requests , I have tried different combinations of ips and port while creating a security group but it still wont work . the app works as needed on my localhost. here is the code

import logging
import sys
import threading
from flask import Flask, request, jsonify
from main import mainfunction
import concurrent.futures
# Configure logging to capture output
app = Flask(__name__)

# Your asynchronous function that will be called
def process_client(client):
    # Redirect stdout to the console
    sys.stdout = sys.__stdout__
    # Create a thread to run mainfunction in the background
    thread = threading.Thread(target=mainfunction, args=(client,))
    thread.start()
    return "Processing client in the background..."

@app.route('/process', methods=['POST'])
def process():
    try:
        data = request.get_json()
        if 'client' in data:
            client = data['client']

            # Call the asynchronous function using asyncio
            result = process_client(client)

            return jsonify({'result': result})
        else:
            return jsonify({'error': 'Missing client data in request'}), 400
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/', methods=['GET'])
def status():
    return 'Server is listening'

if __name__ == '__main__':
    app.run(debug=True)

enter image description here

enter image description here enter image description here

here are the inbound and outbound rules I have setup

enter image description here enter image description here it has been more than a week and i dont know how to proceed with this problem


Solution

  • When deploying a Flask application on an EC2 instance, there are several things to consider for it to be accessible externally. Below are some troubleshooting steps that might help you figure out why you can't send HTTP requests to your EC2 Flask app.

    Security Groups

    Make sure that you have opened the port (by default Flask uses port 5000) in the EC2 Security Group.

    Go to your AWS Console.

    • Navigate to EC2.
    • Go to "Security Groups" under the "Networking & Security" section.
    • Select the security group associated with your EC2 instance.
    • Add an inbound rule: Type: Custom TCP Port range: 5000 Source: 0.0.0.0/0 (though you might want to limit it later for security reasons)

    Running the Flask App

    In your Flask app code, you have:

    if __name__ == '__main__':
        app.run(debug=True)
    

    Change this to:

    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000, debug=True)
    

    Using 0.0.0.0 allows the app to listen to requests from any IP address, not just localhost.

    Networking

    Check your EC2 instance's public IP. Use that IP to connect to your Flask app from your local machine, like so:

    arduino

    http://[EC2_Public_IP]:5000/
    or
    curl http://[EC2_Public_IP]:5000/
    

    Firewall

    It's also possible that you have a local firewall enabled on the EC2 instance itself that is preventing external access. Check that using:

    For Ubuntu/Debian:

    sudo ufw status
    

    For Red Hat/CentOS:

    sudo firewall-cmd --list-all
    

    Logs and Debugging

    Enable Flask logging by adding these lines in your code:

    import logging
    
    logging.basicConfig(level=logging.DEBUG)
    

    Then check the logs for any errors or issues.

    Finally

    If none of these steps work, the problem could be more complex, and you might need to look into networking settings, VPC configurations, or something else.