To run a Flask application on port 80, first ensure you have permission to run the application on lower ports, as ports below 1024 typically require administrator or root privileges. Next, you can configure your Flask application to run on port 80 using the following methods:
1. Specify the Port Directly in Code
You can specify the port in the Flask application's startup script. For example:
pythonfrom flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hello, World!' if __name__ == '__main__': app.run(host='0.0.0.0', port=80)
In this example, the line app.run(host='0.0.0.0', port=80) will make the Flask application listen on port 80 for all available network interfaces (where 0.0.0.0 indicates listening on all interfaces).
2. Use Command Line Parameters
If you prefer not to hardcode the port number in the code, you can specify it via the command line when running the application. For example:
bashFLASK_APP=app.py flask run --host=0.0.0.0 --port=80
Here, FLASK_APP=app.py is an environment variable that tells Flask which file is the application entry point, while --host=0.0.0.0 and --port=80 are used to set the listening IP address and port number, respectively.
3. Use Environment Configuration
Another option is to configure Flask using environment variables. You can set FLASK_RUN_PORT in your system's environment variables:
bashexport FLASK_RUN_PORT=80 FLASK_APP=app.py flask run --host=0.0.0.0
Note on Security and Permissions
- Permissions: As previously mentioned, listening on ports below 1024 typically requires administrator privileges. If running on a Linux system, you may need to use the
sudocommand or modify the application's permissions. - Security: Running on port 80 means your application is directly exposed to the internet. Ensure your application is properly secured, for example, by using WSGI middleware to handle requests and keeping Flask and its dependencies updated to the latest versions.
Using these methods, you can flexibly configure your Flask application to run on port 80 in development or production environments as needed.