DEV Community

Lucas Oliveira
Lucas Oliveira

Posted on

💡 Spring Boot + Docker Compose: Uma combinação sensacional!

Durante meus estudos, topei com uma biblioteca que, apesar de não ser tão nova, eu ainda não conhecia: spring-boot-docker-compose. Achei sensacional e, para compartilhar essa descoberta (e reforçar o aprendizado, claro), resolvi escrever este artigo.

🚀 Começando com Spring Boot e Docker Compose

Antes de tudo, certifique-se de estar na versão 3.x do Spring Boot e de ter o Docker instalado na máquina.

📦 Dependências necessárias

Para o projeto, criaremos um endpoint REST integrado com um banco PostgreSQL. No pom.xml, inclua as seguintes dependências:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-docker-compose</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Aqui, a estrela do show é a dependência spring-boot-docker-compose, que permite integrar e subir containers do Docker Compose automaticamente!

🛠️ Configurando o Docker Compose
Agora, precisamos definir o banco de dados no arquivo compose.yml:

services:
  db:
    image: postgres:12.22
    ports:
      - "5432:5432"
    environment:
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: ingredientesdb
Enter fullscreen mode Exit fullscreen mode

Caso você queira personalizar o nome do arquivo, basta configurar oo application.yml:

spring:
  docker:
    compose:
      enabled: true
      file: docker-compose.yml
Enter fullscreen mode Exit fullscreen mode

✨ Pronto! Agora, ao rodar a aplicação, o PostgreSQL será iniciado automaticamente. Você pode conferir os logs ou rodar um docker ps para verificar se o container está rodando:

03:00  INFO 25164 --- [ingredientes-service] o.s.boot.docker.compose.core.DockerCli   :  Container ingredientes-db-1  Started
Enter fullscreen mode Exit fullscreen mode
CONTAINER ID   IMAGE            STATUS        PORTS                    NAMES
4b9b463b0daf   postgres:12.22   Up 3 seconds  0.0.0.0:5432->5432/tcp   ingredientes-db-1
Enter fullscreen mode Exit fullscreen mode

🔍 Bônus: Usando @Profile
Podemos usar essa funcionalidade com @Profile, ativando o Compose apenas em determinados ambientes!

O código completo está disponível no meu GitHub:
🔗 https://github.com/LuLiveira

Se curtiu essa dica ou já usou essa biblioteca, comenta aí! 👇🚀

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay