Search code examples
pythonflaskgunicorn

Make python Flask application accessible from the Internet with gunicorn


what I have:
I made a simple web application using Flask, which woks great on the localhost.

what I want to achieve:
I want to deploy it so it is visible in the internet.


Because Flask says that the production server should not be used for deployment I installed gunicorn.
I managed to get it working on localhost (running gunicorn server:app).

Then I tried to make it public using the -b 0.0.0.0:5000 option. it said it is running on 192.168....:5000 Now I could access the website using that ip address from my computer and also from my phone connected to the same wifi. however I was unable to connect to the website when I didn't use this wifi.

when I searched about this, I found out that the 192.168.... ip address range is reserved to the local network and cannot be accessed from anywhere else.

how do I need to run the script so it is accessible from everywhere? Do I need to modify the firewall settings? Maybe there is a better way to deploy such an app on the local machine using a different framework?

Just some additional information:

  • python version: 3.9
  • I am using a venv (and installed flask and gunicorn into it)
  • os: macos 11.6.1 (I could run it on an Ubuntu machine if that is easier)

Solution

  • You would need to do the following steps:

    • read up and learn a lot about security for Web servers, then read some more, it is fraught with risks

    • find your Mac's IP address on your local network and make sure it is fixed, i.e. set as static on your Mac (under "System Preferences->Network") or reserved in your router's DHCP tables (by putting your Mac's MAC address in its allocation tables) so that it always gets the same local address on your internal network when it boots

    • log into your router and set up "Port Forwarding" to forward external requests (coming from the Internet) for port 5000 (or some other port) to your Mac's fixed IP address and the port 5000 where Gunicorn is serving

    • log into your router and find your WAN IP address, or go to http://whatsmyip.com to get the address you need to put in your browser, or your friends need to put in their browsers to see your shiny new website

    • as it stands, this will work until the next time your router reboots when your ISP will likely allocate it a new IP address. If you want it permanent, you need to either 1) ask your ISP for a static IP address, or 2) subscribe a DDNS service (e.g. noip.com or dyndns.com) or 3) tell your friends your new IP address every time you reboot your router


    Updated July 2023

    Note that with the advent of tailscale this answer would be very different. You could install tailscale on your Mac and share its IP address securely with selected friends...