天天看點

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