2017-05-03 151 views
0

我部署了一个docker容器,该容器具有从openjdk7基本映像构建的简单Java-JDBC代码。无法连接到我的主机上从docker容器运行的mySql

现在我有我的本地计算机在端口3306上运行mysql。现在我怎样才能连接到从docker容器运行在主机上的mysql?

我一直在使用部署容器:

docker run -it -p 25000:27000 -p 3307:3306 94e56cffbdf7 bash 

但在容器中,当我尝试运行javaCode,我得到这样一个错误:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

如果我尝试连接到MySQL通过使用命令:

mysql -h 10.10.35.129 -p 3307 -u root -p 

其中10.01.35.129是我的主机的ip。

我得到错误:

bash: mysql: command not found

做参考,我还附上我想搬运工容器内运行的Java代码:

package jdbcCodes; 

import java.sql.*; 

public class MySqlJDBC { 

    public static void main(String[] args) { 
     try{ 
      Class.forName("com.mysql.jdbc.Driver"); 
      // here testEmp is DB name and root is user and xxx os password 
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/testEmp","root","xxx"); 
      Statement stmt = con.createStatement(); 
      ResultSet rs=stmt.executeQuery("select * from tempEntry"); 
      while(rs.next()){ 
       System.out.println(rs.getInt(1)+" "+rs.getString(2));   
      } 
      con.close();    
     } 
     catch(Exception e){ 
      System.out.println(e); 
     } 
    } 
} 

Repaeating我的问题:
如何瞬移到从docker contaimner运行在主机上的mysql?

+0

[从Docker容器内部,如何连接到本机的本地主机?](http://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container如何做我连接到本地主机) – Berger

回答

0

在码头集装箱内部,localhost指的是集装箱本身,除非您使用--network host,否则会产生其他后果。相反,您希望通过使用其IP地址10.10.35.129来引用主机。

mysql命令不能在容器中工作的原因是因为您没有安装它。默认情况下,在docker中,网络,进程,文件系统和用户(等等)都在容器内分离。

+0

我甚至尝试通过添加标志'--network host'来运行容器。还是同样的问题。 :( –

+0

使用该标志,请尝试使用127.0.0.1 – tcnj

相关问题