简体   繁体   中英

How to access a Python flask application running on AWS EC2 remotely?

I have a flask app that I have cloned onto my aws ec2 instance. I can only run it using a virtual environment (which I activate by running the following):

$ python3 -m venv venv
$ source venv/bin/activate
$ pip install --upgrade pip
$ pip install flask==1.1.1

Below is my app:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run() 

It runs just fine when executing env FLASK_APP=app.py flask run . The problem is, I'd like to access the exposed routes remotely using my aws ec2's public IP or hostname. I get a tiemout error whenever I try to access it though. I think this is because i'm running the flask app in a virtual environment but I'm not sure. I can't find any good tutorials on how to expose this. Where am I going wrong here?

Quick n' safe solution:

As you're running the development server, which isn't meant for production. I would say the best way to connect to this app from just your own machine , is with an ssh tunnel:

ssh -L 5000:localhost:5000 ec2_addr

You can then point your web-browser to http://localhost:5000/ on your client machine, which will be tunneled to port 5000 on the EC2 instance. This is a fast way to connect to a Flask (or any) server on a remote Linux box. The tunnel is destroyed when you stop that ssh session.

Longer method:

I'd like to access the exposed routes remotely using my aws ec2's public IP or hostname.

The timeout isn't because it's running in a virtual environment: You'll probably find it's because you need to assign Security Groups to your instance through the EC2 console. These allow you to open certain ports on the public IP.

See this other answer I wrote, regarding EC2 security groups .

However be careful . You shouldn't expose the development server in this manner. There are a number of tutorials like this one from digital ocean which cover deploying a flask app behind gunicorn and nginx with a Let's Encrypt SSL cert. You should find yourself in a position where your security group exposes port 80 and 443, with requests to port 80 being redirected to the https URL by the nginx configuration.

If this sounds like a whole load of hassle / you don't have Linux skills / you don't want to learn Linux skills, then these are common reasons people pick managed services like AWS Elastic Beanstalk, to which you can deploy your flask app (official guide) , without having to worry about server config. Heroku is another (non AWS) service which offers such features.

It really depends on what you require / wish to gain. Stay safe!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM