之前在非容器環(huán)境下啟用spring boot連接容器內(nèi)的mysql時沒問題,url如下:
jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=CTT
然后切換成用容器啟用spring boot的時候翔悠,報(bào)如下錯誤:
caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure
經(jīng)排查是因?yàn)閿?shù)據(jù)庫地址的問題。
因?yàn)橛萌萜鲉⒂胹pring boot的話,容器的localhost是本容器自身扳剿,因此此URL無法連接到mysql的容器,需要先找到mysql容器的IP地址昼激,可以用:
docker inspect mysql
查看mysql運(yùn)行的ip地址庇绽,下面截取了部分inspect后的內(nèi)容:
"NetworkSettings": {
"Bridge": "",
"SandboxID": "0c1d92762fc6ca2f74c1ef50924296778f9127c61ae3cdefd28e01150e43c5e0",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"3306/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "3306"
}
]
},
"SandboxKey": "/var/run/docker/netns/0c1d92762fc6",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "da20b50cae96f425944364e876036ebfe0a55d16c2e5011a6108d999403c08c6",
"Gateway": "172.17.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"MacAddress": "02:42:ac:11:00:02",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "945bdd4c50acef80817597aa8014c0f9698791387ebac0167d330ecbfe611706",
"EndpointID": "da20b50cae96f425944364e876036ebfe0a55d16c2e5011a6108d999403c08c6",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02",
"DriverOpts": null
}
}
}
}
可以看到mysql運(yùn)行時,分配的IP地址是172.17.0.2橙困,因此修改URL連接為:
jdbc:mysql://172.17.0.2:3306/database?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=CTT
就可以正常運(yùn)行了瞧掺。