How to Change Port in Flask app
0 1160
Introduction
By default, Flask runs your application on port 5000 when you use the development server. However, there are situations where you may want to run your Flask app on a different port—either to avoid conflicts with other services or to match deployment settings. In this blog, we’ll explore how to change the port in a Flask app with simple and flexible methods.
Default Behavior of Flask
When you run a Flask application using app.run() without specifying any arguments, it starts the development server on localhost and listens on port 5000. Here's the basic setup:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello from Flask!'
if __name__ == '__main__':
app.run() # Runs on http://127.0.0.1:5000 by default
Changing the Port in app.run()
To run the Flask app on a different port, just pass the port parameter in the app.run() function. For example, to run it on port 8080:
if __name__ == '__main__':
app.run(port=8080) # Runs on http://127.0.0.1:8080
You can choose any open port number above 1024 if you're not running with administrator privileges.
Specifying Host and Port Together
If you want your app to be accessible over the network (not just on localhost), set the host to '0.0.0.0' and provide the desired port:
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000)
This allows other devices on the same network to access the app using your IP and port 3000.
Changing Port via Command Line
If you're using the flask run command, you can set the port directly from the command line:
flask run --port=7000
To make this work, ensure the FLASK_APP environment variable is set:
# On Windows (CMD)
set FLASK_APP=app.py
flask run --port=7000
# On Unix/macOS
export FLASK_APP=app.py
flask run --port=7000
Why Change the Default Port?
There are several reasons why you might want to change the default port:
- Another service is already using port 5000.
- You want to run multiple Flask apps simultaneously.
- You're deploying behind a reverse proxy with specific port requirements.
- You're mimicking a production environment locally.
Summary
Changing the port in a Flask app is simple and flexible. You can pass the port number directly in the app.run() call or through command line arguments using flask run --port=PORT. Knowing how to customize the port helps you manage your development environment more effectively and avoids potential conflicts.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:


Comments
Waiting for your comments