docker网络桥接-bridge(连接数据库失败)

1. 创建bridge

docker network create -d bridge accounts-db 

2. 创建容器时指定network

docker run -d -p 5050:5050 --name service-accounts-dev --network accounts-db edu/service-accounts:dev

3.查看service-accounts-dev容器network是否生效

  • docker inspect 135e4f3c2c8c (service-accounts-dev容器的id )
"Networks": {
               "accounts-db": {
                   "IPAMConfig": null,
                   "Links": null,
                   "Aliases": [
                       "135e4f3c2c8c"
                   ],
                   "NetworkID": "aca79174ebfbf0aa2d2d84fc6938532565023372db30911aa25b7d5a6218f514",
                   "EndpointID": "4a1977f8ed9ef3c9268b0375d7fd4750ed30a02715e1f04cedd1437d9bafc75c",
                   "Gateway": "172.20.0.1",
                   "IPAddress": "172.20.0.2",
                   "IPPrefixLen": 16,
                   "IPv6Gateway": "",
                   "GlobalIPv6Address": "",
                   "GlobalIPv6PrefixLen": 0,
                   "MacAddress": "02:42:ac:14:00:02",
                   "DriverOpts": null
               }
           }

4. 将accouns-db的bridge与mysql链接并查看network是否生效

docker network connect accounts-db localmysql
  • docker inspect 135e4f3c2c8c (localmysql容器的id )
"Networks": {
                "accounts-db": {
                    "IPAMConfig": {},
                    "Links": null,
                    "Aliases": [
                        "020490810acd"
                    ],
                    "NetworkID": "aca79174ebfbf0aa2d2d84fc6938532565023372db30911aa25b7d5a6218f514",
                    "EndpointID": "d0ad5990be95948c0d93950f3a0cccb1255b5c375b1f55aaeef51622b39fdb9b",
                    "Gateway": "172.20.0.1",
                    "IPAddress": "172.20.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:14:00:03",
                    "DriverOpts": {}
                }
            }

5. 进入service-accounts-dev的bash,ping mysql的ip地址,查看是否能ping通,能ping通则说明bridge已经完成

  • docker exec -it 135e4f3c2c8c bash
root@135e4f3c2c8c:/app# ping 172.18.0.3

  • 此时提示 ping: command not found,需要安装,使用指令:apt-get install iputils-ping 安装ping工具,
  • 若提示以下错误,需要先执行apt-get update,再执行apt-get install iputils-ping
bash: ping: command not found
root@135e4f3c2c8c:/app# apt-get install inetutils-ping
Reading package lists... Done
Building dependency tree        
Reading state information... Done
E: Unable to locate package inetutils-ping

6.修改链接mysql的链接地址

  • 方法1:server改为容器名(localmysql)
  • 方法2:server改为localmysql容器的ip
 database=edu.accounts;server=172.18.0.3;port=3306;uid=root;pwd=xxxxxx;
 或
 database=edu.accounts;server=localmysql;port=3306;uid=root;pwd=xxxxxx;

你可能感兴趣的:(docker网络桥接-bridge(连接数据库失败))