Problem
I am connecting my java program to mysql but every time the ip adress of mysql container will be keep on changing. If it changes, i have to update that ip address in my java program for connection.(i have mentioned 172.17.0.2 in java program as mysql container ip).
Below is my simple jdbc java program
import java.sql.*;
import java.sql.Connection;
import java.lang.*;
public class Sample
{
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
String sql= "select * from student1;"; //insert into student1 values(2,'kalam');
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
System.out.println(e);
}
try{
conn = DriverManager.getConnection("jdbc:mysql://172.17.0.2:3306/university", "root", "root");
stmt = conn.createStatement();
//stmt.execute(sql);
ResultSet rs= stmt.executeQuery(sql);
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
System.out.println("value inserted");
}
catch(Exception e)
{
System.out.println(e+"driver man");
}
finally
{
try{
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
}
catch(SQLException e)
{
System.out.println(" conn problem");
e.printStackTrace();
}
}
}
}
Below is my docker-compose
mysql:
image: mysqlrep
container_name: mysqlcompose
environment:
- MYSQL_ROOT_PASSWORD= root
ports:
- "0.0.0.0:3306:3306"
command: bash -c "/etc/init.d/mysql start && cd /var/lib/mysql && mysql -u root && sleep 10"
java:
image: java:9
container_name: javacompose
links:
- mysql
command: bash -c "javac /compose/Sample.java && java -cp "./compose:./compose/mysql-connector-java-5.1.5-bin.jar" Sample"
volumes:
- ~/compose:/compose
I am using my own image called mysqlrep in mysql service inside docker compose.(i builded mysqlrep image using dockerfile which contains- mysql-server and i created my Database university, table called student1, inserted the values to it through my.sql file).
Now i have to set fixed ip address for mysql container so that i can provide it in my java program for connection(bcz it reduces the task to my client). How can i set it ?
Note:
I am using Docker toolbox on windows 7
docker version:
client version: 1.11.1, Os/Arch: windows/amd64
server version: 1.11.2, Os/Arch: linux/amd64
docker-compose version: 1.7.1
Please suggest...
mysqlas the hostname instead of an IP? If it's on the same docker-compose network, that should work.