How to Allow Remote Connections to Flask Web Service

Flask is a pretty good web framework for Python based on Werkzeug, Jinja 2 and good intentions. It is lightweight, which can help you easily and quickly set up a web application starting from scratch.

For how to build up a web service, please follow the quickstart guide.

Problem

After successfully finishing your web service, you can run it with your Python interpreter. Make sure to not call your application flask.py because this would conflict with Flask itself.

For example, your service script is saved in file hello.py. Start the service with the following command.

1
2
$ python hello.py
* Running on http://127.0.0.1:5000/

Now head over to http://127.0.0.1:5000/, and you should see your service.

You can accees the running service from the localhost. But you may cannot access this service from any other remote machines, such as 192.168.1.100.

Solution

There may be serveral reasons that cause this kind of error.

Please make sure that your HTTP service is listenning on 192.168.1.100:5000 or everywhere ( 0.0.0.0:5000 ) by checking the output of

1
2
$ netstat -tupln | grep ':5000'
tcp 0 0 192.168.1.100:5000 0.0.0.0:* LISTEN 5423/python

If not, please bind the host to an address other than localhost.

Just as the doc said,

If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer.

If you have debug disabled or trust the users on your network, you can make the server publicly available simply by changing the call of the run() method to look like this:

1
2
# runs on its own IP address
app.run(host='192.168.1.100')

or

1
2
# This tells your operating system to listen on all public IPs.
app.run(host='0.0.0.0')

Remember to restart the service manually after each change to your code.

If it is, allow the traffic using iptables:

1
$ iptables -I INPUT -p tcp --dport 5000 -j ACCEPT

Reference