Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect with MySQL DB running as container in docker? [duplicate]

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?

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.

Does someone has any idea.

Connection con = DriverManager.getConnection("jdbc:mysql://10.0.2.15/"what should I put here","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.

Thanks in Advance

like image 486
JustStartedProgramming Avatar asked Jun 27 '17 12:06

JustStartedProgramming


Video Answer


2 Answers

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.

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.

At that point you should be able to hit your SQL with

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.

like image 54
Clem Avatar answered Sep 27 '22 21:09

Clem


You will need to put Database name there. conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password"); Check out this link

Also, it would not hurt to add port in your connector.

like image 23
Aniruddha J Avatar answered Sep 27 '22 22:09

Aniruddha J