0

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.
1

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.