[python] How do I get Flask to run on port 80?

I have a Flask server running through port 5000, and it's fine. I can access it at http://example.com:5000

But is it possible to simply access it at http://example.com? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it.

Traceback (most recent call last):
  File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
   File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
  File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
    test_socket.bind((hostname, port))
  File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use

Running lsof -i :80 returns

COMMAND   PID     USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
apache2   467     root    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2  4413 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14346 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14570 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14571 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)
apache2 14573 www-data    3u  IPv4 92108840      0t0  TCP *:www (LISTEN)

Do I need to kill these processes first? Is that safe? Or is there another way to keep Flask running on port 5000 but have the main website domain redirect somehow?

This question is related to python networking flask port

The answer is


A convinient way is using the package python-dotenv: It reads out a .flaskenv file where you can store environment variables for flask.

  • pip install python-dotenv
  • create a file .flaskenv in the root directory of your app

Inside the file you specify:

FLASK_APP=application.py
FLASK_RUN_HOST=localhost
FLASK_RUN_PORT=80

After that you just have to run your app with flask run and can access your app at that port.

Please note that FLASK_RUN_HOST defaults to 127.0.0.1 and FLASK_RUN_PORT defaults to 5000.


On my scenario the following steps worked like a charm:

  • Installing the package:

    pip install --upgrade pip
    pip install python-dotenv
    
  • Creating a hidden file in my app directory "flaskr/.flaskenv"

  • Adding the following content:

    FLASK_APP=flaskr
    FLASK_RUN_HOST=localhost
    FLASK_RUN_PORT=8000
    
  • Finally, run the flask command one more time:

    flask run
    
  • The version which I am working on is:

    pip freeze |grep -i flask
    Flask==1.1.1
    

For externally visible server, where you don't use apache or other web server you just type

flask run --host=0.0.0.0 --port=80

If you use the following to change the port or host:

if __name__ == '__main__':
  app.run(host='0.0.0.0', port=80)

use the following code to start the server (my main entrance for flask is app.py):

python app.py

instead of using:

flask run

set the port with app.run(port=80,debug=True) you should set debug to true when on dev


This is the only solution that worked for me on Ubuntu-18.

Inside the file app.py , use:

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)

The code above will give the same permission error unless sudo is used to run it:

sudo python3 app.py

1- Stop other applications that are using port 80. 2- run application with port 80 :

if __name__ == '__main__':
      app.run(host='0.0.0.0', port=80)

I had to set FLASK_RUN_PORT in my environment to the specified port number. Next time you start your app, Flask will load that environment variable with the port number you selected.


you can easily disable any process running on port 80 and then run this command

flask run --host 0.0.0.0 --port 80

or if u prefer running it within the .py file

if __name__ == "__main__":
    app.run(host=0.0.0.0, port=80)

If you want your application on same port i.e port=5000 then just in your terminal run this command:

fuser -k 5000/tcp

and then run:

python app.py

If you want to run on a specified port, e.g. if you want to run on port=80, in your main file just mention this:

if __name__ == '__main__':  
    app.run(host='0.0.0.0', port=80)

You don't need to change port number for your application, just configure your www server (nginx or apache) to proxy queries to flask port. Pay attantion on uWSGI.


Your issue is, that you have an apache webserver already running that is already using port 80. So, you can either:

  1. Kill apache: You should probably do this via /etc/init.d/apache2 stop, rather than simply killing them.

  2. Deploy your flask app in your apache process, as flask in apache describes.


Easiest and Best Solution

Save your .py file in a folder. This case my folder name is test. In the command prompt run the following

c:\test> set FLASK_APP=application.py
c:\test> set FLASK_RUN_PORT=8000
c:\test> flask run

----------------- Following will be returned ----------------

 * Serving Flask app "application.py"
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/Aug/2019 09:40:04] "[37mGET / HTTP/1.1[0m" 200 -
127.0.0.1 - - [23/Aug/2019 09:40:04] "[33mGET /favicon.ico HTTP/1.1[0m" 404 -

Now on your browser type: http://127.0.0.1:8000. Thanks


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to networking

Access HTTP response as string in Go Communication between multiple docker-compose projects Can't access 127.0.0.1 How do I delete virtual interface in Linux? ConnectivityManager getNetworkInfo(int) deprecated Bridged networking not working in Virtualbox under Windows 10 Difference between PACKETS and FRAMES How to communicate between Docker containers via "hostname" java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused) wget: unable to resolve host address `http'

Examples related to flask

Flask at first run: Do not use the development server in a production environment Flask - Calling python function on button OnClick event python-How to set global variables in Flask? In Flask, What is request.args and how is it used? How to print from Flask @app.route to python console What does "app.run(host='0.0.0.0') " mean in Flask Making an asynchronous task in Flask Flask ImportError: No Module Named Flask can you add HTTPS functionality to a python flask web server? How to get http headers in flask?

Examples related to port

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated How do I kill the process currently using a port on localhost in Windows? Node.js Port 3000 already in use but it actually isn't? Can't connect to Postgresql on port 5432 Spring Boot - How to get the running port Make docker use IPv4 for port binding How to change the default port of mysql from 3306 to 3360 Open firewall port on CentOS 7 Unable to launch the IIS Express Web server, Failed to register URL, Access is denied XAMPP Port 80 in use by "Unable to open process" with PID 4