从docker容器访问主机数据库

从docker容器访问主机数据库

本文介绍了从docker容器访问主机数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一台主机上运行的mysql数据库,并且该主机也运行docker容器:我如何从在主机上运行的docker容器中访问mysql数据库?

If I have a mysql database running on some host machine, and that host is also running a docker container: How would I access the mysql database from within the docker container that is running on the host?.

例如,是否有一种方式将主机端口发布到容器(与docker运行-p相反)?

For instance, is there a way to publish a hosts port to the container (the inverse of what docker run -p does)?

推荐答案

有一些长期的讨论,如何以一致,理解和便携的方式做到这一点。没有完整的解决方案,但我会链接到下面的讨论。

There are several long standing discussions about how to do this in a consistent, well understood and portable way. No complete resolution but I'll link you to the discussions below.

无论如何,你们都想尝试使用--add-host选项来停靠运行添加将主机的ip地址放入容器的/ etc / host文件中。从这里,在任何所需的端口上连接到主机是微不足道的:

In any event you many want to try using the --add-host option to docker run to add the ip address of the host into the container's /etc/host file. From there it's trivial to connect to the host on any required port:

您可以使用
一个或多个--add-host标志将其他主机添加到容器的/ etc / hosts文件中。此示例为名为docker的
主机添加了静态地址:

You can add other hosts into a container's /etc/hosts file by using one or more --add-host flags. This example adds a static address for a host named docker:

 $ docker run --add-host=docker:10.180.0.1 --rm -it debian
    $$ ping docker
    PING docker (10.180.0.1): 48 data bytes
    56 bytes from 10.180.0.1: icmp_seq=0 ttl=254 time=7.600 ms
    56 bytes from 10.180.0.1: icmp_seq=1 ttl=254 time=30.705 ms
    ^C--- docker ping statistics ---
    2 packets transmitted, 2 packets received, 0% packet loss
    round-trip min/avg/max/stddev = 7.600/19.152/30.705/11.553 ms

注意:有时您需要连接到Docker主机,这意味着
获取主机的IP地址。您可以使用以下shell
命令简化此过程:

Note: Sometimes you need to connect to the Docker host, which means getting the IP address of the host. You can use the following shell commands to simplify this process:

 $ alias hostip="ip route show 0.0.0.0/0 | grep -Eo 'via \S+' | awk '{ print \$2 }'"
 $ docker run  --add-host=docker:$(hostip) --rm -it debian


文档:

从容器访问主机的讨论:

Discussions on accessing host from container:

这篇关于从docker容器访问主机数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 13:36