โš™๏ธ Devops/๐Ÿณ Docker

[Docker] Spring boot ํ”„๋กœ์ ํŠธ๋ฅผ ๋„์ปค ์ด๋ฏธ์ง€ํ™” ํ•ด๋ณด๊ธฐ

iseunghan 2022. 7. 5. 15:59
๋ฐ˜์‘ํ˜•

Spring boot ํ”„๋กœ์ ํŠธ๋ฅผ docker image๋กœ ๋งŒ๋“ค์–ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

๊ฐ„๋‹จํ•œ spring boot ํ”„๋กœ์ ํŠธ ์ƒ์„ฑ

HomeController


import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

    @GetMapping("/hello")
    public String hello(@Value("${test.customName}") String name) {
        return "hello, " + name + "!";
    }
}

application.yml

test:
    customName: ${CUSTOM_NAME}
  • "/hello"๋กœ ์š”์ฒญ์ด ๋“ค์–ด์˜ค๋ฉด application.yml์— ๋ฏธ๋ฆฌ ์ •์˜ํ•œ test.customName์„ ํ•จ๊ป˜ ์ถœ๋ ฅํ•˜๋Š” ๋ฉ”์†Œ๋“œ์ž…๋‹ˆ๋‹ค.

jar ํŒŒ์ผ ์ƒ์„ฑํ•˜๊ธฐ

Gradle -> build -> bootJar๋ฅผ ์‹คํ–‰ํ•˜๋ฉด build/libs/**.jar ๊ฐ€ ์ƒ์„ฑ๋ฉ๋‹ˆ๋‹ค.

Dockerfile ์ƒ์„ฑ

docker image๋ฅผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด์„œ๋Š” Dockerfile์ด๋ผ๋Š” ํŒŒ์ผ์— ์–ด๋–ค base ์ด๋ฏธ์ง€๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋งŒ๋“ค์ง€.. ๋“ฑ๋“ฑ์„ ๋ช…์‹œ ํ•ด์ค˜์•ผํ•ฉ๋‹ˆ๋‹ค.

  • ํ”„๋กœ์ ํŠธ ์ตœ ์ƒ๋‹จ ๋””๋ ‰ํ† ๋ฆฌ์— Dockerfile ์ƒ์„ฑ
#!/bin/bash

# base ์ด๋ฏธ์ง€ ์„ค์ •
FROM openjdk:8-jre-alpine

# jar ํŒŒ์ผ ์œ„์น˜๋ฅผ ๋ณ€์ˆ˜๋กœ ์„ค์ •
ARG JAR_FILE=build/*.jar

# ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์„ค์ •
ENV CUSTOM_NAME default

# jar ํŒŒ์ผ์„ ์ปจํ…Œ์ด๋„ˆ ๋‚ด๋ถ€์— ๋ณต์‚ฌ
COPY ${JAR_FILE} test-app.jar

# ์™ธ๋ถ€ ํ˜ธ์ŠคํŠธ 8080 ํฌํŠธ๋กœ ๋…ธ์ถœ
EXPOSE 8080

# ์‹คํ–‰ ๋ช…๋ น์–ด
CMD ["java", "-Dtest.customName=${CUSTOM_NAME}", "-jar", "test-app.jar"]

docker image ์ƒ์„ฑ

์œ„์—์„œ ๋งŒ๋“  Dockerfile์„ ๊ธฐ๋ฐ˜์œผ๋กœ docker image๋ฅผ ์ƒ์„ฑํ•ด๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

  • docker build
$ docker build -t {name}/{image} .

๋งŒ์•ฝ Docker hub์— ์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œ ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด name์„ docker id์™€ ๋™์ผํ•˜๊ฒŒ ์„ค์ •ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

docker scan ์—๋Ÿฌ

๋„์ปค ์ด๋ฏธ์ง€๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋„์ค‘ docker scan์„ ์‹คํ–‰ํ•˜๋ผ๋Š” ๋ฉ”์„ธ์ง€๊ฐ€ ๋–ด์Šต๋‹ˆ๋‹ค.

ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•์„ ์ฐพ์•„๋ณด๋‹ˆ alpine ์ด๋ฏธ์ง€๋ฅผ scanํ•ด์ฃผ๋ฉด ํ•ด๊ฒฐ๋œ๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

  • docker scan
$ docker scan alpine

  • ๋‹ค์‹œ docker build
$ docker build -t {name}/{image} .
  • ์ด๋ฏธ์ง€ ์กฐํšŒ
$ docker images

์ •์ƒ์ ์œผ๋กœ ์ž˜ ์ƒ์„ฑ๋œ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค!

์‹คํ–‰ํ•ด๋ณด๊ธฐ

$ docker run --it -e CUSTOM_NAME=iseunghan --name test-docker -p 8080:8080 {name}/{image}

  • Docker ์‹คํ–‰ ์‹œ ๋„˜๊ฒจ์คฌ๋˜ ํ™˜๊ฒฝ๋ณ€์ˆ˜๊ฐ€ ์ž˜ ์ „๋‹ฌ๋˜์–ด ์ถœ๋ ฅ๋œ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
๋ฐ˜์‘ํ˜•