目次
開発環境
- Visual Studio Code:version 1.73.0
- OS:Windows10
- Docker Engine:v23.0.5
DockerでフロントエンドをNext.jsにしてバックエンドをSpring Bootで環境構築をする手順
DockerでフロントエンドをNext.jsにしてバックエンドをSpring Bootで環境構築をする手順について解説していきます。
ディレクトリ構成
今回のディレクトリ構成は下記を目指していきます。
1 2 3 4 5 6 7 8 9 | project-root/ ├── docker/ │ ├── frontend/ # Next.js用Dockerfile │ ├── backend/ # Spring Boot用Dockerfile │ ├── database/ # MySQLコンテナ(Dockerfile) │ └── nginx/ # Nginxコンテナ(Dockerfile + 設定ファイル) ├── frontend/ # Next.jsプロジェクト ├── backend/ # Spring Bootプロジェクト └── docker-compose.yml |
最初に必要なディレクトリを作成しておいてください。
docker-compose.ymlを作成
まずはdocker-compose.ymlを作成していきます。
ルートディレクトリの直下にdocker-compose.ymlを作成し、以下のようにしてください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | version: '3.8' services: frontend: build: context: . dockerfile: docker/frontend/Dockerfile container_name: next_frontend ports: - "3000:3000" volumes: - ./frontend:/var/www/html depends_on: - nginx networks: - app-network backend: build: context: . dockerfile: docker/backend/Dockerfile container_name: spring_backend volumes: - ./backend:/var/www/html ports: - "8080:8080" depends_on: - db networks: - app-network nginx: build: context: . dockerfile: docker/nginx/Dockerfile container_name: nginx_proxy ports: - "80:80" volumes: - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf - ./backend:/var/www/html depends_on: - backend networks: - app-network db: build: context: . dockerfile: docker/database/Dockerfile container_name: mysql_db environment: MYSQL_DATABASE: app_db MYSQL_ROOT_PASSWORD: root MYSQL_USER: user MYSQL_PASSWORD: password ports: - "3306:3306" volumes: - db_data:/var/lib/mysql networks: - app-network volumes: db_data: networks: app-network: driver: bridge |
Javaコンテナを作成
次にJavaコンテナを作成していきます。
docker/backend/
ディレクトリの直下にDockerfileを作成し、以下のようにしてください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # Debian ベースの OpenJDK を使用する FROM openjdk:23-jdk-slim WORKDIR /var/www/html # Mavenのバージョンを指定 ENV MAVEN_VERSION=3.9.6 ENV MAVEN_HOME=/opt/maven ENV PATH="${MAVEN_HOME}/bin:${PATH}" # Mavenをダウンロードしてインストール RUN apt-get update && apt-get install -y curl RUN curl -fsSL https://downloads.apache.org/maven/maven-3/${MAVEN_VERSION}/binaries/apache-maven-${MAVEN_VERSION}-bin.tar.gz \ | tar -xz -C /opt/ \ && ln -s /opt/apache-maven-${MAVEN_VERSION} ${MAVEN_HOME} \ && apt-get clean # javaプロジェクトをコピーする COPY ./backend /var/www/html/ |
Nodeコンテナを作成
次にNodeコンテナを作成していきます。
docker/frontend/
ディレクトリの直下にDockerfileを作成し、以下のようにしてください。
1 2 3 4 5 | FROM node:lts-alpine3.21 WORKDIR /var/www/html COPY ./frontend . |
MySQLコンテナを作成
次にMySQLコンテナを作成していきます。
docker/database/
ディレクトリの直下にDockerfileを作成し、以下のようにしてください。
1 | FROM mysql:8.0 |
Nginxコンテナを作成
次にNginxコンテナを作成していきます。
docker/nginx/
ディレクトリの直下にDockerfileを作成し、以下のようにしてください。
1 2 | FROM nginx:alpine COPY ./docker/nginx/default.conf /etc/nginx/conf.d/default.conf |
docker/nginx/
ディレクトリの直下にdefault.confを作成し、以下のようにしてください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | server { listen 80; server_name localhost; # -------------------------------------------------- # Spring Boot APIへのルーティング(例: http://localhost/api/test) # -------------------------------------------------- location /api/ { proxy_pass http://backend:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # -------------------------------------------------- # Next.js へのプロキシ(例: http://localhost/) # -------------------------------------------------- location / { proxy_pass http://frontend:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } |
Next.jsプロジェクトとSpring Bootプロジェクトの作成
次にNext.jsプロジェクトとSpring Bootプロジェクトの作成をしていきます。
まずは以下のコマンドでプロジェクトディレクトリに移動します。
1 | cd project-root |
以下のコマンドでコンテナをビルドします。
1 | docker-compose build |
以下のコマンドでNext.jsプロジェクトを作成します。
1 | docker-compose run --rm frontend sh -c 'npx create-next-app .' |
以下のコマンドでSpring Bootプロジェクトを作成します。
1 2 3 4 | docker-compose run --rm backend sh -c " curl -X GET 'https://start.spring.io/starter.tgz?dependencies=web,data-jpa,mysql&type=maven-project&language=java&bootVersion=3.4.0&javaVersion=23&groupId=com.example&artifactId=backend&name=backend&packageName=com.example.springboot' \ | tar -xz " |
docker-compose.ymlを修正
次にdocker-compose.ymlを修正していきます。
ルートディレクトリの直下にdocker-compose.ymlを以下のように修正してください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | version: '3.8' services: frontend: build: context: . dockerfile: docker/frontend/Dockerfile container_name: next_frontend ports: - "3000:3000" volumes: - ./frontend:/var/www/html command: npm run dev depends_on: - nginx networks: - app-network backend: build: context: . dockerfile: docker/backend/Dockerfile container_name: spring_backend volumes: - ./backend:/var/www/html command: mvn spring-boot:run ports: - "8080:8080" depends_on: - db networks: - app-network nginx: build: context: . dockerfile: docker/nginx/Dockerfile container_name: nginx_proxy ports: - "80:80" volumes: - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf depends_on: - backend networks: - app-network db: build: context: . dockerfile: docker/database/Dockerfile container_name: mysql_db environment: MYSQL_DATABASE: app_db MYSQL_ROOT_PASSWORD: root MYSQL_USER: user MYSQL_PASSWORD: password ports: - "3306:3306" volumes: - "db_data:/var/lib/mysql" networks: - app-network volumes: db_data: networks: app-network: driver: bridge |
Nodeコンテナを作成
次にNodeコンテナを作成していきます。
docker/frontend/
ディレクトリの直下にDockerfileを作成し、以下のようにしてください。
1 2 3 4 5 6 7 | FROM node:lts-alpine3.21 WORKDIR /var/www/html COPY ./frontend . RUN npm install |
Dockerコンテナを再ビルド
以下のコマンドでDockerコンテナを再ビルドします。
1 | docker-compose build --no-cache |
Spring Bootアプリケーションの環境設定
次にSpring Bootアプリケーションの環境設定をしていきます。
Spring Bootアプリケーションのapplication.properties
設定を以下のように修正します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | spring.application.name=backend # MySQLの設定 spring.datasource.url=jdbc:mysql://db:3306/app_db spring.datasource.username=user spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # JPAの設定 spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true # CORSを一旦全部許可(開発用) spring.mvc.cors.allowed-origins=* spring.mvc.cors.allowed-methods=GET,POST,PUT,DELETE |
動作テスト
動作テストのためにコードを追記していきます。
まずはSpring BootにAPIを追加していきます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package com.example.springboot.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController public class TestController { @Autowired private JdbcTemplate jdbcTemplate; @GetMapping("/api/test") public Map<String, String> getTest() { return Map.of("message", "Hello from Spring Boot!"); } @GetMapping("/api/test-connection") public Map<String, String> testConnection() { try { jdbcTemplate.execute("SELECT 1"); return Map.of("status", "OK"); } catch (Exception e) { return Map.of("status", "NG"); } } } |
次にNext.jsにページを追加していきます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 'use client'; import { useEffect, useState } from 'react'; export default function Home() { const [message, setMessage] = useState(''); const [connectionStatus, setConnectionStatus] = useState(''); useEffect(() => { fetch('/api/test') .then(res => res.json()) .then(data => setMessage(data.message)) .catch(err => { console.error('API Error:', err); setMessage('API接続エラーが発生しました'); }); fetch('/api/test-connection') .then(res => res.json()) .then(data => setConnectionStatus(data.status)) .catch(err => { console.error('API Error:', err); setConnectionStatus('データベース接続エラーが発生しました'); }); }, []); return ( <main> <h1>Next.js + Spring Boot API 接続確認</h1> <p>メッセージ: {message}</p> <p>接続ステータス: {connectionStatus}</p> </main> ); } |
次に以下のコマンドでコンテナを起動します。
1 | docker-compose up |
ブラウザでhttp://localhost/test
にアクセスし、「メッセージ: Hello from Spring Boot!」と「接続ステータス: OK」が表示されていれば成功です。
まとめ
今回はDockerでSpring BootとNext.jsの環境構築をする手順について解説していきましたが、いかがだったでしょうか。
近年、フロントエンドとバックエンドを分けて運用するアプリケーションが増えてきましたが、Dockerを使えば簡単に開発環境を構築することができます。
Dockerを使った開発は必須となりつつありますので、是非、チャレンジしてみてください。