1
votes

I'm leaning docker and trying to connect a db in my java application.

I already create the container and started it

5621fc9b438d mysql/mysql-server:latest "/entrypoint.sh mysq About an hour ago Up About an hour 3306/tcp mysql-db

I also accessed the container and create one database by bash. I'm having problem to connect the db on Java class.

My Java method

 @Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost/mydb");
    dataSource.setUsername("mysql-db");
    dataSource.setPassword("root");
    return dataSource;
}

How can I connect and use my docker mysql database on Java application?

1
Do you have to specify the port# to 'setUrl'?ethrbunny
yes, dataSource.setUrl("jdbc:mysql://localhost:3306/mydb");Mauricio Lassakoski

1 Answers

0
votes

Make sure you have open your port 3306 to the outside with -p 3306:3306 (not just -p 3306). By default, only linked container will be able to access your mysql port.

Finally, if you are running Docker with a docker-machine, you will need to speficy the ip generated for the Docker VM rather than localhost.

Good luck.