3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

GradleとDockerを活用したSpring BootアプリケーションのMySQL連携

3
Posted at

プロジェクトの準備

まず、Spring Bootプロジェクトを用意します。以下は、基本的なプロジェクト構成の例

/project-root

├── build.gradle
├── settings.gradle
├── Dockerfile
├── docker-compose.yml
└── src
    └── main
        └── java
            └── com
                └── example
                    └── todoapp
                        └── TodoappApplication.java

GradleでJARファイルを作成

build.gradleファイルが設定されていることを確認し、以下のコマンドを使用してプロジェクトをビルドし、JARファイルを生成します。

./gradlew clean build

このコマンドを実行すると、プロジェクトのルートディレクトリにあるbuild/libsフォルダ内に、Spring BootアプリケーションのJARファイルが生成されます。

例: build/libs/todoapp-0.0.1-SNAPSHOT.jar

Dockerfileの作成

プロジェクトのルートディレクトリにDockerfileを作成し、以下の内容を記述します。

# ベースイメージとしてOpenJDKを使用
FROM openjdk:17-jdk-alpine
# 作業ディレクトリを作成
WORKDIR /app
# アプリケーションのJARファイルをコンテナにコピー
COPY build/libs/todoapp-0.0.1-SNAPSHOT.jar /app/app.jar
# アプリケーションを起動
ENTRYPOINT ["java", "-jar", "/app/app.jar"]

このDockerfileは、JARファイルを含むDockerイメージを作成し、コンテナ内でSpring Bootアプリケーションを実行します。

docker-compose.ymlの作成

次に、docker-compose.ymlを作成し、Spring BootアプリケーションとMySQLを連携させる設定を行います。
[] = 各自設定

version: "3.8"

services:
  mysql:
    image: mysql:8.0
    container_name: mysql-container
    environment:
      MYSQL_ROOT_PASSWORD: []
      MYSQL_DATABASE: []
      MYSQL_ROOT_HOST: "%"
    ports:
      - "3307:3306"
    volumes:
      - mysql_data:/var/lib/mysql
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u[]", "-p[]"]
      interval: 10s
      timeout: 5s
      retries: 5

  spring-app:
    build: .
    container_name: spring-app-container
    ports:
      - "8081:8080"
    environment:
      SPRING_DATASOURCE_URL: jdbc:mysql://mysql:3306/logindemo?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
      SPRING_DATASOURCE_USERNAME: []
      SPRING_DATASOURCE_PASSWORD: []
    depends_on:
      mysql:
        condition: service_healthy

volumes:
  mysql_data:

このdocker-compose.ymlは、MySQLコンテナとSpring Bootアプリケーションコンテナを連携させて起動します。

Dockerイメージのビルドとコンテナの起動

プロジェクトのルートディレクトリで以下のコマンドを実行し、Dockerイメージをビルドし、コンテナを起動します。

docker-compose up --build

このコマンドで以下の操作が行われます:

Dockerfileを基に、Spring BootアプリケーションのDockerイメージがビルドされます。
MySQLとSpringアプリケーションのコンテナが起動され、連携します。
Springアプリケーションはポート8081で動作し、MySQLと接続されます。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?