java 如何连接在 docker 中作为容器运行的 MySQL DB?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44780571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to connect with MySQL DB running as container in docker?
提问by JustStartedProgramming
Can some give me any idea about how to connect with my mysql db which is running as a container in Docker on a virtual machine?
有人可以让我知道如何连接我的 mysql 数据库,该数据库在虚拟机上的 Docker 中作为容器运行吗?
I have no idea about it, please help me.
我对此一无所知,请帮助我。
What I am trying to do is :- I am writing a java program on my local machine and now I want to establish a jdbc connection with mysql. My MySQL DB is running as a docker container on a Virtual machine.
我想要做的是:- 我正在本地机器上编写一个 java 程序,现在我想与 mysql 建立 jdbc 连接。我的 MySQL 数据库在虚拟机上作为 docker 容器运行。
Does someone has any idea.
有没有人有任何想法。
Connection con = DriverManager.getConnection("jdbc:mysql://10.0.2.15/"what should I put here","root","myrootpassword");
Connection con = DriverManager.getConnection("jdbc:mysql://10.0.2.15/ "我应该在这里放什么","root","myrootpassword");
my ip address for the container is 172.17.0.2 and my guest ip is 10.0.2.15. My sql is running on port 3306.
我的容器 ip 地址是 172.17.0.2,我的访客 ip 是 10.0.2.15。我的 sql 在端口 3306 上运行。
Thanks in Advance
提前致谢
回答by Clem
Your docker container should be able to bind its mysql port to any port on the VM. You do it with the -p VMPort:containerPort
option of docker run
.
您的 docker 容器应该能够将其 mysql 端口绑定到 VM 上的任何端口。您可以-p VMPort:containerPort
选择docker run
.
https://docs.docker.com/engine/reference/run/#expose-incoming-ports
https://docs.docker.com/engine/reference/run/#expose-incoming-ports
So this command
所以这个命令
docker run -p 3306:3306 your-sql-container
Will publish the 3306 port of your container to the 3306 port of your VM.
将容器的 3306 端口发布到 VM 的 3306 端口。
At that point you should be able to hit your SQL with
那时你应该能够用你的 SQL
Connection con = DriverManager.getConnection("jdbc:mysql://10.0.2.15:3306/databaseName","root","myrootpassword");
I used your VM address and the binded port on the VM. You should replace databaseName
with the actual name of your DB.
我使用了您的 VM 地址和 VM 上的绑定端口。您应该替换databaseName
为您的数据库的实际名称。
回答by OpsEco
You will need to put Database name there.
conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
Check out this link
您需要将数据库名称放在那里。
conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
看看这个链接
Also, it would not hurt to add port in your connector.
此外,在连接器中添加端口也无妨。