Search code examples
amazon-web-servicesflaskamazon-ec2

How To Run a Flask App on EC2 Public IP Instead of Private IP?


I have a Flask app I want to run on an AWS EC2 instance.

When I do flask run --host=0.0.0.0, the output says its running on all addresses (0.0.0.0), localhost (127.0.0.1), and my AWS EC2's private IPv4 address. I need it to run on the public one so it's accessible anywhere on the internet. When I use the public address for the host argument, it says "Cannot assign requested address".


Solution

  • When I use the public address for the host argument, it says "Cannot assign requested address".

    If your ENI (Elastic Network Interface) has an Elastic IP attached (or a dynamic Publiс IP), all packets are NAT'd between your public and private IPs. It happens outside the EC2 instance.

    The EC2 instance only sees the private IPs of the ENI's attached to it.

    I need it to run on the public one so it's accessible anywhere on the internet.

    1. Set up an inbound rule on a security group attached to the interface, which would allow traffic to your destination port
    2. Listen on the private address of your ENI, or on 0.0.0.0

    This way, requests made to your public IP will reach your Flask app, even if it only listens on the private IP.