KiKo
KiKo

Reputation: 1710

SpringBoot docker connect to mysql docker container

I pulled mysql docker image and run container with command:

docker run --name myapp-mysql -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=mydb -p 3306:3306 -d mysql:latest

At this point springBoot locally is working. It is connected with mysql:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root

Now I want springBoot app also to be on separate docker container, on the same server. For that I'm using Dockerfile:

FROM openjdk:8-jdk-alpine
ADD target/myapp.jar myapp.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "myapp.jar"]

I'm starting this image with:

docker run --name myapp -p 8080:8080 -it myapp:latest

Now springBoot container cannot find myslq container. I try:

docker run --name myapp -p 8080:8080 --link=myapp-mysql:mysql -it myapp:latest

But again it cannot connect to mysql container. How can I connect springBoot container to mysql container?

I also tried to change application.properties to:

spring.datasource.url=jdbc:mysql://myapp-mysql:3306/mydb
spring.datasource.username=root
spring.datasource.password=root

and start springBoot with:

docker run --name myapp -p 8080:8080 --link=myapp-mysql:mysql -it myapp:latest

Again it cannot connect to db:

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.

Upvotes: 0

Views: 2090

Answers (1)

Vijay Daswani
Vijay Daswani

Reputation: 142

In order to link the containers, I will suggest look into docker-compose.

If you don't want to use docker-compose then,

First of all, In your springboot properties file, change the url to:

spring.datasource.url=jdbc:mysql://[container-name]:3306/mydb

In your case,

docker run --name myapp-mysql -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=mydb -p 3306:3306 -d mysql:latest

container-name: myapp-mysql

then try to run both containers.

if it doesn't work then look into docker networks & put the containers in same network.

Docker Network Creation

Upvotes: 2

Related Questions