Im trying to create a docker image with a springboot application and a mysql database but im unable to connect to it from the springboot container.
Initially i thought the Springboot container exited after being unable to connect to the database due to it taking a while to start, but i created a .sh script so that the springboot container didn’t run before the db was initialized, but even with the .h i have been unable to connect to my db.
In the docker-compose i also tried removing all network related code since i thought i wasn’t necessary to specify a network if im building them together like this, but it seems like it has no effect, below you can find my Dockerfile, my docker-compose, the properties of the springboot app, and the little .sh script also a screenshot of the logs from the containers, any help is greatly appreciated!
Dockerfile
FROM maven:3.8.1-openjdk-11 AS build
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn clean package -DskipTests
FROM openjdk:11-jre-slim
RUN apt-get update && apt-get install -y default-mysql-client && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY wait-for-it.sh .
RUN chmod +x wait-for-it.sh
COPY --from=build /app/target/Spring-MyParcial-MVC-DataJPA-Yamid-Punto3-0.0.1-SNAPSHOT.jar .
CMD ["./wait-for-it.sh", "db:3306", "--", "java", "-jar", "Spring-MyParcial-MVC-DataJPA-Yamid-Punto3-0.0.1-SNAPSHOT.jar"]
docker-compose.yml
services:
app:
build: .
ports:
- "8080:8080"
depends_on:
db:
condition: service_healthy
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/test
SPRING_DATASOURCE_USERNAME: qwerty
SPRING_DATASOURCE_PASSWORD: qwerty
SPRING_JPA_HIBERNATE_DDL_AUTO: update
networks:
- app-network
db:
image: mysql:8.0
environment:
MYSQL_DATABASE: test
MYSQL_ROOT_PASSWORD: qwerty
MYSQL_USER: qwerty
MYSQL_PASSWORD: qwerty
ports:
- "3306:3306"
networks:
- app-network
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 10s
timeout: 10s
retries: 10
networks:
app-network:
driver: bridge
application.properties
# Database connection settings
spring.datasource.url=jdbc:mysql://db:3306/test
spring.datasource.username=qwerty
spring.datasource.password=qwerty
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
wait-for-it.sh
#!/bin/bash
# wait-for-it.sh
host="$1"
shift
cmd="$@"
until mysqladmin ping -h "$host" --silent; do
>&2 echo "MySQL is unavailable - sleeping"
sleep 1
done
>&2 echo "MySQL is up - executing command"
exec $cmd