2017-05-03 89 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

相關問題