运行在容器中的spring boot连接容器中mysql报错

之前在非容器环境下启用spring boot连接容器内的mysql时没问题,url如下:

jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=CTT

然后切换成用容器启用spring boot的时候,报如下错误:

caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

经排查是因为数据库地址的问题。
因为用容器启用spring boot的话,容器的localhost是本容器自身,因此此URL无法连接到mysql的容器,需要先找到mysql容器的IP地址,可以用:

docker inspect mysql

查看mysql运行的ip地址,下面截取了部分inspect后的内容:

"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运行时,分配的IP地址是172.17.0.2,因此修改URL连接为:

jdbc:mysql://172.17.0.2:3306/database?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=CTT

就可以正常运行了。

你可能感兴趣的:(运行在容器中的spring boot连接容器中mysql报错)