如何通过app container-docker连接mysql容器的localhost:3306 [英] How to connect localhost:3306 of mysql container via app container- docker

查看:25
本文介绍了如何通过app container-docker连接mysql容器的localhost:3306的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序设置中,我使用以下设置连接到数据库

In my application setting I am connecting to db with below settings

spring.jpa.hibernate.ddl-auto=none
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/gosallowMultiQueries=true&createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root

现在我有两个容器 App 和 mysql.我已经链接了两个容器

Now I have two container App and mysql. I have linked both container

docker run --name app --link mysql:dbalias appimage

但我收到通信链接故障错误.我无法连接到 mysql 服务器

but I am getting Communications link failure error. I am not able to connect with mysql server

我使用下面的命令来运行 mysql 容器:

I used below command to run mysql container:

docker run --name mysql -e MYSQL_ROOT_PASSWORD=root -d -p 3306:3306 mysql:latest

有什么建议吗?

推荐答案

你指向 localhost 这意味着应用程序正在尝试连接到它自己的容器的 localhost.不是您主机的本地主机.

You are pointing to localhost which means the app is trying to connect to localhost of it's own container. NOT the localhost of your host.

如果这两个容器部署在同一个用户定义的桥接网络中,您可以使用容器名称进行通信:

If those 2 containers are deployed inside the same user defined bridge network you can can communicate using container names:

spring.datasource.url=jdbc:mysql://mysql:3306/gosallowMultiQueries=true&createDatabaseIfNotExist=true

spring.datasource.url=jdbc:mysql://mysql:3306/gosallowMultiQueries=true&createDatabaseIfNotExist=true

如果不是,您可以使用 mysql 容器的容器 IP,但这会在容器重新启动/重新创建时发生变化.推荐的方法是创建一个用户定义的桥接网络:

if they aren't you can use the container IP of the mysql container but this can change when the container restarts/is recreated. The recommended approach is to create a user defined bridge network:

$ docker network create my-network
$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
73df63463bb2        bridge              bridge              local
4cabe965c01d        host                host                local
c94ae182d8fa        my-network          bridge              local
93ec6f5bf028        none                null                local

并在同一个网络中启动你的两个容器:

and start your two containers inside the same network:

$ docker run --name mysql --network=my-network -e MYSQL_ROOT_PASSWORD=root -d -p 3306:3306 mysql:latest

当两个容器在同一个用户定义的网络中启动时,您可以使用容器名称进行通信(您可以在其中一个容器内通过 docker exec 进行测试,并尝试使用容器名称 ping 另一个容器).

When both containers are started inside the same user defined network you can communicate using container name (you can test by docker exec inside one of the containers and try to ping the other one using the container name).

这篇关于如何通过app container-docker连接mysql容器的localhost:3306的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆