0
I’m starting in the container world, and when trying to upload an application developed in Springboot with mysql integration in Docker in an aws ec2, the application does not connect to mysql.
Mistakes:
...
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure
...
Caused by: java.net.UnknownHostException: mysql_server
Docker-Compose.yaml:
version: '3.8'
networks:
api-network:
driver: bridge
volumes:
mysql-vol:
services:
mysql_server:
image: mysql:5.6
volumes:
- mysql-vol:/var/lib/mysql
ports:
- "3306:3306"
environment:
- MYSQL_DATABASE=ecommerce
- MYSQL_USER=root
- MYSQL_ALLOW_EMPTY_PASSWORD=yes
networks:
- api-network
api_ecommerce:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
networks:
- api-network
depends_on:
- mysql_server
application properties:
server.port=8080
spring.datasource.url=jdbc:mysql://mysql_server:3306/ecommerce
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
mysql in pom.xml:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
Have you checked if the container is started and accessible? may be that your application has started before mysql is available and responding, "depends_on" does not guarantee that it will wait for the other container to be 100% functional to start
– Ricardo Pontual
@Ricardopunctual the application is going up before mysql, as I can ensure that mysql goes up first?
– cazzruan
has some scripts that keep trying to close a connection with the server to validate this, but ideally your application is resilient to it. A good idea is, at the spring startup if you can’t connect, generate a break I don’t know 5s and try again, and then yes give error, but if you do this in the application you won’t have to worry about the containers
– Ricardo Pontual
thanks for the help!
– cazzruan
You are able to connect in the database with a mysql client normally?
– leandro.dev
@leandro.dev yes, normally connects in a mysql client, the problem is that sometimes in running Docker-Compose, the application is started before mysql, then this error occurs. then you have to run Docker-Compose until mysql is started first!
– cazzruan
@cazzruan, you can create a script in bash to verify that the connection to the database is active; if so, the execution of script; otherwise, awaits. Control startup and shutdown order in Compose. You can use the script with nc or Wait-for-it, dockerize, Wait-for or even the mysqladmin.
– Valdeir Psr
@cazzruan in this question has an answer that I think fits with your question https://answall.com/a/445963/24201
– arkanjoms