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

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!

Related

How to Host a Flask website from localhost 5000

Hello I coded this website that generates math problems (Here is the code: Here)
It is coded on flask and it is locally being hosted on this link that is not accessible to other people http://127.0.0.1:5000/ .I have a google domain and I want to have a website. What things / services do I need to use. I have been wait to see if I need to use AWS but I think I might need to. I have tried things like transferring it off of flask but I can't. If this is a repost sorry please post there answer thanks -Ben
I am assuming what you're asking is to host your flask web site so others can view it. The address you mention in your post is the local host address for your computer and is only accessible from your own computer. If you only want someone on your same network (WiFi) to access it, you would need to replace "127.0.0.1" with the IP address of your computer. You would also likely have to open up a firewall on your computer to allow the port 5000.
However, if you want anyone on the internet to access your site, there are a ton of ways to do this but since you mentioned AWS, you can do this easily by running a small EC2 instance (virtual server). If you have a new AWS account and have not already run any EC2 in that account, you can actually run a small EC2 instance for free for a whole year. Great for small projects. If you're just getting started with EC2, you may want to go here https://aws.amazon.com/ec2/getting-started/
Basic steps:
Spin up an EC2 instance. Choose the default Amazon Linxu 2 OS type, make sure to create/assign a key pair so you can later ssh into it, make sure the Allow SSH from anywhere setting is checked/selected and the Allow HTTP checkbox is checked (not HTTPS).
Wait for the instance to launch.
Log into your instance by clicking on your ec2 instance in the list of ec2 instnaces and click the Connect button, click the Connect button again (Instance connect tab). If that doesn't work, follow the steps on the SSH client tab.
Install flask
pip3 install flask
Clone your git repo
git clone https://github.com/some0ne14/Math-Ibex.git
Change to your repos' folder
cd Math-Ibex/Math-Practice-Website-master
Edit your main.py so that the app.run line looks like the following (you can do this on GitHub before you run git clone actually or use the nano command to edit the file easily). This allows the system to run on the standard web port 80.
app.run(host='0.0.0.0', port=80, debug=True)
Run the following to start the application. If you want to run it as a service so you can walk away or close the terminal and it will still stay running, just search on here how to run flask as a service.
python3 main.py
You can now connect to your server with any web browser using your EC2 instance's public IP address or generated AWS DNS name (available on the EC2 instnace property page).
Make sure to stop your instance when not using it to save those free runtime minutes.

How does Flask process the "flask run" cli command?

I've been trying to understand how it's possible to launch a flask project by running flask run.
What actually happens behind the scenes? How is it possible to actually launch the app using the flask keyword? I got as far as understanding that it is based on the Click library (https://palletsprojects.com/p/click/) but I still don't understand what happens step by step (the internals).
If someone could explain that would be appreciated. Thank you!
To launch a flask application, you can use the command flask run. But how does it work?
Before running any flask application, flask needs to be told how to import it by setting certain environment variables. On your terminal, you run these commands in their order:
(venv) $ export FLASK_APP=app.py
(venv) $ flask run
What is app.py? This is the entry point of your application. In this file, you probably have:
from app import app
# Here, you application instance is being imported.
# The application instance is where you defined your flask app.
Alternatively, this file may have:
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
After the server initializes it will wait for client connections. The output from flask run indicates that the server is running on IP address 127.0.0.1, which is always the address of your own computer. This address is so common that is also has a simpler name that you may have seen before: localhost.
Applications deployed on production web servers typically listen on port 443, or sometimes 80 if they do not implement encryption, but access to these ports require administration rights. Since this application is running in a development environment, Flask uses the freely available port 5000.
To access you application on your web browser, paste this URL:
http://localhost:5000/
There are other environment variables that flask can use:
FLASK_ENV (sets your environment, either to development or production)
FLASK_DEBUG (enables/disables debugging)
Before running flask run, you will run need to add the other environment variables in your terminal:
(venv) $ export FLASK_APP=app.py
(venv) $ export FLASK_ENV=development
(venv) $ export FLASK_DEBUG=True
(venv) $ flask run
Now, you will have specified that your application is running on a development server, and you have enabled flask debugging features.
Every time you want to see the changes in your application, you will need to restart your server by running the same commands in your terminal.
Starting with version 1.0, Flask allows you to register environment variables that you want to be automatically imported when you run the flask command.
It is recommended that you store flask environment variables (these are the ones needed to run your application) in a file called .flaskenv in your project's root directory.
(venv) $ touch .flaskenv
Then update this file with your environment variables:
# .flaskenv
FLASK_APP=app.py
FLASK_ENV=development
FLASK_DEBUG=True
To implement this option, you will need the packege python-dotenv:
(venv)$ pip3 install python-dotenv
This is optional, but it makes it a lot easier rather than you having to memorize all environment variables which you pass via the terminal.
To run your flask app using this option, you will only need:
(venv)$ flask run

Flask app on plesk/apache server - how to change port?

I'm new to setting up a server for python apps, slowly getting my head round all the tools and config options.
I'd like to configure a testing instance on an existing server that has plesk and apache installed. I managed to set up the python environment, virtualenv, the flask app inclusive database and run it successfully on http://domain.test:5000 however I'd need to remove the port number from the domain.
Gunicorn seems to be the tool for that, however I'm not sure how to go about it as plesk is apparently installed on port 80 - so is there any way to get this configured on that server with some port hiding/masking/redirect or do I need to move to a standalone server?
Additionally I'd like to add a ssl certificate to that domain but one step at the time...
The method run on a Flask application takes a keyword argument port:
from flask import Flask
app = Flask(__name__)
app.run(port=80)
Of course you'll need root privileges to run on port 80

How to run flask python website permanently?

I'm following Flask Quickstart guide and can run my web app via http://myip.com:5000.
One issue is that my web is only accessible as long as I keep my SSH remote connection session - when I sleep/shutdown my PC, the website shutdown too.
How can I make it permanent available?
You need to use a regular web server, such as apache2. You can't use the python server for production purposes. Here is how you do it with apache: http://flask.pocoo.org/docs/0.10/deploying/mod_wsgi/

Flask development server blocked by proxy at work

I am trying to use the flask development server at an office with a strict proxy that blocks the default 127.0.0.1:5000 host and port. I have tried using different hosts and ports with no success. I have also tried setting up Flask with XAMPP on Windows via mod_wsgi with no success. I am looking for an option to continue testing flask on my local machine with as little setup as possible as my production environment is a PaaS and does not use the same setup as my local machine.

Categories