Programming/Springboot

[Springboot] Docker 연동

bisi 2022. 11. 2. 12:46

1. spring project 준비

 

- intellij 기준으로 프로젝트 초기화 

 

 

- 프로젝트 생성 

 

 

 

 

 

 

2. web test를 위한 간단한 코드 작성

 

1) pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-docker-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-docker-demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

 

2) SpringDockerDemoApplication.java

 

Intellij 에서 Spring 프로젝트 생성시, 기본 Application.java 클래스는 자동을 생성해준다.

package com.example.springdockerdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringDockerDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringDockerDemoApplication.class, args);
    }
}

 

 

3) SampleController.java

 

web 테스트를 위해 간단한 Controller 클래스를 생성한다.

 

package com.example.springdockerdemo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleController {

    @RequestMapping("/test")
    public String home() {
        return "Hello Docker World";
    }
}

 

 

 

3. application 정상 실행 확인

 

 

 

> http://localhost:8080/test

 

 

 

4. Docker file 작성

FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]