docker container 访问外部宿主机服务

docker 容器的默认网络是采用桥接的形式(和主机在同一个局域网中,但是单独使用一个独立的局域网IP),程序在生产环境中运行时,连接数据库、redis等只需要配置对应的服务地址就可以了。

在开发环境中,如果服务在docker中运行,数据库在本机运行,配置数据库连接的时候配置 127.0.0.1 就不好使了。

可以用两种方式解决这个问题。

一是将宿主机和容器看着是独立的两台机器,在配置地址的时候配置宿主机的局域网ip或是公网ip。

二是将宿主机地址直接写成: host.docker.internal,不过第二种方式需要docker 版本 大于 18.03,且要在windows和mac下才能用。

要测试这两个方式能不能访问宿主机,可以直接用docker运行一个镜像在命令行进行ping测试:

# Start the Alpine container and drop into a Shell prompt.
docker container run --rm -it alpine sh

# Install the ping utility.
apk update && apk add iputils

# Ping your local network IP address (replace my IP address with yours).
ping 192.168.1.3

# You should see this output (hit CTRL+C to stop it):
PING host.docker.internal 56(84) bytes of data.
64 bytes from 192.168.1.3: icmp_seq=1 ttl=37 time=0.539 ms
64 bytes from 192.168.1.3: icmp_seq=2 ttl=37 time=0.417 ms
64 bytes from 192.168.1.3: icmp_seq=3 ttl=37 time=0.661 ms

最后,本地的数据库,像mysql这种,默认是没有开启外部访问权限的,需要去手动开启。

# 授权
mysql> grant all privileges  on *.* to root@'%' identified by "yourpwd";
# 报错及处理方式
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
mysql> SET GLOBAL validate_password_policy=LOW;
Query OK, 0 rows affected (0.00 sec)

mysql> grant all privileges  on *.* to root@'%' identified by "yourpwd";
Query OK, 0 rows affected, 1 warning (0.01 sec)

# 刷新权限
mysql>FLUSH PRIVILEGES

mysql> quit
Bye

参考资料: 

    https://nickjanetakis.com/blog/docker-tip-35-connect-to-a-database-running-on-your-docker-host

    https://nickjanetakis.com/blog/docker-tip-65-get-your-docker-hosts-ip-address-from-in-a-container?

    https://www.cnblogs.com/cnblogsfans/archive/2009/09/21/1570942.html

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值