Setting up a custom host and port in a Flask application is a simple but important step. Flask is a web framework for building web applications with Python. By default, Flask runs on localhost (127.0.0.1) and port 5000. However, you might need to change these settings for different reasons, such as testing on a different machine or using a specific port.
This guide will help you understand how to set up a custom host and port for your Flask app, making your application more flexible and ready for various environments.
Flask’s Default Host and Port Settings
By default, a Flask app runs on localhost (127.0.0.1) and port 5000. You can start a basic Flask app with these lines of code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
When you run this script, your Flask app is accessible from your local machine at http://127.0.0.1:5000 or http://localhost:5000.
Changing the Host and Port in flask
Sometimes, you might need your app to be available on a different host or port. For example, if you’re deploying your app on a server, you may want it to be accessible from any IP address, not just localhost. Or, port 5000 might be used by another app on your server.
Flask lets you set a custom host and port when you start your app, like this:
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
Setting the host to ‘0.0.0.0’ makes your app accessible from any IP address. Setting the port to 8080 (or any other port number) changes the port your app listens on.
Using Environment Variables for Host and Port
Hardcoding the host and port in your app might not be the best way, especially if you’re running your app in different environments (e.g., development, testing, production).
A better way is to use environment variables to set the host and port. Flask makes this easy:
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
host = os.getenv('FLASK_HOST', '127.0.0.1')
port = os.getenv('FLASK_PORT', '5000')
app.run(host=host, port=int(port))
In this code, we use the os.getenv function to get the values of the FLASK_HOST and FLASK_PORT environment variables. If these variables are not set, the function returns default values: ‘127.0.0.1’ for the host and ‘5000’ for the port.
This way, you can easily change the host and port settings by setting environment variables, without changing your app’s code. You can set these variables in your server’s operating system or in a configuration file if you’re using a tool like Docker or Kubernetes.