I have a docker compose which contains the following instructions :
version: '3.8'
services:
mysql-standalone:
container_name: marqueblanchebd
image: marqueblanchebd:latest
ports:
- "3307:3306"
volumes:
- data:/var/lib/mysql
spring-boot:
image: testmb
container_name: mbwebservice
ports:
- "8091:8080"
build:
context: .
dockerfile: Dockerfile
depends_on:
- mysql-standalone
environment:
SPRING_DATASOURCE_PASSWORD: ramses2021
SPRING_DATASOURCE_URL: jdbc:mysql://marqueblanchebd:3307/marque_blanche?useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
SPRING_DATASOURCE_USERNAME: root
volumes:
- ./:/uploads/deployment
volumes:
data:
when i run docker-compose up the following error occurs from my springboot project:
Caused by: java.net.ConnectException: Connection refused (Connection refused)
But when i put the default mysql port 3306 ("3306:3306") in docker-compose file, my springboot project connects itself successfully to my database container.
Here is my mysql dockerfile :
FROM mysql:latest
EXPOSE 3307
ENV MYSQL_DATABASE=marque_blanche
ENV MYSQL_ROOT_PASSWORD=ramses2021
ADD marque_blanche.sql /docker-entrypoint-initdb.d
2
Answers
I will suggest a simple way to solve the problem :
Just insert this line in docker compose file for mysql service:
As it is said in this link
Inside the
docker network
the service namemarqueblanchebd
will resolve to the containers IP. Given theSPRING_DATASOURCE_URL=jdbc:mysql://marqueblanchebd:3307/...
the connection attempt is done to the<container_ip>:3307
however the database is listening on port3306
hence the connection is refused. For the connection to work you’d need to configure themysql
service to listen on port3307
instead of port3306
. The traffic does not transit out of thedocker network
to the host then from the host back into thedocker network
.I’d suggest not exposing the database to the host, you can remove the
ports
mappings from themysql-standalone
service e.g.:… and configure the
spring-boot
service to use the defaultmysql-standalone
service port:This would isolate the database inside of the
docker network
.