The Creative Network Session 10 — connecting to localhost of the machine from inside of a Docker container

Previous sessions

Stephens Xu
Fullstack Network

--

  1. Introduction session
  2. Setting up redux
  3. Home Page with React
  4. Setting up GraphQL
  5. GraphQL schema V1
  6. Integrating GraphQL in React with Lokka
  7. Building photo upload with AWS Lambda and S3
  8. Serverless architecture, Lambda and Gateways
  9. Deployment with Terraform and Docker

NEXT TWO SESSIONS:

Session 11: Tuesday, May 23rd 9:00pm PST

Session 12: Thursday, May 25th 9:00pm PST

Video for this session:

In first part of this session we worked with Docker to compile our lambda function in a linux environment. The second part is more interesting, where we found a nice solution to connect to localhost of the development machine from a docker container that runs on the same machine.

If you do development with Docker on a Mac computer and at some point you want to access some localhost service on the machine from inside of the docker container, such as your local mysql database, it’s actually quite a hassle. For example in my case, I have a simple web application that runs inside of the Docker and I wanted to connect to my local mysql, which runs outside of this docker container on my localhost 127.0.0.1 port 3306.

Apparently, locahost or 127.0.0.1 inside of docker container does not really have direct access to localhost of my development machine, it’s actually localhost of the container itself. We need to establish some sort of bridge in order to access localhost services from containers. As a matter of fact, a similar question on stackoverflow got 146,076 views(maybe this is a common issue people run into?).

Our solution is to use ngrok. ngrok creates secure tunnels to localhost and expose these connections to the outside world through HTTP or TCP.

IMPORTANT: If you want to use ngrok to work with TCP, you need to sign up for an account. You will receive an authentication token upon signing up. Signing up and using both HTTP/TCP are free of charge as of 05/11/2017.

Let’s use my case of connecting to local mysql service as an example.

Once I downloaded the ngrok client, I can simply do:

ngrok tcp 3306

This creates a tcp connection to port 3306 on my localhost machine, which is where mysql is running. ngrok would show a view such as this

So here ngrok is forwarding localhost:3306 to 0.tcp.ngrok.io:15629

Now inside of the docker container, I can access my localhost:3306 by doing this:

mysql --host 0.tcp.ngrok.io --port 15629 -u root

(second screenshot is using different port because ngrok rotate port with every start)

That’s it! Hope this helps. Join us at our next live streaming session if you wanna see more.

--

--