Expose Local Servers to the Outside World Tunnelling with ngrok

Imagine you develop a web application and want to make it publicly available for other people (or yourself) to access it but you don't have money or time to deploy it in a public server. In other words, you want to run the application on your localhost but want others to access it.

I'm sure many would think of configuring the router, map ports, etc. Too much work, isn't it? Read the following with a salesman voice: What if I told you now you can share a URL with anybody so that your localhost server is accessible from anywhere in the world in a secure way?


Tunnelling with ngrok

There is an amazing tool called ngrok for this purpose where you can register for free. You can download it, extract it and add an add an authorisation token (available at your account's control panel) so that you can run a tunnel between your localhost and ngrok in the cloud and receive external requests.

Let's see this with an example:
  1. Clone a sample web application that can run on port 5000
    git clone https://gitlab.com/iberodev/DiDrDe.DotNetCoreWeb.git
  2. With a bash like Git Bash go to the cloned folder and ompile this .NetCore solution
  3. dotnet build
  4. Run the web application within the folder where the Startup.cs is located. The web application would be accessible at http://localhost:5000
    cd DiDrDe.DotnetCoreWeb
    dotnet run
  5. Start the tunnel with ngrok by going to the folder where ngrok.exe is and running the following
    .ngrok http 5000
  6. Go to ngrok account and under status you can find the public URL that you can access or share so that anybody's requests to that URL can be tunnelled to your localhost's web application. For example: http://2efac2cc.ngrok.io/

Isn't this amazing?

Some things to notice:
  • The free account on ngrok will change the tunnelled URL each time you run the tunnel. So if you want to have always the same public URL you will have to pay. Fair enough.
  • Sometimes, your web application could freak out if the request header does not come from localhost (because it thinks that it's running only on localhost for local requests) and will return a 400 Bad Request. To allow the external requests simply run the tunnel with the following option
    ./ngrok http 5000 -host-header="localhost:5000"
    

Comments