본문 바로가기

인프라/Docker

k8s 실습을 위한 SpringBoot Dockerfile 작성

2023.08.27 - [인프라/Kubernetes] - Kubernetes 실습 및 서비스 구축

 

k8s 실습을 위해 SpringBoot 프로젝트, dockerfile을 작성 

 

Controller

package com.example.demo;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller {
	@GetMapping("/")
	public ResponseEntity<String> Main() throws Exception {
		try {
			InetAddress inetAddress = InetAddress.getLocalHost();
			String strIpAdress = inetAddress.getHostAddress();
			String html = " 현재 내부 아이피 주소는 <b>" + strIpAdress+"</b> 입니다.";
			return ResponseEntity.status(HttpStatus.OK).body(html);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("아이피 주소를 불러 올 수 없습니다");
		}
			
	}

}

 

build.gradle

plugins {
	id 'java'
	id 'org.springframework.boot' version '3.1.3'
	id 'io.spring.dependency-management' version '1.1.3'
}

//추가
jar {
    enabled = false
}

group = 'com.example'
version = '0.0.1'

java {
	sourceCompatibility = '17'
}

configurations {
	compileOnly {
		extendsFrom annotationProcessor
	}
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	developmentOnly 'org.springframework.boot:spring-boot-devtools'
	annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

// 삭제
// tasks.named('test') {
// 	 useJUnitPlatform()
// }

plains.jar 파일을 생성 안 하기 위해 jar { enabled =false}를 주었고,

test코드를 사용하지 않기 때문에 스프링 프로젝트를 기본으로 있는 tasks.name('test'){ useJUnitPlatform() }을 삭제해 줍니다.

 

Dockfile 완성본

FROM openjdk
RUN microdnf install findutils
RUN mkdir /project
WORKDIR /project
COPY ./ .
RUN ./gradlew build
WORKDIR build/libs
ENTRYPOINT java -jar *.jar

그냥 openjdk를 사용하려 하다가 엄청나게 애를 먹었다. 

RUN microdnf install findutils를 지우고 빌드하게 되면

이런 오류들이 발생하는 것을 볼  수 있다. xargs를 설치해야해서 도커 명령어를 통해 컨테이너를 실행시켜주었다.

docker container run -it openjdk /bin/bash

확인해보니 fedora OS였고 yum 혹은 dnf를 패키지 관리자로 사용한다고 구글링 결과 나왔지만 둘 다 사용할 수 없었고 추가적인 검색을 통해 microdnf의 존재를 알게 되어 해결하게 되었다.

 

실행 결과

docker image build -t sihyun2/learningk8s .

위 명령어를 통해 빌드 후

docker container run -p 8000:8080 -d sihyun2/learningk8s

위 명령어를 통해 실행시켜 주면

잘 나오는 것 을 확인 할 수 있습니다.

 

Kubernetes 관련 파일은 

https://github.com/Sihyun3/LearningKubernetes/tree/main

 

GitHub - Sihyun3/LearningKubernetes

Contribute to Sihyun3/LearningKubernetes development by creating an account on GitHub.

github.com

여기서 확인 가능합니다.