1

I have deployed a docker container having a simple Java-JDBC Code build from openjdk7 base image.

Now I have mysql running on my local machine on port 3306. Now How can I connect to mysql running on host machine from docker container?

I have deployed container using:

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

But in the container, when I try to run the javaCode, I get an error like:

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.

If I try to connect to mysql by using the command:

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

where 10.01.35.129 is my host machine's ip.

I get error:

bash: mysql: command not found

For refrence I am also attaching the Java Code I am trying to run inside docker container:

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 my question:
How to conect to mysql running on host machine from docker contaimner?

Prashant Prabhakar Singh
  • 1,120
  • 4
  • 15
  • 33
  • Possible duplicate of [From inside of a Docker container, how do I connect to the localhost of the machine?](http://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach) – Arnaud May 03 '17 at 07:10

1 Answers1

1

Inside a docker container, localhost refers to the container itself, unless you use --network host, which has other consequences. Rather, you want to refer to the host by using its IP address, 10.10.35.129.

The reason why the mysql command is not working in the container is because you don't haven't it installed. By default in docker, networking, processes, filesystems and users (amongst others) are all seperated inside the container.

tcnj
  • 495
  • 4
  • 10