How to connect to a running mysql service on host from a docker container on same host

March 31, 2020

Introduction

I have a host running mysql (not on a container). I have to run an nodejs app inside a container and access that mysql service here. Note: The host is not exposed on internet or local network.

When I’m inside that nodejs container, I can not use

  • localhost, as it would refer to the container’s IP, not the host
  • , I can not use the hostname, as the host is not exposed to the internet or local network

Running container in Host networking mode

Docker provides lot of networking models. One of them is to use Host networking.

docker run -it --net=host -d node

Now when inside the container, you try to use hostname as localhost, it will work like a charm.

Docker host networking mode

With this networking mode, the container shares the same networking space as of host. The container does not gets its own ip. Example, if you run apache container on port 8080 with this networking mode. That service is available on localhost:8080 on host, without need to expose or binding the port.

It is important to note that with this option, port binding options are ignored like -p, —publish. And, this mode works only on linux hosts. This do not work on docker for mac, windows.


Similar Posts

Latest Posts