Uma forma que encontrei para executar o MySQL no Docker sempre que o Spring Boot inicializar, sem a necessidade de ter que abrir o terminal e passar comandos Docker, é por meio da criação de um arquivo docker-compose.dev.yml
e da adição de algumas dependências no pom.xml
e configurações no application-dev.yml
.
docker-compose.dev.yml
:
services:
mysql:
image: 'mysql:9.1.0'
environment:
- 'MYSQL_DATABASE=forum'
- 'MYSQL_PASSWORD=secret'
- 'MYSQL_ROOT_PASSWORD=verysecret'
- 'MYSQL_USER=myuser'
ports:
- '3306:3306'
pom.xml
:
...
<dependencies>
...
<dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-docker-compose -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-docker-compose</artifactId>
<scope>runtime</scope>
<optional>true</optional>
<version>3.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
<version>9.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-testcontainers -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
<version>3.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testcontainers/junit-jupiter -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
<version>1.19.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testcontainers/mysql -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mysql</artifactId>
<scope>test</scope>
<version>1.19.8</version>
</dependency>
</dependencies>
...
application-dev.yml
:
spring:
docker:
compose:
file: docker-compose.dev.yml
...
Dessa forma, toda vez que o Spring for inicializado, ele irá subir um container Docker com o MySQL.