Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to local MySQL server through Docker?

Tags:

docker

This is more a general question for how to connect to local services through Docker. There's a similar question in a Github issue here that doesn't seem to have any resolution. What I'm really looking for is to be able to do development locally against my local development MySQL server, then once I'm ready to deploy, to test locally against a newly created deploy candidate docker image.

Ideally, both get settings from the same place as well, so I could put mysql_server: host_ip. This seems like a typical use case. Is anything like this currently possible?

I'm using Boot2Docker specifically with MySQL server running on my host mac's OS X Yosemite NOT in a container. Would be cool to have a more general answer for future readers though.

like image 428
Eli Avatar asked Dec 18 '14 21:12

Eli


People also ask

Can I access localhost from docker?

Accessing the Host With the Default Bridge ModeYou just need to reference it by its Docker network IP, instead of localhost or 127.0. 0.1 . Your host's Docker IP will be shown on the inet line. Connect to this IP address from within your containers to successfully access the services running on your host.

How do I connect to a MySQL docker database?

Answer: MySQL Docker in a container instance can be connected through the command line by logging into the container. Once the connection is established, any SQL commands can be executed. Once the above command is executed, you will be prompted to enter the database password.


1 Answers

The Docker CLI docs give this solution (which assumes you are running on a Linux host with ):

Sometimes you need to connect to the Docker host from within your container. To enable this, pass the Docker host’s IP address to the container using the --add-host flag. To find the host’s address, use the ip addr show command.

The flags you pass to ip addr show depend on whether you are using IPv4 or IPv6 networking in your containers. Use the following flags for IPv4 address retrieval for a network device named eth0:

$ HOSTIP=`ip -4 addr show scope global dev eth0 | grep inet | awk '{print \$2}' | cut -d / -f 1`
$ docker run  --add-host=docker:${HOSTIP} --rm -it debian

Then the name docker inside the container will map to the host's IP address. For your case, you could use docker run --add-host=mysql_server:$(hostip) ...

If using Boot2Docker, it sets up a mapping to the host at a predefined address, so on that platform the equivalent to the above is just the one command:

$ docker run  --add-host=docker:192.168.59.3 --rm -it debian
like image 92
Bryan Avatar answered Oct 25 '22 23:10

Bryan