0

My goal is to deploy a Rest API on a docker container but I have the following error

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

Firstly, I created the mysql container with the following line of code:

docker run -d -p 3307:3306 --name mysqldb -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=user mysql

it succesfully connected, but when I want to create the api container I got the error, this is the line of code that I typed:

docker run -p 9090:8080 --name myuserapp --net spring-net -e MYSQL_HOST=mysqldb -e MYSQL_USER=root -e MYSQL_PASSWORD=root -e MYSQL_PORT=3306 userapp/service

Additionally, I add my configuraton properties and Dockerfile files:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3307/user
spring.datasource.username=root
spring.datasource.password=root

Dockerfile:

FROM openjdk:11 as build
MAINTAINER Andres
COPY target/user-0.0.1-SNAPSHOT.jar user-0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java", "-jar","user-0.0.1-SNAPSHOT.jar"]

 

I really appreciate if someone can help me.

2
  • 1
    Your MySQL container should use the same network as your other container (spring-net). Also, you are using localhost in your configuration file(?), it should be mysqldb. Commented Jun 28, 2022 at 4:12
  • I did eerything that you mentioned, but when the I switched localhost to mysqldb the rest api didn't compile. Could you please give another tip? Commented Jun 28, 2022 at 4:48

1 Answer 1

0

First of all - you can't use loopback adress for inter-communication between hosts. Docker containers are different hosts and each has it's own loopback.

You should create network first

docker network create mysqlnetwork

then you should add containers to that network (don't even need to expose ports, your local machine don't need an access in my example)

lets start tomcat (it works on 8080 port by default)

docker run -d --name tomcat --network mysqlnetwork tomcat:8.5.38

then start nginx (it works on 80 by default)

docker run -d --name nginx  --network mysqlnetwork nginx:latest

as we specify names of containers (--name tomcat), we can use that named for requests (dns-names)

check access from nginx container to tomcat container using name (it will print html response)

docker exec nginx curl http://tomcat:8080

check access from tomcat container to nginx container using name (it will print html response)

docker exec tomcat curl http://nginx

Now you can connect your containers with network and use container names and their ports (not exposed to local machine, but their own; not forwarded 3307, but 3306 for mysql).

I have not enought reputation to comment. If you still have any questions, i'll answer under that answer.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.