Skip to content
Fix Code Error

From inside of a Docker container, how do I connect to the localhost of the machine?

March 13, 2021 by Code Error
Posted By: Anonymous

So I have a Nginx running inside a docker container, I have a mysql running on localhost, I want to connect to the MySql from within my Nginx. The MySql is running on localhost and not exposing a port to the outside world, so its bound on localhost, not bound on the ip address of the machine.

Is there any way to connect to this MySql or any other program on localhost from within this docker container?

This question is different from “How to get the IP address of the docker host from inside a docker container” due to the fact that the IP address of the docker host could be the public IP or the private IP in the network which may or may not be reachable from within the docker container (I mean public IP if hosted at AWS or something). Even if you have the IP address of the docker host it does not mean you can connect to docker host from within the container given that IP address as your Docker network may be overlay, host, bridge, macvlan, none etc which restricts the reachability of that IP address.

Solution

Edit: If you are using Docker-for-mac or Docker-for-Windows 18.03+, just connect to your mysql service using the host host.docker.internal (instead of the 127.0.0.1 in your connection string).

As of Docker 18.09.3, this does not work on Docker-for-Linux. A fix has been submitted on March the 8th, 2019 and will hopefully be merged to the code base. Until then, a workaround is to use a container as described in qoomon’s answer.

2020-01: some progress has been made. If all goes well, this should land in Docker 20.04

Docker 20.10-beta1 has been reported to implement host.docker.internal :

$ docker run --rm --add-host host.docker.internal:host-gateway alpine ping host.docker.internal
PING host.docker.internal (172.17.0.1): 56 data bytes
64 bytes from 172.17.0.1: seq=0 ttl=64 time=0.534 ms
64 bytes from 172.17.0.1: seq=1 ttl=64 time=0.176 ms
...

TLDR

Use --network="host" in your docker run command, then 127.0.0.1 in your docker container will point to your docker host.

Note: This mode only works on Docker for Linux, per the documentation.


Note on docker container networking modes

Docker offers different networking modes when running containers. Depending on the mode you choose you would connect to your MySQL database running on the docker host differently.

docker run –network="bridge" (default)

Docker creates a bridge named docker0 by default. Both the docker host and the docker containers have an IP address on that bridge.

on the Docker host, type sudo ip addr show docker0 you will have an output looking like:

[[email protected]:~] $ sudo ip addr show docker0
4: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 56:84:7a:fe:97:99 brd ff:ff:ff:ff:ff:ff
    inet 172.17.42.1/16 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::5484:7aff:fefe:9799/64 scope link
       valid_lft forever preferred_lft forever

So here my docker host has the IP address 172.17.42.1 on the docker0 network interface.

Now start a new container and get a shell on it: docker run --rm -it ubuntu:trusty bash and within the container type ip addr show eth0 to discover how its main network interface is set up:

[email protected]:/# ip addr show eth0
863: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 66:32:13:f0:f1:e3 brd ff:ff:ff:ff:ff:ff
    inet 172.17.1.192/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::6432:13ff:fef0:f1e3/64 scope link
       valid_lft forever preferred_lft forever

Here my container has the IP address 172.17.1.192. Now look at the routing table:

[email protected]:/# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         172.17.42.1     0.0.0.0         UG    0      0        0 eth0
172.17.0.0      *               255.255.0.0     U     0      0        0 eth0

So the IP Address of the docker host 172.17.42.1 is set as the default route and is accessible from your container.

[email protected]:/# ping 172.17.42.1
PING 172.17.42.1 (172.17.42.1) 56(84) bytes of data.
64 bytes from 172.17.42.1: icmp_seq=1 ttl=64 time=0.070 ms
64 bytes from 172.17.42.1: icmp_seq=2 ttl=64 time=0.201 ms
64 bytes from 172.17.42.1: icmp_seq=3 ttl=64 time=0.116 ms

docker run –network="host"

Alternatively you can run a docker container with network settings set to host. Such a container will share the network stack with the docker host and from the container point of view, localhost (or 127.0.0.1) will refer to the docker host.

Be aware that any port opened in your docker container would be opened on the docker host. And this without requiring the -p or -P docker run option.

IP config on my docker host:

[[email protected]:~] $ ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
       valid_lft forever preferred_lft forever

and from a docker container in host mode:

[[email protected]:~] $ docker run --rm -it --network=host ubuntu:trusty ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
       valid_lft forever preferred_lft forever

As you can see both the docker host and docker container share the exact same network interface and as such have the same IP address.


Connecting to MySQL from containers

bridge mode

To access MySQL running on the docker host from containers in bridge mode, you need to make sure the MySQL service is listening for connections on the 172.17.42.1 IP address.

To do so, make sure you have either bind-address = 172.17.42.1 or bind-address = 0.0.0.0 in your MySQL config file (my.cnf).

If you need to set an environment variable with the IP address of the gateway, you can run the following code in a container :

export DOCKER_HOST_IP=$(route -n | awk '/UG[ t]/{print $2}')

then in your application, use the DOCKER_HOST_IP environment variable to open the connection to MySQL.

Note: if you use bind-address = 0.0.0.0 your MySQL server will listen for connections on all network interfaces. That means your MySQL server could be reached from the Internet ; make sure to setup firewall rules accordingly.

Note 2: if you use bind-address = 172.17.42.1 your MySQL server won’t listen for connections made to 127.0.0.1. Processes running on the docker host that would want to connect to MySQL would have to use the 172.17.42.1 IP address.

host mode

To access MySQL running on the docker host from containers in host mode, you can keep bind-address = 127.0.0.1 in your MySQL configuration and all you need to do is to connect to 127.0.0.1 from your containers:

[[email protected]:~] $ docker run --rm -it --network=host mysql mysql -h 127.0.0.1 -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 36
Server version: 5.5.41-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.

mysql>

note: Do use mysql -h 127.0.0.1 and not mysql -h localhost; otherwise the MySQL client would try to connect using a unix socket.

Answered By: Anonymous

Related Articles

  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Nginx refuses to read custom nginx.config when dockerized
  • Dockerize next.js and nginx at one Dockerfile
  • nginx docker alpine envsubst doesn't work when…
  • Is there a way to use nextjs with docker and nginx
  • How to connect to a docker container from outside…
  • How to remove MySQL completely with config and…
  • NextJS deploy to a specific URL path
  • Docker Networking - nginx: [emerg] host not found in…
  • Using variables in Nginx location rules
  • PHP-FPM and Nginx: 502 Bad Gateway
  • nginx - nginx: [emerg] bind() to [::]:80 failed (98:…
  • Rust: implementing an iterator from a vector of…
  • Docker command can't connect to Docker daemon
  • nginx / docker / ssl for localhost
  • Nginx fails to load css files
  • Nginx try_files not working for my Vue app
  • How to correctly link php-fpm and Nginx Docker containers?
  • Jenkins with nginx using docker Port 50000 config
  • How to define startup file in…
  • How to remove old and unused Docker images
  • Nextjs getInitialProps not working with NGINX
  • Node.js/Express.js App Only Works on Port 3000
  • How to mount host volumes into docker containers in…
  • Cannot connect to the Docker daemon on macOS
  • How to copy files inside a local virtual machine or…
  • Rebuild Docker container on file changes
  • How to create User/Database in script for Docker Postgres
  • Extracting stuffs from my Jenkins container docker…
  • phpMyAdmin on MySQL 8.0
  • Runing vue/cli app under docker simple index.html is opened
  • Nginx configuration setup for windows
  • Use SQL Server Management Studio to connect remotely…
  • NGINX reverse proxy to .netcore app gives bad gateway 502
  • docker command not found even though installed with apt-get
  • Error 'Map', but got one of type 'Null' flutter web…
  • Docker Compose wait for container X before starting Y
  • How to deal with persistent storage (e.g. databases)…
  • How to handle a redis connection error in express?
  • Run docker image on specific port
  • Node.js + Nginx - What now?
  • How to use Laravel docker container & MySQL DB…
  • Can Windows Containers be hosted on linux?
  • Trying to get a headless WordPress to do hot…
  • Can not connect to oracle outside docker container
  • Remix error The transaction has been reverted to the…
  • How can I initialize a MySQL database with schema in…
  • Error: getaddrinfo ENOTFOUND…
  • NullpointerException error while working with…
  • Exposing a port on a live Docker container
  • What is the difference between "expose" and…
  • Double port forwarding kubernetes + docker
  • nginx: [emerg] "server" directive is not allowed here
  • Cannot read property '$i18n' of undefined when using…
  • Oracle listener not running and won't start
  • webpack-dev-server npm run dev throwing TypeError:…
  • Error: Can't set headers after they are sent to the client
  • "configuration file /etc/nginx/nginx.conf test…
  • Should MySQL have its timezone set to UTC?
  • Best TCP port number range for internal applications
  • Serving Polymer PWA with nginx reverse proxy
  • How do I append a node to an existing XML file in java
  • WAMP server, localhost is not working
  • Smart way to truncate long strings
  • Cannot run docker:dind as docker:docker
  • Starting Docker as Daemon on Ubuntu
  • Nginx redirection different with IP behavior on 2…
  • Can't connect to docker from docker-compose
  • How to fix docker: Got permission denied issue
  • NGINX setup for separate Vue Frontend and Express Backend
  • Why are ARGS specified in `docker-compose.yml`…
  • How to find the default JMX port number?
  • Postman gives 401 Unauthorized - Spring Boot & MYSQL
  • Docker container will automatically stop after…
  • Mount current directory as a volume in Docker on Windows 10
  • Docker-Compose can't connect to Docker Daemon
  • why nginx ingress controller is deployed as a…
  • XAMPP MySQL password setting (Can not enter in PHPMYADMIN)
  • during wct test: Failed to load resource: the server…
  • SSH -L connection successful, but localhost port…
  • How to combine the data from two different…
  • How can I get docker running in Jenkins nodes which…
  • jmxterm: "Unable to create a system terminal" inside…
  • 16 to 1 mux using 2 to 1 mux in vhdl
  • How to change XAMPP apache server port?
  • How do you list volumes in docker containers?
  • Correctly configure webpack-dev-middleware with…
  • Kafka-Elasticsearch Sink Connector not working
  • Docker compose, running containers in net:host
  • (13: Permission denied) while connecting to upstream:[nginx]
  • Docker compose build time args from file
  • Cannot receive data from ORSSerialPort
  • Aurelia, Docker, Nginx, AWS Elastic Beanstalk…
  • Docker remove TAG images
  • Vue npm run serve starts on random port
  • NGinx Default public www location?
  • RegEx match open tags except XHTML self-contained tags
  • How to know if docker is already logged in to a…
  • Nginx serves .php files as downloads, instead of…
  • Forward host port to docker container

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I make calls to a REST API using C#?

Next Post:

How can I get last characters of a string

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error