I am trying to connect my service to MySQL docker container via docker-compose. The connection is refused. I tried to run MySQL docker image and connect my running service to it locally. the connection is established and everything is working fine. The problem is when I want to run both the service and MySQL container, the connection is refused. I created the custom network and tried many solutions but it has already taken me 2 days!
the docker compose configs are:
version : '3.8'
services:
healthcare:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
depends_on:
- mysql
restart: always
environment:
RDS_URL: mysql
networks:
- saman-network
mysql:
image: mysql:8-oracle
container_name:
mysql
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: hospital_db
MYSQL_USER: saman
MYSQL_PASSWORD: saman
volumes:
- myvolume:/var/lib/mysql
ports:
- "3308:3306"
networks:
- saman-network
volumes:
myvolume:
networks:
saman-network:
the application.properties configs are:
server.port=8080
spring.application.name=healthcare
spring.datasource.url=jdbc:mysql://${RDS_URL:localhost}:3308/hospital_db
spring.datasource.username=saman
spring.datasource.password=saman
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
the error I am getting:
springboot-hospitalmng-sample-healthcare-1 | ... 46 common frames omitted
springboot-hospitalmng-sample-healthcare-1 | Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure
and
springboot-hospitalmng-sample-healthcare-1 | ... 59 common frames omitted
springboot-hospitalmng-sample-healthcare-1 | Caused by: java.net.ConnectException: Connection refused
springboot-hospitalmng-sample-healthcare-1 | at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
springboot-hospitalmng-sample-healthcare-1 | at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672) ~[na:na]
springboot-hospitalmng-sample-healthcare-1 | at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:542) ~[na:an]
springboot-hospitalmng-sample-healthcare-1 | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
springboot-hospitalmng-sample-healthcare-1 | 2023-01-05T14:20:37.165Z ERROR 1 --- [ main] j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
CodePudding user response:
I think this is the problem. mysql runs on port 3306, you expose it on the host on 3308. But from the configuration you connect through the docker network using RDS_URL
but port 3308, it should be 3306 instead