<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Docker &#8211; WONIZZ.LOG</title>
	<atom:link href="https://blog.wonizz.com/category/tech/docker/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.wonizz.com</link>
	<description>AI 자동화를 직접 굴려 본 개발자의 실무 교훈</description>
	<lastBuildDate>Fri, 04 Dec 2026 08:07:55 +0000</lastBuildDate>
	<language>ko-KR</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0.2</generator>

<image>
	<url>https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2026/08/wz-siteicon-512.png?fit=32%2C32&#038;ssl=1</url>
	<title>Docker &#8211; WONIZZ.LOG</title>
	<link>https://blog.wonizz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">152411368</site>	<item>
		<title>[DevOps] 도커 이미지 용량 정리 3단계</title>
		<link>https://blog.wonizz.com/2026/09/25/docker-image-disk-cleanup/</link>
					<comments>https://blog.wonizz.com/2026/09/25/docker-image-disk-cleanup/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Fri, 25 Sep 2026 02:13:27 +0000</pubDate>
				<category><![CDATA[Docker]]></category>
		<guid isPermaLink="false">https://blog.wonizz.com/?p=3709</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>도커 이미지 용량을 줄이려고 prune 을 돌렸는데 0B 가 나오는 이유를 빈 Docker 재현 실험으로 확인하고, 컨테이너와 이미지와 빌드 캐시와 볼륨을 지우는 순서를 3단계로 정리했습니다.</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2026/09/25/docker-image-disk-cleanup/">[DevOps] 도커 이미지 용량 정리 3단계</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
도커 이미지 용량을 줄이려고 <code>docker image prune</code> 을 돌렸는데 <code>Total reclaimed space: 0B</code> 만 돌아온다면, 기본 <code>image prune</code> 이 이름 없는(dangling) 이미지만 지우기 때문이고 종료된 컨테이너, 이미지, 빌드 캐시, 볼륨 순서로 풀어야 실제로 줄어듭니다.

안녕하세요? 정리하는 개발자 워니즈입니다. 이번 시간에는 비어 있는 Docker 에 흔한 개발 상태를 일부러 만들어두고 정리 명령을 하나씩 돌려서 각 명령이 실제로 무엇을 지우고 무엇을 남기는지 숫자로 재본 결과를 정리해보려고 합니다.

<blockquote>
<strong>한 줄 요약</strong> 도커 이미지 용량은 어떤 prune 명령을 고르느냐보다 어떤 순서로 돌리느냐에 따라 명령 한 번에 되찾는 양이 달라졌습니다. 종료된 컨테이너, 이미지, 빌드 캐시, 볼륨 순서로 풀어야 앞 단계가 붙잡고 있던 몫이 뒤 단계에서 풀려납니다.
</blockquote>

<ul>
  <li><strong>무엇을 쟀나</strong> macOS Docker Desktop(Engine 29.8.0)에서 이미지 5종을 받고 같은 태그로 3회 재빌드하고 컨테이너 4개와 볼륨 2개를 만든 뒤 prune 명령 5개가 각각 회수한 도커 이미지 용량을 쟀습니다</li>
  <li><strong>예상과 달랐던 것</strong> 같은 태그로 세 번 빌드했는데 dangling 이미지가 0개였고 그래서 기본 <code>image prune</code> 은 0B 를 회수했습니다</li>
  <li><strong>그래서 바꾼 순서</strong> 이미지를 먼저 지우자 빌드 캐시 회수 가능량이 36.38MB 에서 98.08MB 로 늘었고, 볼륨은 컨테이너가 남아 있는 동안 <code>-a</code> 를 붙여도 0B 였습니다. 반대 순서로 돌리면 합계는 같고 <code>builder prune</code> 을 두 번 돌려야 했습니다(2026-09-29 재측정)</li>
</ul>

지금 내 PC 의 도커 이미지 용량이 어느 칸에 얼마나 쌓였는지는 아래 명령 한 줄로 먼저 확인할 수 있습니다.

<pre class="wp-block-code"><code>docker system df</code></pre>

이번 재현 환경에서 컨테이너까지 만든 직후 찍은 출력은 이랬는데요, RECLAIMABLE 열이 지금 지워도 되는 몫이라서 이 열부터 보시면 됩니다.

<pre class="wp-block-code"><code class="language-text">TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          6         3         687.1MB   335.3MB (48%)
Containers      4         2         98.3kB    12.29kB (12%)
Local Volumes   2         2         0B        0B
Build Cache     13        0         98.08MB   36.38MB</code></pre>

지금 상황에 맞춰 고르면 이렇습니다.

<ul>
  <li><code>docker image prune</code> 이 0B 를 돌려준다면 이름 있는 안 쓰는 이미지까지 지우는 <code>docker image prune -a</code> 로 넘어갑니다(4장)</li>
  <li>빌드 캐시가 크게 남았다면 이미지를 먼저 지운 뒤 <code>docker builder prune</code> 을 돌립니다(6장)</li>
  <li>볼륨이 <code>-a</code> 를 붙여도 안 지워진다면 그 볼륨을 쓰는 컨테이너가 남아 있는지부터 봅니다(7장)</li>
  <li>CI 러너처럼 작업이 끝나면 머신째 사라진다면 정리 순서를 고민하지 않아도 됩니다(10장)</li>
</ul>

목차

<ol>
  <li>도커 이미지 용량은 어디에 쌓이는가</li>
  <li>재현 실험은 빈 Docker 에서 이렇게 만들었습니다</li>
  <li>1단계 지우기 전에 system df 로 센다</li>
  <li>기본 image prune 은 왜 0B 를 돌려줬을까요?</li>
  <li>2단계 종료된 컨테이너부터 풀고 이미지를 지운다</li>
  <li>3단계 빌드 캐시를 비우고 볼륨은 마지막에 본다</li>
  <li>볼륨은 왜 -a 를 붙여도 하나도 안 지워졌을까요?</li>
  <li>system prune 한 줄로 끝내면 안 되나요?</li>
  <li>이번 재현으로 말할 수 없는 것</li>
  <li>정리와 필자의 결론</li>
</ol>

<h2>1. 도커 이미지 용량은 어디에 쌓이는가</h2>

흔히 도커 이미지 용량이라고 뭉뚱그려 부르지만 Docker 가 디스크를 쓰는 곳은 네 칸으로 나뉘어 있고, <code>docker system df</code> 가 이 네 칸을 Images, Containers, Local Volumes, Build Cache 로 따로 보여줍니다(<a href="https://docs.docker.com/reference/cli/docker/system/df/" target="_blank" rel="noopener">Docker 공식 문서 docker system df</a>).

<figure class="wp-block-table">

<table><thead><tr><th>칸</th><th>무엇이 들어가나</th><th>지우는 명령</th></tr></thead><tbody><tr><td>Images</td><td>pull 로 받거나 직접 빌드한 이미지</td><td>docker image prune</td></tr><tr><td>Containers</td><td>컨테이너마다 이미지 위에 얹힌 쓰기 계층</td><td>docker container prune</td></tr><tr><td>Local Volumes</td><td>볼륨에 쌓인 데이터</td><td>docker volume prune</td></tr><tr><td>Build Cache</td><td>BuildKit 이 빌드 중에 남긴 중간 산물</td><td>docker builder prune</td></tr></tbody></table>

</figure>

이 글의 출발점이 된 실패부터 보여드리면, 빈 Docker 에 이미지 5종을 받고 같은 태그로 세 번 빌드하고 컨테이너 4개를 만든 뒤 기본 정리 명령을 돌린 결과가 아래입니다(2026-09-29 재측정, 9월 25일 첫 측정과 숫자가 한 자리도 다르지 않았습니다).

<pre class="wp-block-code"><code class="language-text">$ docker image prune -f
Total reclaimed space: 0B

$ docker system df
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          6         3         687.1MB   335.3MB (48%)
Containers      4         2         98.3kB    12.29kB (12%)
Local Volumes   2         2         0B        0B
Build Cache     13        0         98.08MB   36.38MB</code></pre>

이미지 칸의 RECLAIMABLE 이 335.3MB 인데 기본 prune 은 0B 였고, 같은 상태에서 <code>docker image prune -a -f</code> 는 <code>Total reclaimed space: 328.7MB</code> 를 돌려줬습니다. SIZE 열은 그 칸이 지금 차지하는 총량이고 RECLAIMABLE 열이 지금 지워도 되는 몫이라, 명령을 고르기 전에 뒤쪽 열과 명령이 지우는 범위를 먼저 맞춰 봐야 합니다. 재현 절차는 2장에 그대로 있고 스크립트 한 번에 1분 남짓 걸렸습니다.
<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2026/09/01-diagram.png?w=1200&#038;ssl=1" alt="도커 이미지 용량이 이미지, 컨테이너, 볼륨, 빌드 캐시 네 칸으로 나뉘고 칸마다 지우는 명령이 다른 것을 보여주는 카드 다이어그램" />

<h2>2. 재현 실험은 빈 Docker 에서 이렇게 만들었습니다</h2>

도커 정리 글에 실린 숫자는 보통 글쓴이 PC 한 대의 상태라서 독자가 자기 환경과 맞춰볼 방법이 없습니다. 그래서 이번에는 네 칸이 전부 0B 인 빈 Docker 에서 출발해 누구나 같은 상태를 다시 만들 수 있는 재현 실험으로 도커 이미지 용량의 변화를 쟀습니다.

<figure class="wp-block-table">

<table><thead><tr><th>항목</th><th>값</th></tr></thead><tbody><tr><td>실행일</td><td>2026-09-25 첫 측정, 2026-09-29 같은 절차로 재측정(숫자 동일)</td></tr><tr><td>Docker Engine(Server)</td><td>29.8.0</td></tr><tr><td>스토리지 드라이버</td><td>overlayfs</td></tr><tr><td>이미지 저장소</td><td>containerd(driver-type io.containerd.snapshotter.v1)</td></tr><tr><td>호스트</td><td>macOS, Docker Desktop</td></tr><tr><td>시작 상태</td><td>이미지, 컨테이너, 볼륨, 빌드 캐시 전부 0B</td></tr></tbody></table>

</figure>

재현은 아래 세 단계로 진행했고 각 단계가 끝날 때마다 <code>docker system df</code> 를 찍어서 네 칸이 어떻게 바뀌는지 남겼습니다.

<ol>
  <li>흔히 쓰는 이미지 5종을 받았습니다. alpine:3.20, nginx:1.27-alpine, node:20-slim, python:3.12-slim, redis:7-alpine 입니다</li>
  <li>python:3.12-slim 위에 requests 를 설치하는 작은 이미지를 <code>demo-app:latest</code> 라는 같은 태그로 세 번 빌드했고, 빌드마다 <code>--build-arg V</code> 값만 1, 2, 3 으로 바꿨습니다</li>
  <li>컨테이너 4개를 만들었습니다. nginx 와 redis 는 실행 상태로 두고 redis 에는 <code>cachedata</code> 라는 이름 붙은 볼륨을 달았고, alpine 은 한 번 실행하고 끝나는 컨테이너를 두 개 만들면서 그중 하나에 <code>-v /scratch</code> 로 익명 볼륨을 붙였습니다</li>
</ol>

빌드에 쓴 Dockerfile 은 아래 다섯 줄이고, Dockerfile 문법이 낯설다면 <a href="https://blog.wonizz.com/2019/07/31/docker-dockerfile/">Dockerfile 의 이해</a> 를 먼저 보시면 읽기 편합니다.

<pre class="wp-block-code"><code class="language-dockerfile">FROM python:3.12-slim
ARG V=1
RUN pip install --no-cache-dir requests==2.31.0 && echo "build $V" > /build.txt
COPY app.py /app/app.py
CMD ["python", "/app/app.py"]</code></pre>

같은 태그로 세 번 빌드하고 dangling 이미지를 세는 부분은 아래와 같은데, <code>ctx</code> 는 위 Dockerfile 과 한 줄짜리 app.py 가 들어 있는 빌드 디렉터리입니다.

<pre class="wp-block-code"><code class="language-bash">for v in 1 2 3; do
  docker build -q -t demo-app:latest --build-arg V=$v ctx
done
docker images -f dangling=true</code></pre>

<h2>3. 1단계 지우기 전에 system df 로 센다</h2>

첫 단계는 아무것도 지우지 않고 도커 이미지 용량이 어느 칸에 얼마나 있는지 세는 것인데요, 컨테이너까지 만든 직후 <code>docker system df</code> 를 돌리자 아래 출력이 나왔습니다(macOS Docker Desktop, Engine 29.8.0, 2026-09-25 실행).

<pre class="wp-block-code"><code class="language-text">TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          6         3         687.1MB   335.3MB (48%)
Containers      4         2         98.3kB    12.29kB (12%)
Local Volumes   2         2         0B        0B
Build Cache     13        0         98.08MB   36.38MB</code></pre>

재현 단계마다 같은 명령을 찍어서 네 칸 중 크게 움직인 이미지와 빌드 캐시만 모아보면 아래 표처럼 됩니다.

<figure class="wp-block-table">

<table><thead><tr><th>시점</th><th>이미지</th><th>이미지 회수 가능</th><th>빌드 캐시</th><th>캐시 회수 가능</th></tr></thead><tbody><tr><td>빈 상태</td><td>0개, 0B</td><td>0B</td><td>0개, 0B</td><td>0B</td></tr><tr><td>이미지 5종 pull</td><td>5개, 669.2MB</td><td>669.2MB</td><td>0개, 0B</td><td>0B</td></tr><tr><td>같은 태그 3회 재빌드</td><td>6개, 687.1MB</td><td>484.4MB</td><td>13개, 98.08MB</td><td>36.38MB</td></tr><tr><td>컨테이너 4개 생성</td><td>6개, 687.1MB</td><td>335.3MB</td><td>13개, 98.08MB</td><td>36.38MB</td></tr></tbody></table>

</figure>

<strong>직접 확인 1.</strong> 실행 중인 컨테이너는 nginx 와 redis 두 개뿐인데 Images 의 ACTIVE 는 3 으로 찍혔고, 남은 하나는 이미 종료된 컨테이너 두 개가 쓰고 있던 alpine 이었습니다. 종료된 컨테이너도 자기가 만들어진 이미지를 사용 중으로 붙잡고 있다는 뜻입니다. 컨테이너를 만든 뒤 이미지 회수 가능량이 484.4MB 에서 335.3MB 로 줄어든 것도 같은 이유로 읽힙니다.

반대로 컨테이너 칸 자체의 회수 가능량은 12.29kB 로 사실상 0 에 가까웠으니, 종료된 컨테이너는 그 자체로는 거의 공간을 차지하지 않으면서 이미지를 붙잡는 방식으로 도커 이미지 용량을 늘리고 있었던 셈입니다.
<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2026/09/02-screenshot.png?w=1200&#038;ssl=1" alt="컨테이너까지 만든 재현 환경에서 docker system df 를 실행한 터미널 출력, RECLAIMABLE 열에 이미지 335.3MB 회수 가능이 찍힌 화면" />

<h2>4. 기본 image prune 은 왜 0B 를 돌려줬을까요?</h2>

이 환경에는 지울 dangling 이미지가 처음부터 하나도 없었기 때문입니다. 공식 문서에 따르면 <code>docker image prune</code> 은 기본으로 dangling 이미지만 지우고 <code>-a</code> 를 붙여야 컨테이너가 참조하지 않는 이미지까지 지우는데, 기본 명령의 대상이 비어 있으니 회수량도 0B 일 수밖에 없었습니다(<a href="https://docs.docker.com/reference/cli/docker/image/prune/" target="_blank" rel="noopener">Docker 공식 문서 docker image prune</a>).

<strong>직접 확인 2.</strong> 같은 태그로 세 번 빌드한 직후 <code>docker images -f dangling=true</code> 는 머리글 한 줄만 찍고 목록이 비어 있었고, 이미지 개수도 받은 5종에 <code>demo-app:latest</code> 하나를 더한 6개라서 앞선 두 번의 빌드 결과는 목록에 별도 이미지로 남지 않았습니다. 이 상태에서 <code>docker image prune -f</code> 를 돌리자 결과는 <code>Total reclaimed space: 0B</code> 였고 네 칸의 숫자도 한 자리도 바뀌지 않았습니다.

같은 태그로 다시 빌드하면 이전 이미지가 태그를 잃고 dangling 으로 남는다는 설명이 흔한데 이번 환경에서는 그 현상이 나타나지 않았습니다. 이 환경은 containerd 이미지 저장소를 쓰고 있었고, dangling 목록의 머리글도 <code>IMAGE ID DISK USAGE CONTENT SIZE EXTRA</code> 로 기존에 익숙한 형식과 달랐습니다(<a href="https://docs.docker.com/desktop/features/containerd/" target="_blank" rel="noopener">Docker Desktop containerd image store 문서</a>).

<blockquote>
기본 <code>image prune</code> 이 0B 를 돌려주는 것은 명령이 고장 난 것이 아니라 지울 dangling 이미지가 없다는 뜻입니다. 돌리기 전에 <code>docker images -f dangling=true</code> 로 대상이 있는지부터 보면 헛걸음을 줄일 수 있습니다.
</blockquote>

다만 이 관찰을 Docker 29 부터 항상 그렇다는 규칙으로 읽으면 곤란한데요, 필자가 확인한 것은 containerd 저장소를 쓰는 이 한 환경이고 기존 방식 저장소를 쓰는 서버에서는 같은 태그 재빌드가 dangling 을 남길 수 있어서 비교 실험 없이는 말할 수 없습니다. 앞선 두 번의 빌드 결과가 어디로 갔는지도 df 숫자만으로는 가를 수 없어서 미확인으로 남겨둡니다.

<h2>5. 2단계 종료된 컨테이너부터 풀고 이미지를 지운다</h2>

이번 재현에서 도커 이미지 용량이 실제로 크게 빠진 명령은 <code>docker image prune -a</code> 였고, 같은 상태에서 이 명령을 돌리자 <code>Total reclaimed space: 328.7MB</code> 가 찍혔습니다.

<figure class="wp-block-table">

<table><thead><tr><th>항목</th><th>정리 전</th><th>image prune -a 후</th></tr></thead><tbody><tr><td>이미지 개수</td><td>6개</td><td>3개</td></tr><tr><td>이미지 SIZE</td><td>687.1MB</td><td>149.2MB</td></tr><tr><td>이미지 회수 가능</td><td>335.3MB</td><td>0B</td></tr><tr><td>빌드 캐시 회수 가능</td><td>36.38MB</td><td>98.08MB</td></tr></tbody></table>

</figure>

<strong>직접 확인 3.</strong> 지워진 이미지는 어떤 컨테이너도 쓰지 않던 node:20-slim, python:3.12-slim, demo-app 세 개였고 남은 세 개는 nginx 와 redis 와 alpine 이었습니다. alpine 은 실행 중인 컨테이너가 하나도 없는데도 종료된 컨테이너 두 개가 붙잡고 있어서 <code>-a</code> 로도 지워지지 않았습니다.

그래서 2단계는 종료된 컨테이너를 먼저 정리하고 이미지를 지우는 순서입니다. 공식 문서 설명대로라면 종료된 컨테이너가 사라진 뒤에는 alpine 도 참조가 끊겨 <code>-a</code> 의 대상이 되지만 이 순서로 한 번 더 돌려서 alpine 이 빠지는지는 이번에 따로 재지 않았습니다.

<pre class="wp-block-code"><code class="language-bash">docker ps -a --filter status=exited
docker container prune -f
docker image prune -a -f
docker system df</code></pre>

<code>docker container prune</code> 은 종료된 컨테이너를 전부 지우므로 다시 켜서 쓸 컨테이너가 섞여 있는지 첫 줄로 먼저 확인하고, <code>-a</code> 로 지운 이미지는 다음에 필요할 때 다시 받아야 하니 받기 어려운 이미지가 섞여 있다면 그것부터 빼두는 편이 안전합니다.

<strong>직접 확인 4.</strong> 숫자 하나가 맞지 않았는데, prune 이 보고한 회수량은 328.7MB 였지만 df 의 이미지 SIZE 는 687.1MB 에서 149.2MB 로 537.9MB 가 줄었습니다. 9월 29일 재측정 때 정리 직전에 <code>docker system df -v</code> 를 찍어 보니 이유가 보였습니다. RECLAIMABLE 335.3MB 는 지워질 세 이미지의 UNIQUE SIZE(demo-app 17.9MB, node:20-slim 315.2MB, python:3.12-slim 2.185MB)를 더한 값이고, demo-app 과 python:3.12-slim 이 같이 쓰던 SHARED SIZE 202.7MB 는 어느 이미지의 회수 가능 몫으로도 잡히지 않았습니다. 두 이미지가 함께 지워지면서 공유 계층도 풀렸으니 df 감소는 335.3MB 에 202.7MB 를 더한 538MB 쪽과 맞습니다. prune 보고값 328.7MB 가 UNIQUE 합계보다 6.6MB 작은 이유는 이번에도 확인하지 못했으니, 정리 계획을 세울 때는 prune 보고값과 df 전후 차이를 둘 다 적어두는 쪽이 나중에 헷갈리지 않습니다.

이미지를 처음부터 작게 만드는 방법은 <a href="https://blog.wonizz.com/2021/10/08/devops-dockerfile-optimization/">Dockerfile 최적화</a> 에서 레이어 캐싱과 베이스 이미지 선택을 다뤘는데, 지우는 것보다 덜 쌓는 쪽이 도커 이미지 용량 관리에서는 오래가는 방법이라고 생각합니다.

<h2>6. 3단계 빌드 캐시를 비우고 볼륨은 마지막에 본다</h2>

마지막 단계는 앞 단계가 풀어준 몫을 지우는 것인데요, 이미지를 정리한 직후 <code>docker builder prune -f</code> 를 돌리자 <code>Total: 98.08MB</code> 가 찍혔고 빌드 캐시 칸은 13개, 98.08MB 에서 0개, 0B 가 됐습니다(<a href="https://docs.docker.com/reference/cli/docker/builder/prune/" target="_blank" rel="noopener">Docker 공식 문서 docker builder prune</a>).

<strong>직접 확인 5.</strong> 이 글에서 순서를 강조하는 이유가 여기 있는데, 이미지를 지우기 전 빌드 캐시의 회수 가능량은 36.38MB 였지만 <code>image prune -a</code> 뒤에는 98.08MB 로 약 2.7배가 됐습니다. 이미지가 남아 있는 동안에는 빌드 캐시 일부가 회수 대상에서 빠져 있었다는 뜻입니다.

<figure class="wp-block-table">

<table><thead><tr><th>시점</th><th>빌드 캐시 전체</th><th>회수 가능</th></tr></thead><tbody><tr><td>이미지 정리 전</td><td>13개, 98.08MB</td><td>36.38MB</td></tr><tr><td>image prune -a 직후</td><td>13개, 98.08MB</td><td>98.08MB</td></tr><tr><td>builder prune 직후</td><td>0개, 0B</td><td>0B</td></tr></tbody></table>

</figure>

<strong>직접 확인 5-1(2026-09-29 반대 순서 실측).</strong> 같은 스크립트에서 순서만 바꿔 빌드 캐시를 먼저 비웠더니 <code>docker builder prune -f</code> 는 <code>Total: 36.38MB</code> 를 돌려줬고, 빌드 캐시 칸에는 6개, 61.7MB 가 회수 불가로 남았습니다. 그다음 <code>docker image prune -a -f</code>(보고값 330.8MB)를 돌리자 남은 61.7MB 가 회수 가능으로 바뀌었고, <code>builder prune</code> 을 한 번 더 돌려야 비워졌습니다.

<figure class="wp-block-table">

<table><thead><tr><th>순서</th><th>1차 builder prune</th><th>image prune -a</th><th>2차 builder prune</th><th>빌드 캐시 합계</th></tr></thead><tbody><tr><td>이미지 먼저(이 글의 순서)</td><td>돌리지 않음</td><td>328.7MB</td><td>98.08MB</td><td>98.08MB</td></tr><tr><td>빌드 캐시 먼저</td><td>36.38MB</td><td>330.8MB</td><td>61.7MB</td><td>98.08MB</td></tr></tbody></table>

</figure>

그래서 9월 25일 판에 적었던 &#8220;순서가 뒤 칸의 회수량까지 바꾼다&#8221;는 문장은 고칩니다. 두 순서의 빌드 캐시 합계는 98.08MB 로 같았고, 순서가 바꾼 것은 명령 한 번에 빠지는 양이었습니다. 빌드 캐시를 먼저 비우면 이미지를 지운 뒤 <code>builder prune</code> 을 한 번 더 돌려야 같은 양이 빠집니다. 이미지가 캐시를 붙잡는 내부 구조는 문서에서 확인하지 못해 미확인으로 둡니다.

공식 문서는 <code>builder prune</code> 이 기본으로 dangling 캐시만 지우고 <code>-a</code> 를 붙이면 사용하지 않는 캐시 전부를 지운다고 설명합니다. 이번 재현에서는 <code>-a</code> 없이 돌렸는데도 이미지를 먼저 지운 뒤라서 98.08MB 전부가 빠졌고, <code>-a</code> 를 붙였을 때 결과가 어떻게 달라지는지는 재지 않았습니다.

빌드 캐시는 도커 이미지 용량을 이루는 칸 가운데 잃는 것이 다음 빌드 시간뿐인 칸이라 주기적으로 돌려도 고민할 거리가 적고, CI 에서 빌드를 자주 태우는 환경이라면 예전에 정리한 <a href="https://blog.wonizz.com/2022/05/25/jenkins-k8s-cicd/">Docker Build Pipeline 구성하기</a> 처럼 빌드가 도는 자리에 이 명령을 같이 두는 방식을 생각해볼 수 있습니다.
<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2026/09/03-chart-2.png?w=1200&#038;ssl=1" alt="이미지 정리 전 36.38MB였던 빌드 캐시 회수 가능량이 image prune -a 이후 98.08MB로 늘어난 것을 보여주는 막대 차트" />

<h2>7. 볼륨은 왜 -a 를 붙여도 하나도 안 지워졌을까요?</h2>

볼륨 두 개가 모두 컨테이너에 참조되고 있었기 때문입니다. 공식 문서는 <code>docker volume prune</code> 이 어떤 컨테이너도 참조하지 않는 볼륨만 지우고 기본으로는 익명 볼륨만 대상으로 삼으며, <code>-a</code> 를 붙이면 이름 붙은 볼륨까지 대상을 넓힌다고 설명합니다(<a href="https://docs.docker.com/reference/cli/docker/volume/prune/" target="_blank" rel="noopener">Docker 공식 문서 docker volume prune</a>).

<strong>직접 확인 6.</strong> 이미지와 빌드 캐시를 정리한 뒤 <code>docker volume prune -f</code> 와 <code>docker volume prune -a -f</code> 를 차례로 돌렸는데 둘 다 <code>Total reclaimed space: 0B</code> 였고, <code>docker volume ls</code> 에는 두 볼륨이 이름 그대로 남아 있었습니다.

<figure class="wp-block-table">

<table><thead><tr><th>볼륨</th><th>종류</th><th>참조하는 컨테이너</th><th>volume prune</th><th>volume prune -a</th></tr></thead><tbody><tr><td>cachedata</td><td>이름 붙음</td><td>redis 컨테이너(실행 중)</td><td>남음</td><td>남음</td></tr><tr><td>61b2e0f02c17 로 시작하는 해시</td><td>익명</td><td>이름 없는 alpine 컨테이너(종료)</td><td>남음</td><td>남음</td></tr></tbody></table>

</figure>

<code>-a</code> 는 대상 범위를 이름 붙은 볼륨까지 넓힐 뿐이고 사용 중인 볼륨을 지우는 옵션이 아닙니다. 익명 볼륨은 컨테이너가 이미 종료됐는데도 그 컨테이너가 남아 있다는 이유만으로 지워지지 않았고 이것이 볼륨 정리를 컨테이너 정리 뒤에 두는 이유입니다.

<strong>직접 확인 7.</strong> 실험을 원상 복구하면서 컨테이너를 전부 지우고 <code>docker system prune -a -f --volumes</code> 를 돌렸더니 볼륨은 2개에서 1개로 줄었습니다. 9월 29일 재측정에서는 이름까지 찍었는데, <code>Deleted Volumes:</code> 아래에는 해시 이름의 익명 볼륨 하나만 나왔고 뒤이은 <code>docker volume ls</code> 에는 이름 붙은 <code>cachedata</code> 가 남아 있었습니다. 공식 문서대로 <code>--volumes</code> 는 익명 볼륨만 지웠고, 이름 붙은 볼륨은 <code>docker volume rm cachedata</code> 로 따로 지워야 했습니다.

볼륨은 네 칸 중 유일하게 지우면 데이터가 사라지는 칸이라서 도커 이미지 용량을 되찾겠다고 한 번에 밀어버리기보다 목록을 눈으로 보고 하나씩 판단하는 편이 낫고, 볼륨의 종류와 마운트 방식은 예전에 정리한 <a href="https://blog.wonizz.com/2019/07/29/docker-volume/">Volume 의 관리</a> 에 더 자세히 있습니다.
<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2026/09/04-screenshot.png?w=1200&#038;ssl=1" alt="docker volume prune 과 volume prune -a 를 실행한 뒤에도 docker volume ls 에 볼륨 두 개가 그대로 남아 있는 터미널 출력" />

<h2>8. system prune 한 줄로 끝내면 안 되나요?</h2>

끝낼 수는 있지만 이번 재현에서 드러난 차이를 보려면 나눠 돌리는 쪽이 맞다고 봅니다. <code>docker system prune</code> 은 종료된 컨테이너와 사용하지 않는 네트워크와 dangling 이미지와 빌드 캐시를 한 번에 지우고 <code>-a</code> 와 <code>--volumes</code> 로 범위를 넓히는 명령입니다(<a href="https://docs.docker.com/engine/manage-resources/pruning/" target="_blank" rel="noopener">Docker 공식 문서 Prune unused Docker objects</a>).

<figure class="wp-block-table">

<table><thead><tr><th>명령</th><th>지우는 대상(공식 문서)</th><th>이번 재현 회수량</th></tr></thead><tbody><tr><td>docker image prune</td><td>dangling 이미지</td><td>0B</td></tr><tr><td>docker image prune -a</td><td>컨테이너가 참조하지 않는 이미지 전부</td><td>328.7MB</td></tr><tr><td>docker builder prune</td><td>빌드 캐시(기본은 dangling)</td><td>98.08MB(이미지 정리 뒤)</td></tr><tr><td>docker volume prune</td><td>참조 없는 익명 볼륨</td><td>0B</td></tr><tr><td>docker volume prune -a</td><td>참조 없는 볼륨 전부</td><td>0B</td></tr><tr><td>docker system prune</td><td>위 대상을 묶어서</td><td>개별 회수량으로는 재지 않음</td></tr></tbody></table>

</figure>

한 줄로 돌리면 도커 이미지 용량이 어느 칸에서 얼마나 빠졌는지가 출력 하나로 뭉쳐서 다음에 같은 상황이 왔을 때 무엇이 원인이었는지 되짚기 어렵습니다. <code>--volumes</code> 를 붙여도 이름 붙은 볼륨은 남는다는 점도 7장에서 본 대로라서, 한 줄이면 다 지워진다는 기대 자체가 맞지 않습니다.

필자는 도커 이미지 용량을 정리할 때 단계마다 <code>docker system df</code> 를 한 번씩 찍어 네 칸의 변화를 남기는 쪽을 택했는데, 명령 하나가 늘어날 뿐이지만 3장의 표 같은 기록이 쌓이면 자기 환경에서 어느 칸이 주로 불어나는지가 보이기 시작합니다.
<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2026/09/05-chart.png?w=1200&#038;ssl=1" alt="image prune, image prune -a, builder prune, volume prune, volume prune -a 다섯 명령이 이번 재현에서 각각 회수한 도커 이미지 용량을 나란히 비교한 막대 차트" />

<h2>9. 이번 재현으로 말할 수 없는 것</h2>

재현 실험은 조건을 통제한 대신 범위가 좁아서, 확인하지 못한 것을 지우지 않고 아래에 그대로 적어둡니다.

<figure class="wp-block-table">

<table><thead><tr><th>항목</th><th>상태</th><th>이유</th></tr></thead><tbody><tr><td>기존 방식 이미지 저장소에서도 dangling 이 0개인가</td><td>미확인</td><td>containerd 저장소 한 환경만 돌렸습니다</td></tr><tr><td>빌드 캐시를 먼저 지우면 회수량이 얼마인가</td><td>확인(2026-09-29)</td><td>1차 36.38MB, 이미지 정리 뒤 2차 61.7MB, 합계는 이 글의 순서와 같은 98.08MB</td></tr><tr><td>종료된 컨테이너를 지운 뒤 alpine 이 -a 로 빠지는가</td><td>미확인</td><td>문서상 동작이고 따로 재지 않았습니다</td></tr><tr><td>prune 보고값 328.7MB 와 df 감소 537.9MB 의 차이</td><td>일부 확인(2026-09-29)</td><td>공유 계층 202.7MB 가 RECLAIMABLE 에 잡히지 않아서입니다. prune 보고값과 UNIQUE 합계의 6.6MB 차이는 미확인</td></tr><tr><td>builder prune 에 -a 를 붙이면 달라지는가</td><td>미확인</td><td>-a 없이만 돌렸습니다</td></tr><tr><td>macOS 쪽 Docker Desktop 가상 디스크 파일이 같이 줄어드는가</td><td>미확인</td><td>호스트 파일 크기를 재지 않았습니다</td></tr></tbody></table>

</figure>

규모도 작았습니다. 이미지 5종에 수백 MB 수준의 실험이라 이미지가 수십 개 쌓인 환경에서 칸별 비율이 같게 나온다고 말할 근거는 없고, 이 글이 도커 이미지 용량 정리에서 말할 수 있는 것은 칸 사이의 관계와 지우는 순서까지입니다.

<h2>10. 정리: 누구에게 맞고 누구에게는 굳이인가, 그리고 필자는 이렇게 봅니다</h2>

이 정리 순서가 잘 맞는 쪽은 Docker Desktop 으로 개발하면서 빌드를 자주 돌리고 한 번 띄우고 끝나는 컨테이너가 쌓이는 환경인데, 종료된 컨테이너가 이미지를 붙잡고 그 이미지가 빌드 캐시를 붙잡는 구조가 이번 재현과 같다면 순서만 바꿔도 명령 한 번에 되찾는 도커 이미지 용량이 달라집니다.

굳이인 쪽도 있어서, 작업이 끝나면 머신째 사라지는 CI 러너라면 정리 순서를 고민할 이유가 적고 기존 방식 저장소를 쓰는 서버라면 이 글의 0B 관찰을 그대로 옮기지 말고 dangling 목록부터 세어보는 것이 먼저일 것 같습니다.

<h3>필자의 결론</h3>

<strong>도커 이미지 용량 정리는 명령을 아는 문제가 아니라 붙잡힌 순서대로 푸는 문제라고 봅니다.</strong> 기본 <code>image prune</code> 의 0B 도, 빌드 캐시의 2.7배도, <code>-a</code> 를 붙여도 남은 볼륨도 전부 앞 칸이 뒤 칸을 붙잡고 있어서 생긴 숫자였습니다.

그래서 필자는 정리 순서를 종료된 컨테이너, 이미지, 빌드 캐시, 볼륨으로 고정하고 단계마다 <code>docker system df</code> 를 찍어 남기기로 했습니다. 9월 29일에 같은 스크립트로 반대 순서를 돌려 보니 빌드 캐시 합계는 같았고 <code>builder prune</code> 을 두 번 돌려야 했으니, 이 순서의 이득은 총량이 아니라 한 번에 끝나는 데 있습니다. 기존 방식 저장소와의 비교는 containerd 가 아닌 환경을 따로 준비해야 해서 아직 하지 않았고, 이번에는 한 환경의 숫자를 있는 그대로 남기는 데서 멈췄습니다.

오늘 해 볼 일 하나만 고르면, 정리 명령을 돌리기 전에 <code>docker system df</code> 를 한 번 찍어 RECLAIMABLE 열이 가장 큰 칸이 어디인지부터 확인해 보세요.

<h2>함께 보면 좋은 글</h2>

<ul>
<li><a href="https://blog.wonizz.com/2021/10/08/devops-dockerfile-optimization/?from=3709">Dockerfile 최적화</a>: 이미지를 처음부터 작게 만드는 빌드 쪽 방법</li>
<li><a href="https://blog.wonizz.com/2019/07/29/docker-volume/?from=3709">Volume 의 관리</a>: 볼륨 종류와 마운트 방식, 지우기 전에 볼 것</li>
<li><a href="https://blog.wonizz.com/2019/07/31/docker-dockerfile/?from=3709">Dockerfile 의 이해</a>: 이번 재현에 쓴 Dockerfile 문법의 기초</li>
<li><a href="https://blog.wonizz.com/2019/02/26/devops-assign/">DevOps 사전 과제</a></li><li><a href="https://blog.wonizz.com/2020/01/22/devops-jenkins-job-automation/">[DevOps] Jenkins Job을 통한 자동화</a></li><li><a href="https://blog.wonizz.com/2021/12/03/devops-nginx-ingress-install-guide/">[DevOps] Nginx ingress 사용해보기</a></li></ul>

도커 디스크가 찼을 때 여러분은 어떤 명령부터 돌리시나요? 정리 순서를 정해 두셨는지, 그때그때 <code>system prune</code> 한 줄로 끝내시는지 댓글로 알려 주세요.

<div class="jetpack_subscription_widget"><h2 class="widgettitle"></h2>
			<div class="wp-block-jetpack-subscriptions__container">
			<form action="#" method="post" accept-charset="utf-8" id="subscribe-blog-1"
				data-blog="152411368"
				data-post_access_level="everybody" >
									<div id="subscribe-text"><p>새 글이 올라오면 메일로 받아 보실 수 있습니다.</p>
</div>
										<p id="subscribe-email">
						<label id="jetpack-subscribe-label"
							class="screen-reader-text"
							for="subscribe-field-1">
							전자 우편 주소						</label>
						<input type="email" name="email" autocomplete="email" required="required"
																					value=""
							id="subscribe-field-1"
							placeholder="전자 우편 주소"
						/>
					</p>

					<p id="subscribe-submit"
											>
						<input type="hidden" name="action" value="subscribe"/>
						<input type="hidden" name="source" value="https://blog.wonizz.com/category/tech/docker/feed/"/>
						<input type="hidden" name="sub-type" value="widget"/>
						<input type="hidden" name="redirect_fragment" value="subscribe-blog-1"/>
						<input type="hidden" id="_wpnonce" name="_wpnonce" value="8e0d64dde7" /><input type="hidden" name="_wp_http_referer" value="/category/tech/docker/feed/" />						<button type="submit"
															class="wp-block-button__link"
																						style="margin: 0; margin-left: 0px;"
														name="jetpack_subscriptions_widget"
						>
							메일로 받기						</button>
					</p>
							</form>
						</div>
			
</div><p>The post <a rel="nofollow" href="https://blog.wonizz.com/2026/09/25/docker-image-disk-cleanup/">[DevOps] 도커 이미지 용량 정리 3단계</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2026/09/25/docker-image-disk-cleanup/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3709</post-id>	</item>
		<item>
		<title>[DevOps] Nginx Rate Limit</title>
		<link>https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/</link>
					<comments>https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Fri, 03 Nov 2023 08:29:21 +0000</pubDate>
				<category><![CDATA[kubernetes]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=2093</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번 시간에는 Nginx를 통해 트래픽을 제어하기 위한 기능은 Rate Limit에 대해서 정리해보도록 하겠습니다. 필자가 Rate Limit 적용을 하면서 겪었던 사례도 함께 정리합니다. Nginx에 관한 시리즈 포스팅은 아래에서 확인이 가능합니다. [DevOps] Nginx 컴파일 설치 [DevOps] ansible nginx config 배포 구성 [DevOps] Nginx Logrotation 설정 [DevOps] Nginx GeoIP 모듈 적용 [DevOps] Nginx Log&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번 시간에는 Nginx를 통해 트래픽을 제어하기 위한 기능은 <code>Rate Limit</code>에 대해서 정리해보도록 하겠습니다. 필자가 Rate Limit 적용을 하면서 겪었던 사례도 함께 정리합니다.</p>
<p>Nginx에 관한 시리즈 포스팅은 아래에서 확인이 가능합니다.</p>
<ul>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/02/09/devops-nginx-compile-installation/">[DevOps] Nginx 컴파일 설치</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/">[DevOps] ansible nginx config 배포 구성</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/08/10/linux-logrotate/">[DevOps] Nginx Logrotation 설정</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/08/17/devops-nginx-geoip-module/">[DevOps] Nginx GeoIP 모듈 적용</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/10/19/devops-nginx-log-aggregation-dashboard/">[DevOps] Nginx Log Aggregation &#038; Dashboard</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/">[DevOps] Nginx Lua module 사용법</a>
  </li>
</ul>
<h2>1. Rate Limit 이란?</h2>
<blockquote><p>
  Incomming connection 혹은 requests 에 대한 rate을 제한하는 기능입니다.
</p></blockquote>
<p>예를들어 너무 많은 connection이 동시에 발생해 server에 부담을 가하는 경우, rate limit을 초과한 connection은 reject할 수 있습니다.</p>
<h3>Rate Limit을 사용하는 이유</h3>
<p>Rate Limit을 사용하는 이유는 다음과 같습니다.</p>
<ul>
<li>DDos공격에 의한 자원 고갈을 방지</li>
<li>서버 과부하 방지
<ul>
<li>Bot에서 오는 트래픽이나 사용자의 잘못된 이용 패턴으로 유발된 트래픽을 걸러내는데 활용</li>
<li>서버가 처리할 수 있는 요청의 임계 값을 넘어선 요청을 방지함으로써 서버의 안정성을 높이는 역할</li>
</ul>
</li>
</ul>
<h3>Rate Limit 알고리즘</h3>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.tk/wp-content/uploads/2023/11/rate_limit_1.png?w=1200" alt="DevOps Nginx Rate Limit 설명 이미지 1" /></p>
<ul>
<li>토큰 버킷은 지정된 용량(버킷 크기)을 갖는 컨테이너로, 사전 설정된 양의 토큰(토큰 공급률)이 주기적으로 채워집니다.
<ul>
<li>각 요청은 처리될 떄 마다 하나의 토큰을 사용합니다.</li>
<li>요청이 들어오면 먼저 충분한 토큰이 있는지 검사한 후, 있는 경우 버킷에서 토큰 하나를 꺼낸 후 요청을 전달합니다.</li>
<li>만약 충분한 토큰이 없는 경우, 해당 요청은 버려집니다.</li>
</ul>
</li>
<li>장점
<ul>
<li>큐의 크기가 제한되어 있어, 메모리 사용 측며네서 효율적</li>
<li>고정된 처리율을 갖고 있어 안정적 출력이 필요한 경우 적합</li>
</ul>
</li>
<li>단점
<ul>
<li>단 시간에 트래픽이 몰려서 요청이 들어오면 쌓이게 되고 제때 처리하지 못하면 최신 요청들은 버려지게 됩니다.</li>
<li>버킷 크기의와 처리율을 튜닝하기 까다롭습니다.</li>
</ul>
</li>
</ul>
<h2>2. Nginx Rate Limit 설정</h2>
<p>Nginxdㅔ서는 Rate Limit을 2가지 방식으로 제공하고 있습니다.</p>
<ul>
<li>limit_req &#8211; 요청 제한
<pre><code class="line-numbers">#동일 아이피 당 Rate을 10r/s로 제한하겠다는 의미
limit_req_zone $binary_remote_addr zone=request_limit_per_ip:10m rate=10r/s;

server {
  location /login/ {
      limit_req zone=request_limit_per_ip burst=10 nodelay;

      proxy_pass http://my_upstream;
  }
}
</code></pre>
</li>
<li>limit_conn &#8211; 커녁션 제한
<pre><code class="line-numbers">#동시에 서버에 연결되는 커넥션 수로 10개로 제한하겠다는 의미
limit_req_zone $server_name zone=request_limit_per_server:10m;

server {
  location /login/ {
      limit_req zone=request_limit_per_server 10;

      proxy_pass http://my_upstream;
  }
}
</code></pre>
</li>
</ul>
<blockquote><p>
  Zone</p>
<ul>
<li>rate limit을 적용할 zone을 정의합니다.
<ul>
<li>$server_name(per serer)</li>
<li>$binary_remote_addr(per user)</li>
<li>$request_uri(per uri)</li>
</ul>
</li>
</ul>
<p>  zone size</p>
<ul>
<li>zone의 이름과 메모리에 저장할 zone의 사이즈 결정
<ul>
<li>zone=MYZONE:10m</li>
</ul>
</li>
</ul>
<p>  limit_req 정의</p>
<ul>
<li>rate=1r/s, rate=60r/m과 같이 frequency를 정의합니다.
<ul>
<li>예를들어 10r/s가 1초당 10개의 요청이 처리된다는 것이 아닙니다. <strong>0.1초에 1개의 요청을 처리할 수 있다는 의미</strong>입니다.</li>
</ul>
</li>
</ul>
</blockquote>
<h3>Burst Mode</h3>
<p>burst를 적용하면, rate limiting을 초과하는 connection을 즉시 reject하지 않고 wait하게 만들 수 있습니다. 일부 rate limit을 넘어 들어온 요청을 queue에 적재하고, rate limit 속도에 맞춰 pop 되어 실행합니다.</p>
<ul>
<li>속도가 제한된 엔드포인트에 10개의 병렬 요청 보내기
<ul>
<li>10개 요청 중 9개가 거부됩니다. 이는 <code>30r/m</code> 즉, 2초마다 새 요청이 허용된다는 의미입니다. 여기서는 10개의 요청이 동시에 도착했고, 그 중 하나는 허용되고 나머지 9개는 nginx에서 거부가 됩니다.</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/cdn-media-1.freecodecamp.org/images/1%2AbqER3OkNtH4MNWZTCjF4Zg.gif?w=1200&#038;ssl=1" alt="DevOps Nginx Rate Limit 설명 이미지 2" /></p>
</li>
<li>Burtmode를 통해 허용치 늘리기
<ul>
<li><code>burst=5</code> 를 통해서 버스트를 처리할 수 있도록 합니다. 기존에는 1/10에서 6/10개가 성공이 되도록 허용치를 늘렸습니다. ( 나머지는 거부 ) 그러나 여기서 주목해야될 것은 나머지 5개가 허용이 되었더라도 <code>30r/m</code> 즉, 2초마다 1개의 요청에 대해서 처리하도록 제한합니다.</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/cdn-media-1.freecodecamp.org/images/1%2AR9D2q4zmUdDQO2k0AvrOWA.gif?w=1200&#038;ssl=1" alt="DevOps Nginx Rate Limit 설명 이미지 3" /></p>
</li>
<li>Nodelay를 통해 burst mode된 나머지 요청도 지연없이 처리 하기
<ul>
<li><code>burst=5</code> 인경우와 처리되는 갯수는 동일합니다. 그러나 이제 처리 속도는 2초당 1개의 요청속도로 엄격하게 제한되지 않습니다.</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/cdn-media-1.freecodecamp.org/images/1%2AwVpU5zy5Yfg6c_lx2VIrAw.gif?w=1200&#038;ssl=1" alt="DevOps Nginx Rate Limit 설명 이미지 4" /></p>
</li>
</ul>
<h2>4. Nginx Rate Limit 사용 사례</h2>
<p>필자가 운여하는 서비스에서 공격성 트래픽이 다수 들어오는 케이스가 있었습니다. 서두에서도 설명했듯이 Rate Limit을 설정하는 이유는 외부의 비이상적 트래픽으로부터 서비스를 보호하고 안정성을 유지하기 위함입니다.</p>
<h3>Requested URI 분석</h3>
<ul>
<li>공격성 트래픽에 의한 Request 패턴을 분석하기로 했습니다.
<ul>
<li>다양하게 호출을 하면서 내부의 취약점을 찾으려는 내용들이 식별됐습니다.</li>
</ul>
<pre><code class="line-numbers">{request_uri="/_next/static/LdA0nq_uXCJOjaYEOuZcS/.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\.\\..\\etc/passwd"}
{request_uri="/_next/static/LdA0nq_uXCJOjaYEOuZcS/./WEB-INF/web.xml?"}

GET /api/v1/games/������������������������������������������������������������etc��passwd
GET /api/v1/games/(nslookup-q=cnamehitufxhlvamalcfebb.bxss.me||curlhitufxhlvamalcfebb.bxss.me))
GET /api/v1/games/../../../../../../../../boot.ini
</code></pre>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.tk/wp-content/uploads/2023/11/rate_limit_2.png?w=1200" alt="DevOps Nginx Rate Limit 설명 이미지 5" /></p>
</li>
<li>
<p>Rate Limit을 설정하기 위한 RPS 확인 (회고를 위한 기록)</p>
<ul>
<li>사실 해당 영역의 분석은 <code>잘못된</code> 내용입니다.</li>
<li>rate limit을 속도의 개념으로 생각해서 rps 분석을 통해서 적절한 값을 찾으려고했습니다. <- 이부분 부터가 잘못된 생각이였습니다.</li>
<li>아래의 그림을 통해서 rate limit 설정치 : 2 <= 제한값 <= 17 의 설정치를 계산했지만, 잘못된 내용이였습니다.</li>
<li>rate limit은 한개의 요청 이후 다음 요청이 들어올 떄까지의 속도이고 예를들어 `30r/m&#8220;은 2초안에 1개의 요청만 허용한다는 개념입니다.</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.tk/wp-content/uploads/2023/11/rate_limit_3.png?w=1200" alt="DevOps Nginx Rate Limit 설명 이미지 6" /></p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.tk/wp-content/uploads/2023/11/rate_limit_4.png?w=1200" alt="DevOps Nginx Rate Limit 설명 이미지 7" /></p>
</li>
</ul>
<h3>다시 처음부터 분석</h3>
<ul>
<li>Rate Limit 산정을 위한 Request 분석
<ul>
<li>한개의 IP에 대해서 요청을 상세히 분석합니다. 하나의 요청으로부터 다음 요청까지의 시간 차이를 계산하여 대략적인 rate limit의 값을 계산했습니다. 여기서는 약 0.2초의 1개의 요청을 허용하도록 산정하여 <code>5r/s</code> 로 산정을 하게 됐습니다.</li>
</ul>
<pre><code class="line-numbers">- 2023-07-21 14:53:32.105 "GET / HTTP/2.0”
- 2023-07-21 14:53:32.361 "GET /robots.txt?1689918812080 HTTP/2.0”
- 2023-07-21 14:53:32.857 "GET /_next/image?url=https%3A%2F% HTTP/2.0"
- 2023-07-21 14:53:33.358 "GET /_next/image?url=https%3A%2F% HTTP/2.0"
- 2023-07-21 14:53:34.109 "GET /api/v1/drops/banners?size=10 HTTP/2.0”
- 2023-07-21 14:53:34.359 "GET /api/v1/games/title HTTP/2.0”
- 2023-07-21 14:53:34.359 "GET /_next/image?url=https%3A%2F% HTTP/2.0"
- 2023-07-21 14:53:34.359 "GET /_next/image?url=https%3A%2F%5 HTTP/2.0"
</code></pre>
</li>
</ul>
<h3>설정 예시</h3>
<ul>
<li>실제로 설정한 예시
<pre><code class="line-numbers">#Back-end의 API에 대한 rate limit
limit_req_zone $whitelist zone=be_access_limit_per_ip:10m rate=10r/s;
...
location ~ ^/(api|pg-api)/ {
  limit_req zone=be_access_limit_per_ip burst=5 nodelay;
  limit_req_status 429;
  # limit_req_dry_run on;


#Front-end에 대한 rate limit
limit_req_zone $whitelist zone=fe_access_limit_per_ip:10m rate=10r/s;
...
location /  {
  limit_req zone=fe_access_limit_per_ip burst=5 nodelay;
  limit_req_status 429;
  # limit_req_dry_run on;

</code></pre>
</li>
</ul>
<h2>5. 마치며&#8230;</h2>
<p>이번 시간에는 nginx의 rate limit 기능을 알아보고, 실제로 적용해던 사례에 대해서 정리를 해보았습니다. 처음에는 단순하게 속도의 개념으로 알았는데 1개의 요청으로부터 다음 요청이 들어오는 사이의 시간을 조정하는것을 알게 됐습니다. 또한 burst mode를 통해서 동시다발적으로 요청이 들어올때도 제어해서 요청을 처리 할 수 있게 됐습니다. Nginx의 기능을 통해서 트래픽을 제어할 수 있게 되어 서비스에 많은 공헌을 하게 된것 같습니다.</p>
<h2>6. 참고</h2>
<p><a class="wp-editor-md-post-content-link" href="https://www.freecodecamp.org/news/nginx-rate-limiting-in-a-nutshell-128fe9e0126c/" target="_blank" rel="noopener">NGINX rate-limiting in a nutshell</a></p>
<p><a class="wp-editor-md-post-content-link" href="https://minholee93.tistory.com/entry/Nginx-Rate-Limiting" target="_blank" rel="noopener">[Nginx] Rate Limiting</a></p>
<p><a class="wp-editor-md-post-content-link" href="https://willseungh0.tistory.com/191" target="_blank" rel="noopener">[Nginx RateLimit] Nginx에 RateLimit 적용해보기</a></p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2093</post-id>	</item>
		<item>
		<title>[DevOps] Hubot 적용기</title>
		<link>https://blog.wonizz.com/2023/05/11/devops-hubot-automation-1/</link>
					<comments>https://blog.wonizz.com/2023/05/11/devops-hubot-automation-1/#comments</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Thu, 11 May 2023 12:53:16 +0000</pubDate>
				<category><![CDATA[kubernetes]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=2037</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 hubot 적용기에 대해서 정리를 해보도록 하겠습니다. 필자는 DevOps업무를 하다보니, 주로 여러개의 개발팀으로부터의 요청들 (CI/CD설정, 네트워크, 인프라, 모니터링 등)에 대해서 처리를 해주는 업무를 합니다. 요청양도 최근들어 꽤나 늘어났고, 요청의 범주도 굉장히 다양하기 때문에 Slack W/F를 통해서 모든것으르 제어하기는 어려운 시점이 왔습니다. JIRA의 티켓을 수동으로 등록하여 관리를 하고있었는데, 이부분을 자동화 시키고 슬랙&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2023/05/11/devops-hubot-automation-1/">[DevOps] Hubot 적용기</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 hubot 적용기에 대해서 정리를 해보도록 하겠습니다. 필자는 <strong>DevOps</strong>업무를 하다보니, 주로 여러개의 개발팀으로부터의 요청들 (CI/CD설정, 네트워크, 인프라, 모니터링 등)에 대해서 처리를 해주는 업무를 합니다.

요청양도 최근들어 꽤나 늘어났고, 요청의 범주도 굉장히 다양하기 때문에 <strong>Slack W/F</strong>를 통해서 모든것으르 제어하기는 어려운 시점이 왔습니다.

<strong>JIRA</strong>의 티켓을 수동으로 등록하여 관리를 하고있었는데, 이부분을 자동화 시키고 슬랙 Thread상에서 일감을 처리하면 자동 종료까지 되는 부분으로 업무의 프로세스를 개선하고 싶었습니다.

<h2>1. hubot 소개</h2>

<ul>
<li>Hubot 은 깃헙의 사내용으로 제작된 챗봇이지만, 많은 발전을 거듭하여 현재 오픈소스로 공개되어있습니다. Node 기반이며, Slack과 친화적입니다.</li>
<li>휴봇의 가장 큰 장점은 간단한 스크립트(CoffeeScript, JavaScript) 작성을 통해 강력한 기능을 추가할 수 있다는 점입니다.</li>
<li>특정 단어 혹은 문장에 따라 <strong>프로세스</strong>를 정의할 수 있습니다. 이미 구축된 스크립트들도 많이 공개 되어있어 손쉽게 스크립트를 추가하여 구현할 수 있습니다.</li>
</ul>

<pre><code class="language-coffeescript line-numbers">enterReplies = ['Hi', 'Target Acquired', 'Firing', 'Hello friend.', 'Gotcha', 'I see you']
leaveReplies = ['Are you still there?', 'Target lost', 'Searching']

module.exports = (robot) ->
  robot.enter (res) ->
    res.send res.random enterReplies
  robot.leave (res) ->
    res.send res.random leaveReplies

[출처] https://blog.hax0r.info/2017-05-14/slack-developer-kit-for-hubot/  [Hax0r blog]
</code></pre>

스크립트를 통해 Local 혹은 Heroku를 통해 배포하여 슬랙과 연동할 수 있습니다.

<ul>
<li><a class="wp-editor-md-post-content-link" href="https://github.com/hubot-scripts/hubot-diagnostics" target="_blank" rel="noopener">hubot-diagnostics</a>: 간단한 기본기능들이 들어있다. 위에서 사용했던 <code>ping</code>을 이 모듈이 응답한 것이다. 그 외 <code>time</code>과 <code>echo</code>도 있다.</li>
<li><a class="wp-editor-md-post-content-link" href="https://github.com/hubot-scripts/hubot-help" target="_blank" rel="noopener">hubot-help</a>: 현재 hubot의 명령어들을 표시해준다. script들의 # Commands 들을 가져와서 뿌려주는 역할을 한다.</li>
<li><a class="wp-editor-md-post-content-link" href="https://github.com/hubot-scripts/hubot-pugme" target="_blank" rel="noopener">hubot-pugme</a>: 설명을 보면은 가장 중요한 휴봇 스크립트라고 적혀있다. 기능은 퍼그 이미지 url을 랜덤으로 가져오는 것이다. 하지만 2년이 지나서 그런지 url이 유효하지 않다.</li>
<li><a class="wp-editor-md-post-content-link" href="https://github.com/hubot-scripts/hubot-rules" target="_blank" rel="noopener">hubot-rules</a>: hubot의 룰을 설명한다. <code>> hubot rules</code>으로 볼 수 있다.</li>
<li><a class="wp-editor-md-post-content-link" href="https://github.com/hubot-scripts/hubot-shipit" target="_blank" rel="noopener">hubot-shipit</a>: 가지고 있는 이미지URL중 랜덤으로 하나를 보내준다. <code>hubot-pugme</code>와 마찬가지로 유효한 URL이 별로 없다.</li>
<li><a class="wp-editor-md-post-content-link" href="https://github.com/hubot-scripts/hubot-heroku-keepalive" target="_blank" rel="noopener">hubot-heroku-keepalive</a>: 무료 heroku를 사용할 경우 하루 사용시간 제한이 있기 때문에 필요한 것 같다.</li>
<li><a class="wp-editor-md-post-content-link" href="https://github.com/hubot-scripts/hubot-redis-brain" target="_blank" rel="noopener">hubot-redis-brain</a>: hubot의 brain기능을 redis로 이용하는 것이다.
<a class="wp-editor-md-post-content-link" href="https://github.com/hubot-scripts/hubot-google-images" target="_blank" rel="noopener">hubot-google-images</a>와 <a class="wp-editor-md-post-content-link" href="https://github.com/hubot-scripts/hubot-google-translate" target="_blank" rel="noopener">hubot-google-translate</a>는 이름에서도 알 수 있듯이 구글의 API키를 받아서 구글 서비스를 사용할 때 필요하다.
<a class="wp-editor-md-post-content-link" href="https://github.com/gkoo/hubot-maps" target="_blank" rel="noopener">hubot-maps</a>도 구글의 맵서비스를 이용하는 것이다.</li>
</ul>

<h2>2. hubot 설치 및 설정</h2>

hubot은 기본적으로 node기반으로 수행되는 어플리케이션입니다. 따라서 npm과 node가 설치되어있어야 설치가 가능합니다.

<ul>
<li>node version : v16.17.0</li>
<li>npm version : 8.15.0</li>
</ul>

<h3>2-1. hubot 설치</h3>

<pre><code class="language-bash line-numbers">$ npm install -g yo generator-hubot
</code></pre>

여기서 <a class="wp-editor-md-post-content-link" href="http://yeoman.io/" target="_blank" rel="noopener">yoman</a> 이라는것을 같이 설치하게 되는데, 간단하게 말하면 구조를 어플리케이션의 구조를 잡아주는 도구라고 보시면 됩니다.

<pre><code class="language-bash line-numbers">$ mkdir -p ~/apps/devops
$ cd ~/apps/devops
$ yo hubot --adapter=slack
</code></pre>

여기서 몇가지 Interactive Question을 받게 되는데, 간단하게 입력을 하면됩니다.

<h3>2-2. hubot 설정</h3>

이제 간단하게 hubot 설치는 마쳤습니다. Hubot 기능중에 데이터 유지를 위해서 Redis module이 자동적으로 들어가있는데 이부분을 제거해야 합니다.

<pre><code class="language-bash line-numbers"># external-script.json
[]
</code></pre>

external-script.json에는 hubot에 필요한 모듈들을 탑재할 수 있는데, 별도의 서버에서 구성을 진행하기 때문에 모든 내용들을 삭제해줘도 무방합니다. 밑의 내용은 필수적으로 삭제를 진행합니다.

<ul>
<li>hubot-heroku-keepalive</li>
<li>hubot-redis-brain</li>
</ul>

<pre><code class="language-bash line-numbers"># ~/apps/devops/node_modules/hubot/src/hubot.js
...
const port = process.env.EXPRESS_PORT || process.env.PORT || 8083
...
</code></pre>

port도 겹치지 않게 custom port로 변경을 해줍니다.

<h3>2-3. Slack 설정</h3>

Hubot 사용의 가장 큰 목적은 Slack을 통해서 <strong>ChatOps</strong>를 구현하기 위함입니다. 따라서 Slack에 앱을 추가하고 연동을 하는 작업이 필요합니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2023/05/hubot_1.png?w=1200&#038;ssl=1" alt="DevOps Hubot 적용기 설명 이미지 1" />

Slack 앱을 추가하면 Hubot 설정 페이지가 나오게 되고, 그곳에서 Hubot의 <strong>Token</strong>값을 얻을 수 있습니다.

<h3>2-4. Hubot 실행</h3>

<pre><code class="language-bash line-numbers">$ HUBOT_SLACK_TOKEN=xoxb-... ./bin/hubot --adapter slack
</code></pre>

hubot을 실행하게 되면, Slack상에 Hubot이 연결이 되면서 연결중으로 접속이 표시가 됩니다. 이렇게 되면 설치 &amp; 설정이 마무리 된것이고, Hubot에 대한 Script를 작성해서 기능을 추가하면 됩니다.

<h2>3. hubot script 가이드</h2>

hubot은 script를 통해서 기능 확장이 가능하고, 현재 open source로 나와있는 여러가지 Script들을 참고 할 수도 있습니다.

<ul>
<li><a class="wp-editor-md-post-content-link" href="https://hubot.github.com/docs/scripting/" target="_blank" rel="noopener">Hubot Script Guide</a>

<ul>
<li>.coffee 혹은 .js 파일로 작성이 가능합니다.</li>
</ul></li>
</ul>

<h3>3-1. send/ reply / emote</h3>

<pre><code class="language-bash line-numbers"># 경로에 script 작성 /apps/devops/scripts
# send : room으로 왔으면 room으로 전달, DM으로 오면 DM으로 전달
# reply : thread에 댓글 형식으로 메시지 전달
# emote : room으로 메시지 전달 
module.exports = (robot) -> 
  robot.hear /badger/i, (res) ->
    res.send "Badgers? BADGERS? WE DON'T NEED NO STINKIN BADGERS"

  robot.respond /open the pod bay doors/i, (res) ->
    res.reply "I'm afraid I can't let you do that."

  robot.hear /I like pie/i, (res) ->
    res.emote "makes a freshly baked pie"


</code></pre>

<h3>3-2. messageRoom</h3>

<pre><code class="language-bash line-numbers"># messageRoom 기능을 이용하여 지정된 방이나 사용자에게 메시지를 보낼 수 있습니다.
module.exports = (robot) ->
  robot.hear /green eggs/i, (res) ->
    room = "mytestroom"
    robot.messageRoom room, "I do not like green eggs and ham.  I do not like them sam-I-am."

  robot.respond /I don't like Sam-I-am/i, (res) ->
    room =  'joemanager'
    robot.messageRoom room, "Someone does not like Dr. Seus"
    res.reply  "That Sam-I-am\nThat Sam-I-am\nI do not like\nthat Sam-I-am"

  robot.hear /Sam-I-am/i, (res) ->
    room =  res.envelope.user.name
    robot.messageRoom room, "That Sam-I-am\nThat Sam-I-am\nI do not like\nthat Sam-I-am"
</code></pre>

<h3>3-3. Capturing</h3>

<pre><code class="language-bash line-numbers"># 정규식에 대해 들어오는 메시지를 처리할 수 있습니다. 
  robot.respond /open the (.*) doors/i, (res) ->
    doorType = res.match[1]
    if doorType is "pod bay"
      res.reply "I'm afraid I can't let you do that."
    else
      res.reply "Opening #{doorType} doors"
</code></pre>

<h3>3-4. HTTP 호출하기</h3>

<pre><code class="language-bash line-numbers"># Hubot은 3rd API들과 연계하기 위해서 HTTP 호출을 할 수 있습니다.
  data = JSON.stringify({
    foo: 'bar'
  })
  robot.http("https://midnight-train")
    .header('Content-Type', 'application/json')
    .post(data) (err, res, body) ->
      # your code here
      if err
        res.send "Encountered an error : ( #{err}"
        return
      # your code here, knowing it was successful   

      if res.statusCode isnt 200
        res.send "Request didn't come back HTTP 200 : ("
        return

      # RateLimit을 이용하여 호출량을 조절
      rateLimitRemaining = parseInt res.getHeader('X-RateLimit-Limit') if res.getHeader('X-RateLimit-Limit')
      if rateLimitRemaining and rateLimitRemaining < 1
        res.send "Rate Limit hit, stop believing for awhile"      

</code></pre>

<h3>3-5.  HTTP 수신기</h3>

<pre><code class="language-bash line-numbers"># Hubot은 HTTP 요청을 처리하기 위한 익스프레스 웹 프레임워크에 대한 지원을 포함합니다. 
# 해당 포트로 정적파일 제공도 가능합니다.

module.exports = (robot) ->
  # the expected value of :room is going to vary by adapter, it might be a numeric id, name, token, or some other value
  robot.router.post '/hubot/chatsecrets/:room', (req, res) ->
    room   = req.params.room
    data   = if req.body.payload? then JSON.parse req.body.payload else req.body
    secret = data.secret

    robot.messageRoom room, "I have a secret: #{secret}"

    res.send 'OK'

# Curl을 이용하여 테스트
// raw json, must specify Content-Type: application/json
curl -X POST -H "Content-Type: application/json" -d '{"secret":"C-TECH Astronomy"}' http://127.0.0.1:8080/hubot/chatsecrets/general

// defaults Content-Type: application/x-www-form-urlencoded, must st payload=...
curl -d 'payload=%7B%22secret%22%3A%22C-TECH+Astronomy%22%7D' http://127.0.0.1:8080/hubot/chatsecrets/general
</code></pre>

<h3>3-6. 기타 기능</h3>

<pre><code class="language-bash line-numbers"># Randomize
lulz = ['lol', 'rofl', 'lmao']

res.send res.random lulz

# Detect Enter & Exit
enterReplies = ['Hi', 'Target Acquired', 'Firing', 'Hello friend.', 'Gotcha', 'I see you']
leaveReplies = ['Are you still there?', 'Target lost', 'Searching']

module.exports = (robot) ->
  robot.enter (res) ->
    res.send res.random enterReplies
  robot.leave (res) ->
    res.send res.random leaveReplies

# Brain 
robot.respond /have a soda/i, (res) ->
  # Get number of sodas had (coerced to a number).
  sodasHad = robot.brain.get('totalSodas') * 1 or 0

  if sodasHad > 4
    res.reply "I'm too fizzy.."

  else
    res.reply 'Sure!'

    robot.brain.set 'totalSodas', sodasHad+1
robot.respond /sleep it off/i, (res) ->
  robot.brain.set 'totalSodas', 0
  msg.reply 'zzzzz'

</code></pre>

<h2>4. hubot 기능 구현</h2>

필자가 최초 생각했던 것처럼, Slack W/F와 연계하여 각 개발팀에서 DevOps를 통한 문의 및 요청들이 접수되면, 해당 내용을 기반으로 Hubot이 JIRA에 Ticket을 생성하고 해당 Ticket을 링크로 응답 합니다.

또한, 작업이 모두 완료된 이후로는 emoji를 설정하였을때, 작업을 종료하도록 구성하고자 합니다.

<h3>4-1. JIRA 자동 등록</h3>

JIRA에 자동 등록을 하기 위해서는 JIRA의 API를 활용해야 합니다.

<a class="wp-editor-md-post-content-link" href="https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/" target="_blank" rel="noopener">Jira Rest API 문서</a>

간단하게 JSON 구조를 만들어서 http request를 한 뒤, 결과를 parsing하여 massage로 다시 return해주는 구조입니다. 그렇게 되면, Slack의 Thread 상에서 티켓의 링크를 확인할 수 있습니다.

<pre><code class="language-coffeescript line-numbers">module.exports = (robot) ->
  robot.respond /create TICKET(.*)/i, (msg) ->

    threadId = getThreadId(msg);
    title = ''
    for line in msg.message.text.split(/\r?\n/)
      console.log (line)
      if line.indexOf("*Summary : *") != -1
        title = line.replace /\*Summary \:\*/, ""
    if title == ''
      msg.send 'Faild to get the subject'
      return
    json =
      fields:
        project:
          key: "LNDO"
        summary: title,
        description: msg.message.text,
        issuetype:
          name: "_Task"
        labels: ["help_devops_thread"]
    json = JSON.stringify(json)    

    create_query = btsBaseUrl + "/rest/api/2/issue"
    auth = btoa("#{user}:#{password}")

    msg.http(create_query)
      .headers(Authorization: "Basic #{auth}", 'Content-Type': 'application/json')
      .post(json) (err, res, body) ->
        issueName = undefined
        if body
          returnJson = JSON.parse(body)
          if returnJson.hasOwnProperty('key')
            issueName = returnJson.key
        if err
          console.log 'Error!'
          console.log err
        if issueName == undefined
          console.log res
          msg.send 'Error on creation issue on BTS'
        else
          link = '<https://jira.test.com/browse/' + issueName + '|' + issueName + '>'
          msg.send 'Create TICKET at ' + link
          threadCache[threadId] = {'lastUpdate': Date.now(), 'fsUpdate': Date.now(), 'BTS': issueName}
          fs.writeFileSync(threadDir + threadId, JSON.stringify(threadCache[threadId]))
</code></pre>

<h3>4-2. JIRA 상태 업데이트</h3>

Slack을 통해서 일감 처리가 완료되면, 이모지(DONE)를 통해서 해당 요청이 종료되었다는 것을 표기하였습니다. 그러다보니 명확하게 티켓과 동기화가 되지 않았었습니다. 이러한 부분을 이모지를 인식해서 티켓의 상태를 업데이트(Resolve)처리를 하도록 구성했습니다.

<pre><code class="language-coffeescript line-numbers">robot.respond /(.*)resolve TICKET(.*)/i, (msg) ->
    threadId = getThreadId(msg);
    getThreadCache(threadId);

    json =
      transition:
        id: "21"
      fields:
        resolution:
          name: "Done"
    json = JSON.stringify(json)

    BTS = threadCache[threadId]['BTS']
    resolve_query = btsBaseUrl + '/rest/api/2/issue/' + BTS + '/transitions?expand=transitions.fields&transitionId=21'
    auth = btoa("#{user}:#{password}")

    msg.http(resolve_query)
      .headers(Authorization: "Basic #{auth}", 'Content-Type': 'application/json')
      .post(json) (err, res, body) ->
        if body
          returnJson = JSON.parse(body)
          console.log(returnJson)
        if err
          console.log err
          msg.send 'There is an error reolsve ticket!'
        else
          link = '<https://jira.test.com/browse/' + BTS + '|' + BTS + '>'
          msg.send 'Cloase BTS  at ' + link
          threadCache[threadId] = {'lastUpdate': Date.now(), 'fsUpdate': Date.now(), 'BTS': BTS}
          fs.writeFileSync(threadDir + threadId, JSON.stringify(threadCache[threadId]))
</code></pre>

<h2>5. hubot 구성도</h2>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2023/05/hubot_2.png?w=1200&#038;ssl=1" alt="DevOps Hubot 적용기 설명 이미지 2" />

전체적인 구성도는 위와 같습니다.

<ul>
<li>Request Layer : Slack W/F를 통해서 요청하는 영역</li>
<li>Slack - Hubot Layer : Slack의 W/F를 분석하여 Hubot 스크립트를 수행하는 영역</li>
<li>InfraStructure Layer : Hubot과 연계되는 Tools가 위치하는 영역</li>
</ul>

이번에 정리된 기준으로는 Jira의 Ticket을 생성하고 종료하는 내용이였습니다. 추후에는 기능을 좀더 강화 할 예정입니다.

<h2>6. 마치며..</h2>

이번시간에는 Slack W/F와 Hubot을 연계하여 업무를 자동화했던 내용을 정리해보았습니다. DevOps업무를 하면서 자동화 처리를 통하여 좀더 효율적으로 일하는 문화를 배울 수 있었고, 특히나 업무 자체를 코드화 시키고, 프로세스화 시키니까 처리하기가 좀더 수월했던 것 같습니다.

다음시간에는 Hubot의 좀더 강화된 기능을 사용하는 내용으로 찾아뵙겠습니다.
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2021/09/01/kubeadm-pod-cidr-change/">[DevOps] kubeadm upgrade를 통한 pod cidr 변경</a></li><li><a href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a></li><li><a href="https://blog.wonizz.com/2023/05/09/devops-k8s-monitoring-with-datadog/">[DevOps] k8s monitoring with Datadog</a></li><li><a href="https://blog.wonizz.com/2023/05/08/devops-istio-virtualhost/">[DevOps] Istio virtualhost 사용법</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2023/05/11/devops-hubot-automation-1/">[DevOps] Hubot 적용기</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2023/05/11/devops-hubot-automation-1/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2037</post-id>	</item>
		<item>
		<title>[DevOps] k8s monitoring with Datadog</title>
		<link>https://blog.wonizz.com/2023/05/09/devops-k8s-monitoring-with-datadog/</link>
					<comments>https://blog.wonizz.com/2023/05/09/devops-k8s-monitoring-with-datadog/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Tue, 09 May 2023 01:51:38 +0000</pubDate>
				<category><![CDATA[kubernetes]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=2034</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈 입니다. 이번시간에는 올해 가장 뿌듯하면서도 성취감 있었던 일중 하나인 datadog모니터링 도입기에 대해서 정리를 하고자 합니다. 현재 진행중인 프로젝트는 Java기반의 Spring Boot로 된 서비스를 개발/운영중입니다. APM(Application Performance Monitoring)을 위해서 기존에는 pinpoint를 사용하고있었지만, 다소 부족한 기능과 전체적인 서비스 가시성을 확보하지 못하여, 상용 솔루션인 Datadog를 도입하기로 하였습니다. 1. Datadog Agent 소개 데이터독을 통해서 그러면&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2023/05/09/devops-k8s-monitoring-with-datadog/">[DevOps] k8s monitoring with Datadog</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈 입니다. 이번시간에는 올해 가장 뿌듯하면서도 성취감 있었던 일중 하나인 <strong>datadog</strong>모니터링 도입기에 대해서 정리를 하고자 합니다.

현재 진행중인 프로젝트는 Java기반의 Spring Boot로 된 서비스를 개발/운영중입니다. <strong>APM(Application Performance Monitoring)</strong>을 위해서 기존에는 pinpoint를 사용하고있었지만, 다소 부족한 기능과 전체적인 서비스 가시성을 확보하지 못하여, 상용 솔루션인 <strong>Datadog</strong>를 도입하기로 하였습니다.

<h2>1. Datadog Agent 소개</h2>

데이터독을 통해서 그러면 어떠한 내용들을 확인 할 수 있을까요? k8s Cluster와 관련된 모든 정보를 확인할 수 있습니다.

<ul>
<li>Cluster Node의 가시성 확보</li>
<li>POD / Container 레벨의 가시성 확보</li>
<li>Kubernetes Event 수집</li>
<li>Application의 Trace 정보 수집</li>
</ul>

그러면 각 Layer 별로 수집을 하기 위해서 어떤 내용이 필요한지 정리해보도록 하겠습니다.
Datadog의 내용들은 공식 Blog에서도 확인할 수 있습니다.

<a class="wp-editor-md-post-content-link" href="https://www.datadoghq.com/blog/" target="_blank" rel="noopener">Datadog Blog</a>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/imgix.datadoghq.com/img/blog/datadog-cluster-agent/kubernetes_diagrams_before_updated.png?w=1200&#038;ssl=1" alt="datadog_1" />

<h3>Kubelet에서 노드 수준 데이터 수집</h3>

Datadog 에이전트는 각 worker node에서 kubelet을 모니터링하여 컨테이너가 어떻게 동작하는지에 대한 모든 메트릭들을 수집합니다.

<h3>API 서버에서 클러스터 수준 데이터 수집</h3>

Datadog 에이전트는 Kubernetes API 서버에 개별적으로 쿼맇아ㅕ 특정 구성 요소의 동작에 대한 데이터를 수집하고 클러스터 전체에 대한 주요 메타데이터를 수집합니다. 이 설정은 클러스터의 규모가 커지면 커질수록 API 서버 및 etcd에 대한 로드를 증가 시켰습니다.

<h3>Datadog 클러스터 에이전트를 통한 분산</h3>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/imgix.datadoghq.com/img/blog/datadog-cluster-agent/kubernetes_diagrams_after_updated.png?w=1200&#038;ssl=1" alt="datadog_2" />

클러스터 에이전트는 API 서버와 노드 기반 에이전트 간의 프록시 역할을 합니다. 이는 API 서버의 직접 부하를 완화할 뿐만 아니라 노드 기반 에이전트가 노드 수준 데이터 수집에 집중할 수 있도록 하는 반면 클러스터 에이전트는 Control Plane에서 클러스터 수준 데이터를 수집합니다.

정리를 하면 다음과 같습니다.

<ul>
<li>datadog-agent : 데이터독 에이전트는 각 노드의 메트릭, 분산 추적 및 로그를 수집하고 서버 리소스(CPU, Memory등) 메트릭을 자동으로 수집</li>
<li>datadog-kube-state-metrics-agent : Kubernetes API를 감시하여 객체의 상태에 대한 메트릭을 수집.</li>
<li>datadog-cluster-agent : node agent에서 Master노드의 API 서버에 직접 쿼리를 하게되면 클러스터 증가시 Master노드의 API서버 및 etcd에 대한 로그가 증가하기 때문에 Master 노드의 서버 부하를 줄이기 위해 API서버와 node agent간의 프록시 역할을 한다.</li>
</ul>

<h2>2. Datadog Agent 설치</h2>

사용자 지정 릴리스 이름으로 차트를 설치하려면 <code>RELEASE_NAME</code>(예: <code>datadog-agent</code>):

<ol>
<li><a class="wp-editor-md-post-content-link" href="https://v3.helm.sh/docs/intro/install/" target="_blank" rel="noopener">Helm</a> 를 설치합니다 .</li>
<li>Datadog Helm 저장소를 추가합니다.<code>helm repo add datadog https://helm.datadoghq.com</code></li>
<li>새로 추가된 차트의 최신 버전 가져오기: <code>helm repo update</code>.</li>
<li>빈 values.yaml 파일을 만들고 원하는 경우 <a class="wp-editor-md-post-content-link" href="https://github.com/DataDog/helm-charts/blob/main/charts/datadog/values.yaml" target="_blank" rel="noopener">기본값</a> 을 재정의합니다 . <a class="wp-editor-md-post-content-link" href="https://github.com/DataDog/helm-charts/tree/main/examples/datadog" target="_blank" rel="noopener">여기</a> 에서 몇 가지 예를 찾을 수 있습니다 .</li>
<li>Datadog 에이전트를 배포합니다.</li>
</ol>

<pre><code class="language-bash line-numbers">helm install RELEASE_NAME -f datadog-values.yaml --set datadog.site='datadoghq.com' --set datadog.apiKey= datadog/datadog 
</code></pre>

<pre><code class="language-yaml line-numbers">targetSystem: "linux"
datadog:
  apiKey: 'sample'
  appKey: 'sample'
  clusterName: 'test-k8s'
  tags: []
  kubelet:
    tlsVerify: "false"
  logs:
    enabled: false
    containerCollectAll: false
    containerCollectUsingFiles: false
  apm:
    portEnabled: true
    socketPath: /var/run/datadog/apm.socket
    hostSocketPath: /var/run/datadog/
  processAgent:
    enabled: false
    processCollection: false
  systemProbe:
    enableTCPQueueLength: false
    enableOOMKill: false
    collectDNSStats: false
</code></pre>

<h3>설치 현황</h3>

<pre><code class="language-bash line-numbers">datadog-agent-2dvkn                                3/3     Running   0          95d
datadog-agent-2jkdh                                3/3     Running   0          95d
datadog-agent-5q595                                3/3     Running   0          95d
datadog-agent-6gnnd                                3/3     Running   0          95d
datadog-agent-6pxn7                                3/3     Running   0          39d
datadog-agent-7kwpl                                3/3     Running   0          95d
datadog-agent-875rt                                3/3     Running   0          95d
datadog-agent-8sbjr                                3/3     Running   0          95d
datadog-agent-9c6d6                                3/3     Running   0          39d
datadog-agent-cluster-agent-84bd789556-cff7d       1/1     Running   0          95d
datadog-agent-kube-state-metrics-fb456b9bf-hqn2p   1/1     Running   0          95d
....
</code></pre>

위와 같이 dd-agent들은 각 노드별로, cluster-agent, kube-state-metric은 하나의 특정 node에 설치가 됩니다.

<h2>3. Helm Chart 수정(APM 설정)</h2>

상위 설정까지 마치게 되면, 아래의 정보까지는 자동으로 수집이 되게 됩니다.

<ul>
<li>Cluster Node의 가시성 확보</li>
<li>POD / Container 레벨의 가시성 확보</li>
<li>Kubernetes Event 수집</li>
</ul>

그럼 이제 APM에 대한 설정을 정리해보겠습니다.

<ul>
<li>Application의 Trace 정보 수집</li>
</ul>

APM을 설정하기 위해서는 Application이 기동할 때, 사용되어야 할 내용들이 있습니다.

<pre><code class="language-yaml line-numbers">apiVersion: apps/v1
kind: Deployment
metadata:
....
## volume을 정의 합니다. 
## 1) dd-apm-agent mount를 위한 container volume 
## 2) apmsocket을 위한 hostpath volume
    spec:
      {{- if (ne .Values.phase "test") }}
      volumes:
      - name: datadog-apm-agent
        emptyDir: {}
      - hostPath:
          path: /var/run/datadog/
        name: apmsocketpath
      {{- end }}    
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: networkType
                operator: DoesNotExist
      containers:
      - name: {{ .Values.phase }}-{{ .Values.projectName }}
        image: {{ .Values.dockerImgName }}:{{ .Values.deployImgVersion }}
                ## volume을 mount 합니다. 
                ## 1) dd-apm-agent mount를 위한 container volume 
                ## 2) apmsocket을 위한 hostpath volume        
        {{- if (ne .Values.phase "test") }}
        volumeMounts:
        - name: datadog-apm-agent
          mountPath: /datadog/apm/agent
        - name: apmsocketpath
          mountPath: /var/run/datadog
        {{- end }}        
       .....      
                ## apm에 대한 셋팅을 합니다.
                ## 1) DD_ENV, DD_SERVICE, DD_VERSION 은 배포된 환경, 서비스 및 버전에 대한 정보 
                ## 2) DD_TRACE_ENABLED는 APM TRACE 사용 유무
        {{- if (ne .Values.phase "alpha") }}
        - name: DD_SERVICE
          valueFrom:
            fieldRef:
              fieldPath: metadata.labels['app']
        - name: DD_VERSION
          valueFrom:
            fieldRef:
              fieldPath: metadata.labels['version']
        - name: DD_ENV
          value: {{ .Values.phase }}
        - name: DD_TAGS
          value : {{ .Values.namespace }}
        - name: DD_TRACE_ENABLED
          value: "true"
        - name: DD_TRACE_SAMPLE_RATE
          value: "1"
        - name: DD_PROFILING_ENABLED
          value: "true"
        - name: DD_JMXFETCH_ENABLED
          value: "true"
                ## 어플리케이션 기동시 APM jar 파일을 삽입합니다. 
        command: ["/bin/sh"]
        args: ["-c", "/sbin/tini java -javaagent:/datadog/apm/agent/dd-java-agent.jar $JAVA_OPTS -jar  api-gateway.jar"]
        {{- end }}                  
      ......
      {{- if (ne .Values.phase "alpha") }}
            ## initcontainer를 이용하여 초기 dd-agent-jar파일을 다운받아 container volue을 mount 합니다.
      initContainers:
      - name: datadog-apm-agent
        image: busybox
        command:
        - wget
        - -O
        - /datadog/apm/agent/dd-java-agent.jar
        - https://dtdg.co/latest-java-tracer
        volumeMounts:
        - name: datadog-apm-agent
          mountPath: /datadog/apm/agent
      {{- end }}      

</code></pre>

위의 과정을 통해서 APM TRACE가 가능해지고, 삽입된 jar파일에서 수집된 정보들은 모두 dd-agent에게 <strong>socket</strong>을 통하여 전달하게 되고, 모든 내용은 SaaS형태의 Datadog 수집 서버로 전송을 하게 됩니다.

<h2>4. Dashboard 작성</h2>

필자는 Dashboard를 보고 한 눈에 어플리케이션들의 상황을 알 수 있게끔 구성을 하고 싶었습니다. 그래서 가장 중점적으로 보는 지표를 정해보기로 했습니다.

<ul>
<li>Kubernetes 현황</li>
<li>Kubernetes Contaeinr CPU, Memory</li>
<li>Kubernetes Events</li>
<li>Application Error(50*)</li>
<li>Application Latency(3s 이상)</li>
<li>Application Request Volume</li>
</ul>

위의 현황으로도 얼추 어느정도의 어플리케이션 상황들은 볼 수 있다라고 생각이 되었습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2023/05/datadog_1.png?w=1200&#038;ssl=1" alt="DevOps k8s monitoring with Datadog 설명 이미지 1" />

붉은색 박스로 표기해놓은 순서대로 위에서 지정한 지표들을 볼 수 있도록 구성했습니다. 실제로 배포시 혹은 특정 이벤트시에 해당 지표들을 매우 잘 활용하고 있으며, 서비스를 안정적으로 운영하는데 많은 기여를 하고 있다고 생각합ㄴ니다.

<h2>5. 마치며..</h2>

Datadog중에서 Cluster, Pod, Container 레벨까지는 Prometheus, Grafana로 충분히 모니터링이 가능합니다. 하지만, Datadog을 도입한 가장큰 이유중 하나는 APM 기능을 이용하기 위함이였습니다.

무수히 많은 어플리케이션들이 MSA 형태로 배포되어있고 호출을 통해서 서로가 서로에게 연결이 되어있습니다. 이상황에서 연결상에 문제라던지 장애를 맞이하면 어디부분에서 문제가 발생을 했는지 찾기가 굉장히 힘듭니다.

그러한 부분에 있어서 APM 도입을 통해 가장 크게 해소 할 수 있던 것 같고, 특히 성능 개선부분에 있어서도 여러가지 시야를 얻을 수 있었습니다.

<h2>6. 참조</h2>

https://dev.to/airoasis/kubernetes-datadog-spring-boot-3g34

<h2>7. 2026년 기준: Helm Chart 기본값이 바뀐 부분</h2>

<p>이 글의 예시 values.yaml 은 <code>datadog.logs.containerCollectUsingFiles: false</code> 로 되어 있는데요, 지금 Datadog 공식 Helm 차트(datadog/datadog, 2026-10-16 기준 버전 3.257.1)에서는 이 값의 기본값이 <code>true</code> 로 바뀌어 있습니다. 파일 기반 수집이 컨테이너 런타임 API 를 거치는 방식보다 효율적이라는 것이 차트 쪽 설명입니다.</p>

<p>그래서 지금 새로 설치한다면 이 항목을 따로 끌 이유가 없으면 건드리지 않아도 되고, 예전에 이 글을 보고 <code>false</code> 로 명시해둔 values.yaml 이 있다면 그 줄을 지워도 기본값이 더 나은 쪽으로 바뀝니다. (출처: <a href="https://github.com/DataDog/helm-charts/blob/main/charts/datadog/values.yaml" target="_blank" rel="noopener">DataDog/helm-charts 공식 values.yaml</a>)</p>

<p><em>최종 갱신 2026-10-16</em></p>

<p>AI 도구로 초안을 만들고 직접 실행·검증한 내용입니다.</p>

<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2022/05/18/devops-k8s-hpa/">[DevOps] k8s Horizontal POD autoscaling</a></li><li><a href="https://blog.wonizz.com/2021/12/20/devops-k8s-log-aggregation/">[DevOps] k8s Log 수집 시스템 구성</a></li><li><a href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a></li><li><a href="https://blog.wonizz.com/2023/05/11/devops-hubot-automation-1/">[DevOps] Hubot 적용기</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2023/05/09/devops-k8s-monitoring-with-datadog/">[DevOps] k8s monitoring with Datadog</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2023/05/09/devops-k8s-monitoring-with-datadog/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2034</post-id>	</item>
		<item>
		<title>[DevOps] Istio virtualhost 사용법</title>
		<link>https://blog.wonizz.com/2023/05/08/devops-istio-virtualhost/</link>
					<comments>https://blog.wonizz.com/2023/05/08/devops-istio-virtualhost/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 08 May 2023 08:00:31 +0000</pubDate>
				<category><![CDATA[kubernetes]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=2028</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 Istio virtualhost를 통한 트래픽 관리에 대해서 정리를 해보려고 합니다. 필자가 속한 프로젝트에서는 Istio를 grpc 분산용으로 사용하고 있습니다. 그러나 따로 트래픽 관리라던지, 인증가 인가에 대한 내용을 적용하고 있지는 않습니다. Istio의 L7 Envoy proxy를 사용은 하고있으나, 적절하게 기능들을 활용하고 있지는 않기에 이번 포스팅을 통해서 어떠한 내용들을 다룰 수 있는지를 기록하고자 합니다. istio관련된&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2023/05/08/devops-istio-virtualhost/">[DevOps] Istio virtualhost 사용법</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 Istio virtualhost를 통한 트래픽 관리에 대해서 정리를 해보려고 합니다. 필자가 속한 프로젝트에서는 Istio를 grpc 분산용으로 사용하고 있습니다. 그러나 따로 트래픽 관리라던지, 인증가 인가에 대한 내용을 적용하고 있지는 않습니다.</p>
<p>Istio의 L7 Envoy proxy를 사용은 하고있으나, 적절하게 기능들을 활용하고 있지는 않기에 이번 포스팅을 통해서 어떠한 내용들을 다룰 수 있는지를 기록하고자 합니다.</p>
<p>istio관련된 시리즈는 아래에서 확인이 가능합니다.</p>
<ul>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/06/28/devops-istio-1/">istio 1편 : Istio란 무엇인가요?</a></li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/03/06/devops-istio-traffic-tracing-kiali/">istio 2편 : Istio Traffic Tracing : Kiali</a></li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/05/08/devops-istio-virtualhost/">istio 3편 : Istio virtualhost 사용법</a></li>
</ul>
<h2>1. Bookinfo Sample app</h2>
<p>istio는 친절하게도 설치를 하게 되면 샘플 앱을 제공하고 있습니다. 이부분이 서비스 메시를 이해하는데 많은 도움이 되었습니다.</p>
<p>먼저 설치는 다음의 포스팅을 확인해주시기 바랍니다.</p>
<p>설치를 하고 다음의 경로를 이동을 하게 되면, example이 존재합니다.</p>
<pre><code class="language-bash line-numbers"># bookinfo sample 예제
/istio-1.10.0/samples/bookinfo

# bookinfo application 설치
$kubectl apply -f /platform/kube/book/bookinfo.yaml
</code></pre>
<p>해당 파일을 설치하게 되면, 다음과 같이 여러개의 어플리케이션이 설치가 됩니다.</p>
<pre><code class="language-bash line-numbers">service/details created
serviceaccount/bookinfo-details created
deployment.apps/details-v1 created

service/ratings created
serviceaccount/bookinfo-ratings created
deployment.apps/ratings-v1 created

service/reviews created
serviceaccount/bookinfo-reviews created
deployment.apps/reviews-v1 created
deployment.apps/reviews-v2 created
deployment.apps/reviews-v3 created

service/productpage created
serviceaccount/bookinfo-productpage created
deployment.apps/productpage-v1 created
</code></pre>
<p>productpage, details, reviews, ratings로 구성이 되어있고, 전체적인 아키텍처는 다음과 같습니다 .</p>
<p><img decoding="async" src="https://istio.io/latest/docs/examples/bookinfo/withistio.svg" alt="bookinfo_1" /></p>
<p>사전에 클러스터에 Istio-1.10.0 버전을 설치하였고, default namespace에 injection 까지 마친상태였습니다. 이후에 각 서비스와 함께 Envoy 사이트카를 주입하여 Istio 환경에서 서비스를 구성하고 실행하기만 하면됩니다.</p>
<p>예제에서는 Ingress를 사용하게끔 되어있지만, 별도의 Ingress Layer를 사용하지 않고, Product Page자체를 Node port로 외부로 노출시켰습니다.</p>
<pre><code class="language-bash line-numbers"># product page 외부로 노출 시키기

kubectl patch svc productpage -p '{"spec": {"type": "NodePort"}}'
service/productpage patched

# service port 
$ kubectl get svc
NAME          TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
details       ClusterIP   192.168.59.179   <none>        9080/TCP         94s
kubernetes    ClusterIP   192.168.0.1      <none>        443/TCP          22h
productpage   NodePort    192.168.32.89    <none>        9080:32383/TCP   94s
ratings       ClusterIP   192.168.50.87    <none>        9080/TCP         94s
reviews       ClusterIP   192.168.56.81    <none>        9080/TCP         94s
</code></pre>
<p>최종적으로 {host ip} : 32383/productpage 로 접속을 하면 다음과 같은 화면이 노출됩니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/miro.medium.com/max/4800/1%2AJ5ydMnlPQN2N5sRfkQZeHQ.png?w=1200&#038;ssl=1" alt="bookinfo_2" /></p>
<h2>2. Destination rule과 Virtual host</h2>
<h3>1) Destinatino Rule</h3>
<p><code>DestinationRule</code>라우팅이 발생한 후 서비스를 위한 트래픽에 적용되는 정책을 정의합니다. 이러한 규칙은 로드 밸런싱에 대한 구성, 사이드카의 연결 풀 크기, 로드 밸런싱 풀에서 비정상 호스트를 감지하고 제거하기 위한 이상값 감지 설정을 지정합니다.</p>
<p>자세한 설정은 다음의 공식 Document에서 볼 수 있습니다.</p>
<p><a class="wp-editor-md-post-content-link" href="https://istio.io/latest/docs/reference/config/networking/destination-rule/" target="_blank" rel="noopener">Destination Rule</a></p>
<p>bookinfo 예제에서 다음의 경로 파일을 열어봅니다.</p>
<pre><code class="language-bash line-numbers"># destionation rule all 
$ vi bookinfo/networking/destination-rule-all.yaml
</code></pre>
<p>내용이 길지만, 하나의 부분에 대해서 말씀을 드리겠습니다.</p>
<pre><code class="language-yaml line-numbers">#  destination-rule-all.yaml
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: reviews
spec:
  host: reviews
  subsets:
  - name: v1
    labels:
      version: v1
  - name: v2
    labels:
      version: v2
  - name: v3
    labels:
      version: v3
</code></pre>
<p><code>host: reviews</code> 는 서비스의 이름을 말합니다.</p>
<p><code>subsets</code> 는 서비스의 개별 버전을 나타내는 하나 이상의 명명된 집합입니다. 트래픽 정책은 하위 집합 수준에서 재정의할 수 있습니다.</p>
<p>위에서는 각 labeling의 version기준으로  v1, v2, v3로 나누었습니다. 처음 아키텍처 그림에서 reviews가 3개의 버전을 서비스가 되는 것을 볼 수 있었습니다.</p>
<pre><code class="language-yaml line-numbers"># destination-rule-reviews.yaml
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: reviews
spec:
  host: reviews
  trafficPolicy:
    loadBalancer:
      simple: RANDOM
  subsets:
  - name: v1
    labels:
      version: v1
  - name: v2
    labels:
      version: v2
  - name: v3
    labels:
      version: v3
</code></pre>
<p><code>trafficPolicy</code> : loadBalancer, connectionPool, outlierDetection, tls을 통해 특정 목적지와 특정 포트에 적용할 수 있는 트래픽 정책입니다.</p>
<p>위의 예에서는 random traffic으로 로드밸런싱을 하도록 구성을 했습니다.</p>
<h3>2) Virtual Service</h3>
<p>위의 정해진 Destination Rule을 기준으로 가상 서비스를 만들 수 있습니다. 트래픽을 어떤식으로 라우팅을 할지 설정이 가능합니다.</p>
<pre><code class="language-yaml line-numbers"># virtual-service-all-v1.yaml
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: productpage
spec:
  hosts:
  - productpage
  http:
  - route:
    - destination:
        host: productpage
        subset: v1
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews
spec:
  hosts:
  - reviews
  http:
  - route:
    - destination:
        host: reviews
        subset: v1
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: ratings
spec:
  hosts:
  - ratings
  http:
  - route:
    - destination:
        host: ratings
        subset: v1
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: details
spec:
  hosts:
  - details
  http:
  - route:
    - destination:
        host: details
        subset: v1
</code></pre>
<p>위의 예제에서는 모든 서비스를 v1으로 보내겠다는 설정을 적용하였습니다.</p>
<p><code>host</code> 트래픽이 보내질 목적지 host(Service name) 입니다.</p>
<p><code>http > route > destination</code> Destination Rule에서 정의한 곳으로 트래픽을 보내기 위해 설정을 합니다.</p>
<p>아래 2개의 파일을 배포하게 되면, ratings 서비스가 v1으로만 트래픽이 전달이 되므로, 별점 정보는 노출이 되지 않는(v1) 으로 서비스를 하게 됩니다.</p>
<p>destination-rule-all.yaml<br />
virtual-service-all-v1.yaml</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2023/05/istio_bookinfo_1.png?w=1200&#038;ssl=1" alt="DevOps Istio virtualhost 사용법 설명 이미지 1" /></p>
<h2>3. Intellegent Routing</h2>
<p>위의 예제와 더불어 Routing에 대해서 bookinfo 예제 파일로 설명을 드리겠습니다.</p>
<h3>특정 User에게 특정 버전만 서비스 하기</h3>
<pre><code class="language-yaml line-numbers"># virtual-service-reviews-test-v2.yaml
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews
spec:
  hosts:
    - reviews
  http:
  - match:
    - headers:
        end-user:
          exact: jason
    route:
    - destination:
        host: reviews
        subset: v2
  - route:
    - destination:
        host: reviews
        subset: v1
</code></pre>
<p>headers에 jason이라고 있으면, reviews를 v2로 서비스 하고 그외에는 v1으로 서비스를 합니다.</p>
<h3>점진적 마이그레이션</h3>
<p>다음 구성에서 보시듯이, reviews의 8:2 비율로 v1과 v2로 라우팅을 시키는 내용입니다.</p>
<pre><code class="language-yaml line-numbers"># virtual-service-reviews-80-20.yaml
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: reviews
spec:
  hosts:
    - reviews
  http:
  - route:
    - destination:
        host: reviews
        subset: v1
      weight: 80
    - destination:
        host: reviews
        subset: v2
      weight: 20
</code></pre>
<h2>4.  Fault Injection</h2>
<p>어플리케이션의 복원력에 대해서 확인하기 위해서 오류를 강제로 삽입할 수 있는 기능입니다.</p>
<p>다음 예제는 jason으로 로그인시 rating 서비스가 100%의 확률로 7초의 딜레이를 강제적으로 발생시키는 내용입니다.</p>
<pre><code class="language-yaml line-numbers"># virtual-service-ratings-test-delay.yaml
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: ratings
spec:
  hosts:
  - ratings
  http:
  - match:
    - headers:
        end-user:
          exact: jason
    fault:
      delay:
        percentage:
          value: 100.0
        fixedDelay: 7s
    route:
    - destination:
        host: ratings
        subset: v1
  - route:
    - destination:
        host: ratings
        subset: v1
</code></pre>
<p>다음은 jason으로 로그인시 100%의 확률로 500에러를 발생하는 내용입니다.</p>
<pre><code class="language-yaml line-numbers"># virtual-service-ratings-test-abort.yaml
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: ratings
spec:
  hosts:
  - ratings
  http:
  - match:
    - headers:
        end-user:
          exact: jason
    fault:
      abort:
        percentage:
          value: 100.0
        httpStatus: 500
    route:
    - destination:
        host: ratings
        subset: v1
  - route:
    - destination:
        host: ratings
        subset: v1  
</code></pre>
<h2>5. Circuit Breaker</h2>
<p>Circuit Breaker는 탄력적인 마이크로 서비스 애플리케이션을 만드는 데 중요한 패턴입니다. Circuit breaking을 사용하면 장애의 영향, 지연 시간 급증 및 기타 네트워크 특성의 바람직하지 않은 영향을 제한하는 애플리케이션을 작성 할 수 있습니다.</p>
<ul>
<li>서비스 A -> B -> C의 구조에서 C가 장애가 발생을 하게 되면, B는 대기를 하게 되고 덩달아 A도 대기상태에 빠져 서비스 불능상태에 빠지게 됩니다. 하나의 장애가 다른 서비스들도 적체를 유발하여 장애가 전파됩니다.</li>
<li>Circuit Breaker는 기능 자체가 동작하지 않는 경우에 Breaking을 통해 해당 서비스로 트래픽이 가지 않도록 차단을 하여 장애가 전파되지 않도록 하는데 목적이 있습니다.</li>
</ul>
<h2>6. 마치며..</h2>
<p>이번시간에는 istio의 virtual host를 통해서 트래픽제어를 정리해봤습니다. istio를 잘만 활용하면, 수많은 MSA구조의 어플리케이션들 사이에서 적절하게 트래픽을 분배하고 라우팅을 할 수 있습니다. 이를 통해서 장애도 제어를 할 수 있을것 같다는 생각이 들었습니다.<br />
다음시간에는 istio의 실제 적용 사례를 정리해보도록 하겠습니다.</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2023/05/08/devops-istio-virtualhost/">[DevOps] Istio virtualhost 사용법</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2023/05/08/devops-istio-virtualhost/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2028</post-id>	</item>
		<item>
		<title>[DevOps] Istio Traffic Tracing : Kiali</title>
		<link>https://blog.wonizz.com/2023/03/06/devops-istio-traffic-tracing-kiali/</link>
					<comments>https://blog.wonizz.com/2023/03/06/devops-istio-traffic-tracing-kiali/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 06 Mar 2023 12:01:12 +0000</pubDate>
				<category><![CDATA[kubernetes]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=2021</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 Kiali라는 툴에 대해서 정리를 해보려고 합니다. DevOps 엔지니어로서 가장 중점을 두는 부분은 모니터링영역입니다. (물론 개인적인 생각입니다.) 모니터링을 잘 구성해두고 철저히 관찰하고 이상유무를 체크하게 된다면, 사이트의 신뢰도 자연스럽게 유지가 될 것입니다. 필자가 운영하는 프로젝트에서는 80-90 여개의 MSA 구조 어플리케이션들이 얽히고 섥혀서 연결이 되어있습니다. 마치 사슬 구조처럼 연결이 외어있는데 Istio는 이러한 서비스&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2023/03/06/devops-istio-traffic-tracing-kiali/">[DevOps] Istio Traffic Tracing : Kiali</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 <strong>Kiali</strong>라는 툴에 대해서 정리를 해보려고 합니다. DevOps 엔지니어로서 가장 중점을 두는 부분은 모니터링영역입니다. (물론 개인적인 생각입니다.) 모니터링을 잘 구성해두고 철저히 관찰하고 이상유무를 체크하게 된다면, 사이트의 신뢰도 자연스럽게 유지가 될 것입니다.</p>
<p>필자가 운영하는 프로젝트에서는 80-90 여개의 MSA 구조 어플리케이션들이 얽히고 섥혀서 연결이 되어있습니다. 마치 사슬 구조처럼 연결이 외어있는데 <strong>Istio</strong>는 이러한 서비스 메시 구조에서 네트웤영역을 담당해주는 오픈소스 입니다.</p>
<p>istio관련된 시리즈는 아래에서 확인이 가능합니다.</p>
<ul>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/06/28/devops-istio-1/">istio 1편 : Istio란 무엇인가요?</a></li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/03/06/devops-istio-traffic-tracing-kiali/">istio 2편 : Istio Traffic Tracing : Kiali</a></li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/05/08/devops-istio-virtualhost/">istio 3편 : Istio virtualhost 사용법</a></li>
</ul>
<p>Istio는 어플리케이션 pod에 side-car 형태로 붙어서 모든 네트워크의 입/출을 통제하고 관리하고 모니터링합니다. 여기서 수집된 정보들을 기반으로 Tracing을 해줄 수 있는것이 오늘 소개드리고자 하는 <strong>Kiali</strong>입니다.</p>
<h2>1. Kiali 설치 과정</h2>
<p>Kiali를 설치하기 이전에 Traffic정보를 수집할 수 있는 Prometheus가 필요합니다. 또한, Traffic Trace를 위해서는 Jaeger가 필요합니다.</p>
<h3>Istio Addon을 통해서 설치</h3>
<pre><code class="language-bash line-numbers">#istio를 다운로드 후, 설치
kubectl apply -f ${ISTIO_HOME}/samples/addons/kiali.yaml
</code></pre>
<h3>Helm을 통해서 설치</h3>
<pre><code class="language-bash line-numbers">helm install \
  --namespace istio-system \
  --set auth.strategy="anonymous" \
  --repo https://kiali.org/helm-charts \
  kiali-server \
  kiali-server
</code></pre>
<h3>Nodeport로 서비스 변경</h3>
<pre><code class="language-yaml line-numbers">spec:
  ports:
    - name: http
      nodePort: 32763
      port: 20001
      protocol: TCP
      targetPort: 20001
    - name: http-metrics
      nodePort: 32762
      port: 9090
      protocol: TCP
      targetPort: 9090
  selector:
    app.kubernetes.io/instance: kiali-server
    app.kubernetes.io/name: kiali
  sessionAffinity: None
  type: NodePort
</code></pre>
<p>필자는 위의 내용을 간단하게 helm chart로 커스텀 구성을 완료 했습니다.</p>
<pre><code class="language-bash line-numbers">.
├── Chart.yaml
├── values.yaml
└── templates
    ├── crds
    │   └── crds.yaml
    └── templates
        ├── configmap.yaml
        ├── dashboards
        │   ├── envoy.yaml
        │   ├── go.yaml
        │   ├── kiali.yaml
        │   ├── micrometer-1.1-jvm.yaml
        │   ├── micrometer-jvm-pool.yaml
        │   ├── micrometer-jvm.yaml
        │   ├── microprofile-1.1.yaml
        │   ├── microprofile-x.y.yaml
        │   ├── nodejs.yaml
        │   ├── quarkus.yaml
        │   ├── springboot-jvm-pool.yaml
        │   ├── springboot-jvm.yaml
        │   ├── springboot-tomcat.yaml
        │   ├── thorntail.yaml
        │   ├── tomcat.yaml
        │   ├── vertx-client.yaml
        │   ├── vertx-eventbus.yaml
        │   ├── vertx-jvm.yaml
        │   ├── vertx-pool.yaml
        │   └── vertx-server.yaml
        ├── deployment.yaml
        ├── rolebinding-controlplane.yaml
        ├── rolebinding.yaml
        ├── role-controlplane.yaml
        ├── role-viewer.yaml
        ├── role.yaml
        ├── serviceaccount.yaml
        └── service.yaml
</code></pre>
<h3>1) 기본 구성 파일</h3>
<ul>
<li>configmap.yaml : kiali의 설정 파일</li>
<li>deployment.yaml : kiali의 배포 파일</li>
<li>service.yaml : kiali 서비스 구성 파일</li>
</ul>
<h3>2) 권한 제어</h3>
<ul>
<li>Rolebinding-controlplane.yaml :</li>
<li>rolebinding.yaml</li>
<li>role-controlplane.yaml</li>
<li>role.yaml</li>
<li>role-viewer.yaml</li>
<li>serviceaccount.yaml : k8s 클러스터내에 모든 영역에 대해서 조회가 가능한 계정</li>
</ul>
<h3>3) 대시보드 파일</h3>
<ul>
<li>대시보드에 대한 내용들을 yaml 파일로 관리합니다.</li>
<li>기본적으로 제공되는 대시보드들에 대해서 helmchart로 구성</li>
</ul>
<h2>2. Kiali 기본</h2>
<h3>인증 전략</h3>
<p>Kiali의 인증전략은 여러가지가 존재합니다. 아래에서 참고 가능하지만, 아쉽게도 ID/PW를 적용하기 위해서는 오픈아이디커넥트(ex. Keycloak)를 적용해야 가능합니다. 따라서 필자는 <strong>token</strong>방식으로 설정을 해두었고, 토큰값으로 접근제어가 되도록 설정을 하였습니다.</p>
<p><a class="wp-editor-md-post-content-link" href="https://kiali.io/docs/configuration/authentication/" target="_blank" rel="noopener">인증 전략</a></p>
<pre><code class="language-yaml line-numbers">spec:
  auth:
    strategy: token
</code></pre>
<p>설정을 하게 되면 최초 로그인시에 Token을 요구하게 됩니다. 이 token의 상단의 serviceaccount에서 생성된 secret 값으로 그대로 복사하여 사용을 하면 됩니다.</p>
<h3>기본 네임스페이스 선택</h3>
<p>기본적으로 Kiali에 처음 액세스할 떄 대부분의 Kiali 페이지에서 사용자는 네임스페이스 드롭다운을 사용하여 데이터를 보려는 NS를 선택해야 합니다. 이러한 부분을 미리 정의된 네임스페이스 선택을 구성할 수 있습니다.</p>
<pre><code class="language-yaml line-numbers">spec:
  kiali_feature_flags:
    ui_defaults:
      namespaces:
      - istio-system
</code></pre>
<h3>프로메테우스 구성</h3>
<p>Kiali에서는 Prometheus가 토폴로지 그래프를 생성하고, 메트릭을 표시하고, 상태를 계산하고, 기타 기능들을 수행하기 위해 필요합니다.</p>
<p>기본적으로 Kiali는 Prometheus가 istio 추가 기능을 <strong>http://prometheus.<istio_namespace_name>:9090</strong>을 사용하고 있습니다. 만약 Prometheus가 다른 서비스 이름이 있거나 다른 네임스페이스에 있다면 아래와 같이 설정을 변경해야 합니다.</p>
<pre><code class="language-yaml line-numbers">spec:
  external_services:
    prometheus:
      # Prometheus service name is "metrics" and is in the "telemetry" namespace
      url: "http://metrics.telemetry:9090/"
</code></pre>
<h3>예거 구성</h3>
<p>Kiali는 여러 기능에 대해 분산 추적 데이터를 사용하여 향상된 경험을 제공하기 떄문에 Jaeger는 적극 권장 되는 서비스 입니다.</p>
<p>기본적으로 Kiali는 Jaeger Istio 추가 기능을 <strong>http://tracing.<istio_namespace_name>:16685/jaeger</strong>를 사용합니다. 만약 다른 서비스 이름이 있거나 다른 네임스페이스에 설치된 경우 다음 예와 같이 변경을 해야 합니다.</p>
<pre><code class="language-yaml line-numbers">spec:
  external_services:
    tracing:
      # Enabled by default. Kiali will anyway fallback to disabled if
      # Jaeger is unreachable.
      enabled: true
      # Jaeger service name is "tracing" and is in the "telemetry" namespace.
      # Make sure the URL you provide corresponds to the non-GRPC enabled endpoint
      # if you set "use_grpc" to false.
      in_cluster_url: 'http://tracing.telemetry:16685/jaeger'
      use_grpc: true
      # Public facing URL of Jaeger
      url: 'http://my-jaeger-host/jaeger'
</code></pre>
<h3>Traffic Health</h3>
<p><a class="wp-editor-md-post-content-link" href="https://kiali.io/docs/configuration/health/" target="_blank" rel="noopener">Health</a></p>
<p>아래 예시처럼, 예를들어 에러 율이 0.1% 이상이면 <strong>Degraded</strong>상태를 10%이상이면 <strong>Failure</strong>상태를 표기합니다.</p>
<pre><code class="language-yaml line-numbers"># ...
  health_config:
    rate:
      - namespace: ".*"
        kind: ".*"
        name: ".*"
        tolerance:
          - code: "^5\\d\\d$"
            direction: ".*"
            protocol: "http"
            degraded: 0
            failure: 10
          - code: "^4\\d\\d$"
            direction: ".*"
            protocol: "http"
            degraded: 10
            failure: 20
          - code: "^[1-9]$|^1[0-6]$"
            direction: ".*"
            protocol: "grpc"
            degraded: 0
            failure: 10
# ...
</code></pre>
<table>
<thead>
<tr>
<th>Priority</th>
<th>Rule (value=% matching requests)</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>value >= FAILURE threshold</td>
<td><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/health-configuration/failure.png?w=1200&#038;ssl=1" alt="img" />FAILURE</td>
</tr>
<tr>
<td>2</td>
<td>value >= DEGRADED threshold AND value < FAILURE threshold</td>
<td><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/health-configuration/degraded.png?w=1200&#038;ssl=1" alt="img" />DEGRADED</td>
</tr>
<tr>
<td>3</td>
<td>value > 0 AND value < DEGRADED threshold</td>
<td><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/health-configuration/healthy.png?w=1200&#038;ssl=1" alt="img" />HEALTHY</td>
</tr>
<tr>
<td>4</td>
<td>value = 0</td>
<td><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/health-configuration/healthy.png?w=1200&#038;ssl=1" alt="img" />HEALTHY</td>
</tr>
<tr>
<td>5</td>
<td>No traffic</td>
<td><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/health-configuration/no_health.png?w=1200&#038;ssl=1" alt="img" />No Health Information</td>
</tr>
</tbody>
</table>
<h2>3. Kiali 기능 정리</h2>
<h3>서비스 작업</h3>
<h4>Traffic management : 라우팅 요청</h4>
<ul>
<li>모든 규칙은 요청에 대해서 일치하는 경우와 라우팅 대상으로 구성이 됩니다.</li>
<li>요청 일치 부분은 Header, Uri, Scheme, Method를 사용하여 여러 필터를 추가 할 수 있습니다.</li>
<li>요청 일치 부분은 비어있을 수 있습니다. 이 경우 모든 HTTP 요청이 규칙에 적용됩니다.</li>
<li>라우팅 대상은 라우팅 되는 트래픽의 비율을 지정할 수 있습니다.</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/features/actions-service-request-routing.png?w=1200&#038;ssl=1" alt="DevOps Istio Traffic Tracing : Kiali 설명 이미지 1" /></p>
<h4>Traffic management : 오류 주입</h4>
<p>고의적으로 결함을 주입하여, 서비스의 탄력성을 테스트할 수 있습니다.</p>
<ul>
<li>HTTP 지연 사양은 요청 전달 경로에 대기 시간을 주입한은데 사용됩니다.</li>
<li>HTTP 중단 사양은 요청을 즉시 중단하고 미리 지정된 상태 코드를 반환하는 데 사용합니다.</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/features/actions-service-fault-injection.png?w=1200&#038;ssl=1" alt="DevOps Istio Traffic Tracing : Kiali 설명 이미지 2" /></p>
<h4>Traffic management : 트래픽 이동</h4>
<p>추후 canary 배포 혹은 blue/green 이용시 활용할 수 있는 부분으로 트래픽을 설정을 통해서 Weight를 줄 수 있습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/features/actions-service-traffic-shifting.png?w=1200&#038;ssl=1" alt="DevOps Istio Traffic Tracing : Kiali 설명 이미지 3" /></p>
<h4>Traffic management : 요청 시간 초과</h4>
<p>Istio를 사용하여 Timeout 설정을 지정할 수 있습니다.</p>
<ul>
<li>HTTP 시간 초과는 요청에 대한 시간 초과를 정의합니다.</li>
<li>HTTP 재시도는 HTTP 요청이 실패할 때 사용할 재시도 정책을 설명합니다.</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/features/actions-service-request-timeout.png?w=1200&#038;ssl=1" alt="DevOps Istio Traffic Tracing : Kiali 설명 이미지 4" /></p>
<h2> </h2>
<h4>Traffic management : 회로 차단기</h4>
<ul>
<li>연결 풀은 업스트림 호스트에 대한 연결 제한을 정의합니다.</li>
<li>이상값 감지는 보고된 연속 오류를 기반으로 회로 차단기를 구현합니다.</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/features/actions-service-advanced-circuit-breaker.png?w=1200&#038;ssl=1" alt="DevOps Istio Traffic Tracing : Kiali 설명 이미지 5" /></p>
<h2>4. Tracing 이란</h2>
<p>Kiali는 Jaeger for Distributed Tracing과의 기본 통합을 제공합니다. 따라서 사용자는 Jaeger의 추적 시각화에 액세스 할 수 있습니다.</p>
<h3>워크로드 세부 정보</h3>
<p>워크로드를 조사할 때 추적 탭을 클릭하여 차트에서 추적을 시각화 합니다. 추적을 선택하면 Kiali는 추적 세부 정보에 대한 탭과 범위 세부 정보데 대한 탭을 제공합니다. Kiali는 히트맵 접근 방식을 사용하여 사용자가 문제 추적 또는 범위를 식별하는데 도움을 줍니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/features/trace-detail.png?w=1200&#038;ssl=1" alt="DevOps Istio Traffic Tracing : Kiali 설명 이미지 6" /></p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/features/trace-span-detail.png?w=1200&#038;ssl=1" alt="DevOps Istio Traffic Tracing : Kiali 설명 이미지 7" /></p>
<h3>히트맵</h3>
<p>워크로드의 추적 탭에 표시되는 히트맵은 특정 추적의 요청 시간을 시간에 따라 집계된 기간 메트릭과 비교하는 메트릭입니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/features/tracing-heatmap.png?w=1200&#038;ssl=1" alt="DevOps Istio Traffic Tracing : Kiali 설명 이미지 8" /></p>
<p>위의 히트맵의 오른쪽 상단 셀은 추적이 나타내는 요청 기간(5.96ms)이 지난 10분 이내에 워크로드에 대한 모든 인바운드 요청의 99번째 백분위수보다 17.5ms 더 빨랐음을 보여줍니다.</p>
<p>셀의 색상 범위는 빨간색과 녹색 사이입니다. 셀이 더 녹색이면 추적 기간이 집계 메트릭 데이터와 비교하여 더 빠릅니다. 빨간색 셀은 연결된 추적이 집계 메트릭 데이터에 비해 훨씬 느리므로 해당 추적을 검사하면 잠재적인 병목 현상이나 문제를 감지하는 데 도움이 될 수 있음을 나타냅니다.</p>
<h3>메트릭 상관 관계</h3>
<p>Kiali는 메트릭 차트에서 스팬 오버레이를 제공합니다. 사용자는 오버레이 생성 옵션을 활성화하여 <strong>spans</strong> 을 클릭한 뒤, 추적에 초첨을 맞춘 추적 탭으로 자동으로 이동 됩니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/features/trace-metric-overlay.png?w=1200&#038;ssl=1" alt="DevOps Istio Traffic Tracing : Kiali 설명 이미지 9" /></p>
<h3>그래프 상관 관계</h3>
<p>그래프에서 노드를 선택하면 측면에 패널이 나타납니다. 트레이스를 선택하면 그래프는 트레이스 범위에 대한 오버레이를 표시합니다. 그리고 측면 패널은 스팬 세부 정ㅈ보를 표시하고 추적 세부 정보 보기에 대한 링크를 제공합니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/features/trace-graph-overlay.png?w=1200&#038;ssl=1" alt="DevOps Istio Traffic Tracing : Kiali 설명 이미지 10" /></p>
<h3>로그 상관 관계</h3>
<p>Kiali는 로그 및 추적 정보에 대한 통합 보기를 제공할 수 있어 사용자가 관심 있는 추적을 식별하기 위해 로그를 사용할 수 있습니다. 옵션을 활성화하면 <code>spans</code>Kiali는 워크로드 로그 보기에 추적 항목을 추가합니다. 아래에서 시간 정렬된 순서로 사용자에게 애플리케이션 로그(흰색), Envoy 프록시 로그(금색) 및 추적 공간(파란색)의 통합 보기가 표시됩니다. 관심 범위를 클릭하면 관심 추적에 대한 세부 정보 보기로 이동합니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/kiali.io/images/documentation/features/trace-logs.png?w=1200&#038;ssl=1" alt="DevOps Istio Traffic Tracing : Kiali 설명 이미지 11" /></p>
<h2>5. 마치며..</h2>
<p>kiali를 통해서 네트워크 트래픽에 대한 흐름을 한 눈에 확인 할 수 있었습니다. istio의 기능을 이용하여 트래픽 제어를 손쉽게 할 수 있을뿐 더러, MSA 구조의 복잡한 구조에서 트래픽이 어디서 어디로 흘러가는 지 바로 확인 할 수 있는 점이 너무 좋았습니다.</p>
<p>다음시간에는 istio의 기능들에 대해서 하나씩 정리를 해보도록 하겠습니다.</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2023/03/06/devops-istio-traffic-tracing-kiali/">[DevOps] Istio Traffic Tracing : Kiali</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2023/03/06/devops-istio-traffic-tracing-kiali/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2021</post-id>	</item>
		<item>
		<title>[DevOps] K8S Resource 최적화 사례</title>
		<link>https://blog.wonizz.com/2022/09/19/devops-k8s-resource-optimization/</link>
					<comments>https://blog.wonizz.com/2022/09/19/devops-k8s-resource-optimization/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 19 Sep 2022 03:22:25 +0000</pubDate>
				<category><![CDATA[kubernetes]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=1963</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 k8s의 리소스 최적화 사례에 대해서 정리를 해보려고 하빈다. 필자가 근무하는 프로젝트에서는 k8s를 직접 구축하여 사용하고 있습니다. 그런데, Worker Node에서 CPU Request가 초과했다는 메트릭을 식별했고, 배포간에는 pod가 pending이 되는 현상까지 식별했습니다. 무엇인가 문제가 생긴것임에는 틀림이 없어, 확인하여 조치하기로 했습니다. 1. k8s에서의 Request와 Limit이란? 필자가 운영하는 k8s에서는 수십개의 pod들이 MSA의 형태로 운영되고&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/09/19/devops-k8s-resource-optimization/">[DevOps] K8S Resource 최적화 사례</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 k8s의 리소스 최적화 사례에 대해서 정리를 해보려고 하빈다. 필자가 근무하는 프로젝트에서는 k8s를 직접 구축하여 사용하고 있습니다.

그런데, Worker Node에서 CPU Request가 초과했다는 메트릭을 식별했고, 배포간에는 pod가 <strong>pending</strong>이 되는 현상까지 식별했습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/bobcares.com/wp-content/uploads/2022/07/podstates.png?w=1200&#038;ssl=1" alt="pod pending" />

무엇인가 문제가 생긴것임에는 틀림이 없어, 확인하여 조치하기로 했습니다.

<h2>1. k8s에서의 Request와 Limit이란?</h2>

필자가 운영하는 k8s에서는 수십개의 pod들이 MSA의 형태로 운영되고 있습니다. 1개의 pod에는 설정할수 있는 CPU와 Memory의 값이 있는데요. 이부분이 최적의 조건으로 설정이 된것이 아니라 최대한 크게 지정되었고, 지속적으로 어플리케이션이 생겨남에 따라 복제가 되어 관리가 되질 않았습니다.

<ul>
<li>Request : 컨테이너에 필요한 최소 리소스양을 정의 -> pod가 스케쥴링 되는 방식에 영향</li>
<li>Limit : 컨테이너가 사용할 수 있는 최대 리소스 양을 정의</li>
<li>CPU: Unless your app is specifically designed to take advantage of multiple cores (scientific computing and some databases come to mind), it is usually a best practice to keep <strong>the CPU request at ‘1’ or below, and run more replicas to scale it out.</strong> This gives the system more flexibility and reliability.</li>
<li>Memory : Mbyte 단위</li>
</ul>

그동안 Request와 Limit의 기준이 모호하게 설정되어있습니다.

<pre><code class="language-yaml line-numbers">resources:  
    requests:    
        cpu: 5
        memory: 10Gi
    limits:    
        cpu: 5
        memory: 10Gi
</code></pre>

실제 예시로 위와 같이 CPU를 <strong>5 core</strong>를 사용하도록 설정이 된 부분도 있었습니다. 여기서 replica가 4개만 설정되어도 <strong>20 core</strong> Resource를 사용하도록 강제하는 것입니다.

<h3>Qos Classes of k8s PODs</h3>

<ul>
<li>서비스 품질(Qos)는 스케쥴러가 pod의 스케쥴링 및 제거 우선순위를 결정하는데 사용하는 kubernetes 개념입니다.</li>
</ul>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/miro.medium.com/max/1400/1%2AiGRP2cF86wMUWwztqQKi3A.png?w=1200&#038;ssl=1" alt="kubernetes QoS" />

<ul>
<li>종료 우선순위 : Base Effort > Burstable > Guaranteed

<ul>
<li>예를들어, Node에 메모리가 부족하게 되면, 종료를 하여 메모리를 확보</li>
</ul></li>
</ul>

<h2>2. k8s 리소스 최적화 방안</h2>

<strong>최적화</strong>가 어려운것은 <strong>정답</strong>이 없다는 것입니다. 필자가 운영하는 어플리케이션 마다의 비지니스도 다르고, 각자가 사용하는 리소스 소모량도 분명히 차이가 있었습니다.

우선 지난 1년간 수집된 <strong>Metric</strong>기반으로 데이터를 분석하기로 했습니다. 평균적으로 사용하는 양을 구했고 아래와 같이 CPU에 대한 사용률은 거의 없고, Memory 위주로 사용하는 것을 식별했습니다.

<table>
<thead>
<tr>
  <th>Namespace</th>
  <th>POD Name</th>
  <th>CPU</th>
  <th>Memory</th>
  <th>CPU optimization</th>
  <th>Memory Optimization</th>
</tr>
</thead>
<tbody>
<tr>
  <td>test-biz</td>
  <td>test-biz-custody-7b757d6664-8nl5q</td>
  <td>9m</td>
  <td>927Mi</td>
  <td>500m</td>
  <td>2Gi</td>
</tr>
<tr>
  <td>test-biz</td>
  <td>test-biz-custody-d77bffb45-nh929</td>
  <td>4m</td>
  <td>68Mi</td>
  <td>500m</td>
  <td>2Gi</td>
</tr>
<tr>
  <td>test-biz</td>
  <td>test-biz-gateway-5b8cc784b-bl58p</td>
  <td>16m</td>
  <td>695Mi</td>
  <td>500m</td>
  <td>2Gi</td>
</tr>
<tr>
  <td>test-biz</td>
  <td>test-biz-internal-gateway-65f489f884-t58br</td>
  <td>16m</td>
  <td>681Mi</td>
  <td>500m</td>
  <td>2Gi</td>
</tr>
<tr>
  <td>test-biz</td>
  <td>test-biz-member-6799f5c5d5-7k42h</td>
  <td>7m</td>
  <td>869Mi</td>
  <td>500m</td>
  <td>2Gi</td>
</tr>
<tr>
  <td>test-game</td>
  <td>test-game-5d4f9c64ff-twc6f</td>
  <td>5m</td>
  <td>67Mi</td>
  <td>500m</td>
  <td>2Gi</td>
</tr>
<tr>
  <td>test-market</td>
  <td>test-market-bff-54559c789-mn8ql</td>
  <td>4m</td>
  <td>68Mi</td>
  <td>500m</td>
  <td>2Gi</td>
</tr>
</tbody>
</table>

다음과 같은 기준에 의거하여 공통적인 Spec을 산정했습니다.

<ul>
<li>CPU 기준

<ul>
<li>.5 core 공통 적용</li>
<li>구글에서 <a class="wp-editor-md-post-content-link" href="https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-resource-requests-and-limits" target="_blank" rel="noopener">가이드</a>하는 문서를 따름.</li>
</ul></li>
<li>Memory 기준

<ul>
<li>1Gi 미만 : 2Gi</li>
<li>1Gi 이상 2Gi 미만 : 3Gi</li>
<li>2Gi 이상 3Gi 미만 : 4Gi</li>
<li>3Gi 이상 : 5Gi</li>
</ul></li>
</ul>

<h2>3. 최적화 진행한 맞이한 문제들</h2>

위에서 정한 Spec을 기준으로 수십개의 어플리케이션들을 전체적으로 재정의했고, 개발환경에 배포를 수행했습니다. 그런데 쉽게 될줄만 알았던 것이 문제에 봉착했었습니다.

<h3>어플리케이션 기동을 위한 최소한의 CPU</h3>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2022/09/resource_optimzation_1.png?w=1200&#038;ssl=1" alt="DevOps K8S Resource 최적화 사례 설명 이미지 1" />

어플리케이션이 최초 기동 시 여러가지 자원들을 생성하고 연결(DB, Kafka, Redis 등)과정을 수립하는데 있어 CPU 소모가 이전보다 더 발생을 하게 됩니다. 즉, 위와 같은 그래프 패턴을 보이게 되는데 평상시에 대한 체크만 수행을 했고, Start할때 최소한의 필요한 양을 산정하지 못했습니다.

확인을 해본결과 <strong>1 Core</strong>를 넘지 않는 것을 확인하고, 공통 Spec으로 1 Core로 수정하기로 했습니다.

<h3>JVM사용을 위한 최소한의 Memory</h3>

위에서 선정한 Memory의 최적화는 <a class="wp-editor-md-post-content-link" href="https://medium.com/@marketing_864/best-practices-java-memory-arguments-for-containers-1d704a65f7db" target="_blank" rel="noopener">컨테이너에 대한 Java 메모리 할당</a>을 참고했습니다. 이 곳에서 설명하길 아래와 같이 되어있습니다.

<blockquote>
  항상 컨테이너에 최소 25% 더 많은 메모리를 할당해야 합니다(예: &#8216;-m&#8217;). 힙 크기 값보다. -Xmx 값을 2GB로 구성한 다음 컨테이너의 메모리 크기를 2.5GB 이상으로 구성했다고 가정합니다.
  
  힙 공간 외에도 애플리케이션에는 Java 스레드, 가비지 컬렉션, 메타 공간, 기본 메모리, 소켓 버퍼를 위한 공간이 필요합니다. 이러한 모든 구성 요소에는 할당된 힙 크기를 초과하는 추가 메모리가 필요합니다
</blockquote>

예를들어 pod가 2.5Gi가 할당되고 JVM에 2Gi가 할당 됐을 때 최적의 모범사례라고 할 수 있습니다.

그래서 다음과 같이 JVM 스펙을 산청했습니다.

<ul>
<li>pod 2.5Gi -> jvm 2Gi</li>
<li>pod 3.5Gi -> jvm 3Gi</li>
<li>pod 4.5Gi -> jvm 3Gi</li>
<li>pod 5.5Gi -> jvm 4Gi</li>
</ul>

위의 기준으로 설정하여 특별히 Java Process에 문제가 발생을 하지 않도록 구성했습니다.

<h2>4. 결과</h2>

<h3>AS-IS</h3>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2022/09/resource_optimzation_2.png?w=1200&#038;ssl=1" alt="DevOps K8S Resource 최적화 사례 설명 이미지 2" />

master를 제외한 나머지 worker node들의 사용률이 아래와 같았고, 평균을 내면 위처럼 CPU가 대략 75%정도를 사용하고있었습니다.

<table>
<thead>
<tr>
  <th>Host Name</th>
  <th>Allocatable CPU</th>
  <th>CPU Requested</th>
  <th>Memory Requested</th>
</tr>
</thead>
<tbody>
<tr>
  <td>worker001</td>
  <td>7900m</td>
  <td>7455m (94%)</td>
  <td>11552310Ki (35%)</td>
</tr>
<tr>
  <td>worker002</td>
  <td>7900m</td>
  <td>7445m (94%)</td>
  <td>12559926Ki (38%)</td>
</tr>
<tr>
  <td>worker003</td>
  <td>7900m</td>
  <td>7445m (94%)</td>
  <td>13084214Ki (40%)</td>
</tr>
<tr>
  <td>Worker004</td>
  <td>7900m</td>
  <td>7445m (94%)</td>
  <td>8566396928 (25%)</td>
</tr>
</tbody>
</table>

<h3>TO-BE</h3>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2022/09/resource_optimization_3.png?w=1200&#038;ssl=1" alt="DevOps K8S Resource 최적화 사례 설명 이미지 3" />

절반정도로 CPU 요청량이 감소했으며, 어플리케이션 성능상에도 특별한 문제가 발생을 하지도 않았습니다.

<h2>5. 마치며&#8230;</h2>

<strong>최적화</strong>라는 것은 정답이 없기에 더더욱 어려운 것 같습니다. 이번의 최적화 작업을 진행하면서, 상황마다의 최적화 할 수 있는 요소들이 다양하다는 것을 느끼게 되었고, 확실히 <strong>데이터(Metric)</strong>기반으로 최적화를 진행하다보니 개발팀을 설득하기도 수월했다고 생각이 됩니다.

무수히 많은 어플리케이션들이 Cluster를 공유하면서 사용하다보니 자원이 많이 부족해질 수 있었던 상황인데 최적화를 통해서 쾌적환 환경을 제공할 수 있게 되어 굉장히 뿌듯했던 것 같습니다.

<h2>6. 참조</h2>

<a class="m-story" href="https://medium.com/inside-sumup/are-kubernetes-cpu-limits-bad-a04430bf54e1" target="_blank" data-width="1200" data-border="1" data-collapsed="" rel="noopener">Medium.com에서 보기</a>

https://blog.kubecost.com/blog/requests-and-limits/

<blockquote class="wp-embedded-content" data-secret="y1yPMn8xG9"><a href="https://itchain.wordpress.com/2018/05/16/kubernetes-resource-request-limit/" target="_blank" rel="noopener">Kubernetes Resource Request와 Limit의&nbsp;이해</a></blockquote><iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;Kubernetes Resource Request와 Limit의&nbsp;이해&#8221; &#8212; Peter&#039;s Story" src="https://itchain.wordpress.com/2018/05/16/kubernetes-resource-request-limit/embed/#?secret=biDWqPnJ5G#?secret=y1yPMn8xG9" data-secret="y1yPMn8xG9" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>

<a class="m-story" href="https://medium.com/blutv/qos-classes-of-k8s-pods-722238a61c93" target="_blank" data-width="1200" data-border="1" data-collapsed="" rel="noopener">Medium.com에서 보기</a>

https://kubesphere.io/blogs/understand-requests-and-limits-in-kubernetes/
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2021/09/01/kubeadm-pod-cidr-change/">[DevOps] kubeadm upgrade를 통한 pod cidr 변경</a></li><li><a href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a></li><li><a href="https://blog.wonizz.com/2023/05/11/devops-hubot-automation-1/">[DevOps] Hubot 적용기</a></li><li><a href="https://blog.wonizz.com/2023/05/09/devops-k8s-monitoring-with-datadog/">[DevOps] k8s monitoring with Datadog</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/09/19/devops-k8s-resource-optimization/">[DevOps] K8S Resource 최적화 사례</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2022/09/19/devops-k8s-resource-optimization/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1963</post-id>	</item>
		<item>
		<title>[DevOps] Docker Build Pipeline 구성하기</title>
		<link>https://blog.wonizz.com/2022/05/25/jenkins-k8s-cicd/</link>
					<comments>https://blog.wonizz.com/2022/05/25/jenkins-k8s-cicd/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Wed, 25 May 2022 11:47:28 +0000</pubDate>
				<category><![CDATA[kubernetes]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=1915</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 Docker Build Pipeline 구성하기에 대해서 정리를 하려고 합니다. 필자가 회사를 이직한지도 어느덧 5개월(5개월시점에 작성한 글입니다.) 정도 되고 있습니다. 이곳에서 k8s를 구성하면서 Deploy Tool로는 ArgoCd를 사용하고 있습니다. 젠킨스를 통해서 Build Job을 구성하고, ArgoCD에서 자동으로 배포할 수 있도록 구성은 이전의 포스팅에서 했었습니다. 아래의 내용을 참고 부탁드립니다. ArgoCD 설치 방법 : https://blog.wonizz.com/2020/06/08/kubernetes-deploy-tool-argocd/ ArgoCD&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/05/25/jenkins-k8s-cicd/">[DevOps] Docker Build Pipeline 구성하기</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 <strong>Docker Build Pipeline 구성하기</strong>에 대해서 정리를 하려고 합니다. 필자가 회사를 이직한지도 어느덧 5개월(5개월시점에 작성한 글입니다.) 정도 되고 있습니다. 이곳에서 k8s를 구성하면서 Deploy Tool로는 ArgoCd를 사용하고 있습니다.

젠킨스를 통해서 Build Job을 구성하고, ArgoCD에서 자동으로 배포할 수 있도록 구성은 이전의 포스팅에서 했었습니다.

아래의 내용을 참고 부탁드립니다.

<ul>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled />ArgoCD 설치 방법 : https://blog.wonizz.com/2020/06/08/kubernetes-deploy-tool-argocd/</li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled />ArgoCD  Slack Notification 방법 : https://blog.wonizz.com/2020/06/15/kubernetes-deploy-tool-notification/</li>
</ul>

이번 포스팅은 좀 더 CI(지속적 통합)에 중점을 두어 작성하려 합니다.

<h2>1. Jenkinsfiles 를 통한 pipeline 구축</h2>

젠킨스 파이프 라인을 통해서 빌드잡을 구성했습니다. 이전의 젠킨스 파이프라인에 대해서 정리해놓은 포스팅이 있으니 참고 부탁드립니다.

<ul>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled />Jenkins 파이프라인 사용법 : https://blog.wonizz.com/2019/08/04/jenkins-pipeline/</li>
</ul>

파이프라인의 흐름은 다음과 같이 구성을 했습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2022/05/jenkins_1.png?w=1200&#038;ssl=1" alt="jenkins_1" />

<ul>
<li>빌드가 시작되면, 운영자 / 개발자에게 시작 알림 메시지</li>
<li>git에서의 소스코드 체크아웃</li>
<li>Application Build ( gradle script를 통한 빌드 )</li>
<li>Image Build ( Jar file Copy )</li>
<li>Harbor push ( Image Repository )</li>
<li>빌드가 완료되면, 운영자/개발자에게  완료 알림 메시지</li>
</ul>

보시다시피, 파이프라인을 통해서 원하는 <strong>Stage</strong>별로 나눠서 Task를 실행하도록 해두었습니다. 그렇게 하다보니 어디부분에서 에러가 발생하는지 명확하게 볼 수 있었습니다.

<pre><code class="language-groovy line-numbers">final HARBOR_USERNAME = '{harbor bot 계정}'
final HARBOR_PASSWORD = '{harbor pw 토큰}'

pipeline {
    agent {
        node {
          label '{slave 고유의 이름}'
        }
    }
    parameters {
        string name: 'REVISION'
        booleanParam name: 'ONLY_BUILD'
    }
    environment {
                DOCKER_IMAGE_TAG = """${sh(
                returnStdout: true,
                script: 'echo ${REVISION#refs/tags/}'
                )}"""
                SLACK_CHANNEL = '{슬랙 채널명}'
                SLACK_TOKEN = '{슬랙 채널 토큰}'
    }
    stages {
        stage('Start Notification') {
            steps {
                slackSend(channel: SLACK_CHANNEL, color: '#ECB22E', message: "Build Start! (${env.BUILD_TAG})\n - phase : ${PHASE}\n- revision : ${DOCKER_IMAGE_TAG}", token: SLACK_TOKEN)
            }
        }
        stage('Checkout') {
           steps {
                checkout([$class: 'GitSCM',
                          branches: [[name: "${REVISION}"]],
                          doGenerateSubmoduleConfigurations: false,
                          extensions: [],
                          gitTool: 'Default',
                          submoduleCfg: [],
                          userRemoteConfigs: [[url: '{git 주소}']]
                        ])
            }
        }
        stage('Build Application') {
            tools {
                jdk 'JDK 8u121 + JCE'
            }
            steps {
                sh './gradlew clean assemble'
            }
        }
        stage('Application Test') {
            tools {
                jdk 'JDK 8u121 + JCE'
            }
            steps {
                sh './gradlew check integrationTest'
            }
        }
        stage('Harbor Log-in') {
                steps {
                  sh 'docker logout {harbor 주소}'
                    sh "docker login {harbor 주소} --username ${HARBOR_USERNAME} --password ${HARBOR_PASSWORD}"
                }
        }
        stage('Build Docker Image') {
            parallel {
                stage('Keystore2') {
                    steps {
                      sh 'docker build -t {harbor 주소}/{path}/{application name}:${DOCKER_IMAGE_TAG} --build-arg APPLICATION_PATH=apps/test --build-arg APPLICATION={application name} --build-arg "EXPOSE=29996 20082 20083" .'
                        sh 'docker push {harbor 주소}/{path}/{application name}:${DOCKER_IMAGE_TAG}'
                    }
                }
            }
        }
        stage ('Invoke_Helm Chart commit') {
            steps {
              build job: '{Invoked Job Name}', 
                parameters: [
                    string(name: 'PHASE', value: 'alpha'),
                    string(name: 'TARGET', value: 'link-framework'),
                    string(name: 'REVISION', value: String.valueOf(DOCKER_IMAGE_TAG)),
                    string(name: 'ONLY_BUILD', value: String.valueOf(ONLY_BUILD))
                ]
            }
        }
    }
    post {
      success {
        slackSend(channel: SLACK_CHANNEL, color: '#2EB67D', message: " Build Completed! (${env.BUILD_TAG})\n - phase : ${PHASE}\n- revision : ${DOCKER_IMAGE_TAG}", token: SLACK_TOKEN)
      }
      failure {
        slackSend(channel: SLACK_CHANNEL, color: '#E01E5A', message: " Build Failed: @{slack menthion}\n - phase : ${PHASE}\n - build url : ${env.BUILD_URL}", token: SLACK_TOKEN)
      }
   }
}
</code></pre>

최종적인 <strong>Jenkinsfiles</strong>의 구성은 위와 같습니다. 중요한 부분은 source를 체크아웃 받기 위해서 <strong>commit hash</strong>값을 인자로 받고 있습니다. 개발(커밋해시), 운영(태그)와 같이 2가지 방식으로 커밋 해시 값이 전달 됩니다.

<pre><code class="language-groovy line-numbers">    parameters {
        string name: 'REVISION'
        booleanParam name: 'ONLY_BUILD'
    }
    environment {
                DOCKER_IMAGE_TAG = """${sh(
                returnStdout: true,
                script: 'echo ${REVISION#refs/tags/}'
                )}"""
                SLACK_CHANNEL = '{슬랙 채널명}'
                SLACK_TOKEN = '{슬랙 채널 토큰}'
    }
</code></pre>

위와 같이 파라미터로 <strong>REVISION</strong>값을 받게 되어있는데, 개발같은 경우는 commit hash 값이 그대로 와서 사용이 가능하지만, tag는 (ref/tags/v2.1.4)와 같은 형태로 오기 때문에 <strong>environment</strong>에서 한번 replace를 해주는 과정이 있습니다.

<h2>2. 젠킨스 Job 구성</h2>

위에서 간단하게 설명하긴 했지만, 파이프라인 이전 스텝에서 2가지 방식으로 파라미터를 전달 받습니다.

<ul>
<li><strong>develop / release branch 푸시 : commit hash 값</strong></li>
</ul>

따라서, 앞에서는 2가지를 받을 수 있는 Job이 필요합니다. 그리고 각 Job에서는 다음과 같이 구성이 필요합니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2022/05/jenkins_2.png?w=1200&#038;ssl=1" alt="jenkins_2" />

Branch specifier부분에서 어떤 부분에 대해서 해당 Job이 감지를 할지 기입해 두면 됩니다. 
<strong>Trigger parameterized build on the project</strong>의 사전 정의 파라미터에서 아래와 같이 입력을 하게 됩니다.

<img decoding="async" src="/Users/user/업무/3_기타/01.블로그이미지/20211015/jenkins_3.png" alt="jenkins_3" />

<strong>GIT_COMMIT</strong>은 해당 브랜치에서 최신의 커밋 해시 버전을 가져옵니다.

같은 방식으로 Tag 생성시에는 아래와 같이 입력을 합니다.

<ul>
<li><strong>tag 생성시 : tag 버전</strong></li>
</ul>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2022/05/jenkins_4.png?w=1200&#038;ssl=1" alt="jenkins_4" />

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2022/05/jenkins_5.png?w=1200&#038;ssl=1" alt="jenkins_5" />

<strong>GIT_BRANCH</strong>는 해당 태그버전의 브랜치명을 가져옵니다.

<h2>3. Dockfile 최적화 작업</h2>

빌드를 수행하면서 Dockerfile에 대해서도 최적화 작업을 진행했습니다. 기존에는 Multi-stage 방식으로 아래와 같이 굉장히 긴 포맷으로 빌드를 수행했습니다.

<pre><code class="language-dockerfile line-numbers"># Build
FROM {harbor 주소}/{path}/{application name}/gradle:6.7.1-jdk8 AS build-env
ARG PROJECT

WORKDIR /{application name}
COPY . ./
RUN gradle clean :${PROJECT}:assemble

# Production
FROM {harbor 주소}/{path}/{application name}/openjdk:8-jre-alpine AS production-env

ARG PROJECT_PATH
ARG PROJECT
ARG EXPOSE
ENV JAR=${PROJECT}.jar
EXPOSE ${EXPOSE}

ENTRYPOINT /sbin/tini java \
${JAVA_OPTS} \
-jar ${JAR}

RUN addgroup -S -g 2001 www && adduser -S -u 1001 -G www www
RUN apk add --no-cache tini bash wget curl bind-tools && rm -rf /var/cache/apk/*
RUN sed -i s/.*networkaddress.cache.ttl.*/networkaddress.cache.ttl=0/g /usr/lib/jvm/java-1.8-openjdk/jre/lib/security/java.security
RUN sed -i s/.*networkaddress.cache.negative.ttl.*/networkaddress.cache.negative.ttl=0/g /usr/lib/jvm/java-1.8-openjdk/jre/lib/security/java.security

WORKDIR /home/www
USER www

# Copy test fils
COPY docker/test-custom.conf \
docker/test-env.conf \
docker/install_test_agent.sh \
./

# Install test agent
RUN sh install_test_agent.sh

# Copy kafka .jks files
COPY kafka ./kafka

# Copy jar
COPY --from=build-env --chown=www /{application 이름 }/${PROJECT_PATH}/${PROJECT}/build/libs/${PROJECT}.jar ./
</code></pre>

파일의 원본은 밝힐수 없어, 내용을 가렸습니다. 결론적으로 위와 같이 Multi Stage에서의 가장큰 문제는 매번 빌드를 수행할때마다, Build-env안에서는 gradle스크립트를 통해서 모든 빌드를 수행한다는 것입니다.

아래의 과정은 <strong>jenkinsfiles</strong>에서 1번만 수행하도록 변경했습니다.

<pre><code class="language-dockerfile line-numbers">RUN gradle clean :${PROJECT}:assemble
</code></pre>

추가적으로 아래와 같은 작업들을 더 진행했습니다.

<ul>
<li>Build 영역 삭제</li>
<li>COPY . ./ : COPY는 좀더 구체적으로 작성</li>
<li>RUN : layer를 출이기 위해 하나의 작업 단위로 구성</li>
<li>wget, curl : 불필요 의존성 제거 필요</li>
</ul>

최종적인 <strong>Dockerfile</strong>은 아래와 같은 모습으로 변경되었습니다.

<pre><code class="language-dockerfile line-numbers"># Production
FROM {harbor 주소}/{path}/{application name}/openjdk:8-jre-alpine-base

# Arguments & Environments
ARG PROJECT_PATH
ARG PROJECT
ARG EXPOSE

ENV JAR=${PROJECT}.jar
EXPOSE ${EXPOSE}

# Entrypoint for running docker 
ENTRYPOINT /sbin/tini java  \
${JAVA_OPTS} \
-jar ${JAR}

# Copy jar
COPY --chown=www /${PROJECT_PATH}/${PROJECT}/build/libs/${PROJECT}.jar ./
</code></pre>

엄청 간결해진것도 있고, 빌드 시간도 약 10m이 소요된것에서 2m정도로 많이 단축이 되었습니다.

<h2>4. 빌드 / 배포 아키텍처</h2>

전체적인 빌드 / 배포에 대한 아키텍처는 다음과 같습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2022/05/jenkins_6.png?w=1200&#038;ssl=1" alt="jenkins_6" />

<ul>
<li>develop branch : 개발/릴리즈 브랜치로부터 커밋 해시 추출</li>
<li>master branch : 태그 생성시 태그값 추출</li>
<li>pipeline  : 젠킨스 파일을 통한 빌드 파이프라인</li>
<li>helm chart update : 최종적으로 빌드가 완료되면, values.yaml 파일의 docker image 버전 업데이트</li>
</ul>

위와 같은 과정을 거치게 되고, <strong>ArgoCD</strong>에서는 helm chart가 변경되게 되면 싱크를 체크하여 변경내역을 확인합니다. 그리고 ArgoCD를 통해 sync를 수행하면 배포가 진행 되는 구조입니다.

<h2>5. 마치며&#8230;</h2>

빠른 개발과 안정적인 서비스를 위해서는 무엇보다도 빌드와 배포는 안정적으로 이루어져야 합니다. Jenkinsfiles와 Dockerfile의 최적화로 안정적인 CI를 구축했고, ArgoCD와 연계하기 위해 Helmchart를 중간에 업데이트 하도록 해두었습니다. 이로써, CI-CD간에 지속적인 통합과 배포가 이루어지도록 했습니다. 
개발자들도 새로운 시스템에서 빠른 이해로 안정적으로 개발을 진행하고 있습니다. 다음시간에는 ArgoCD에 대해서 좀더 심화학습 하여 정리하도록 하겠습니다.
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a></li><li><a href="https://blog.wonizz.com/2023/05/11/devops-hubot-automation-1/">[DevOps] Hubot 적용기</a></li><li><a href="https://blog.wonizz.com/2023/05/09/devops-k8s-monitoring-with-datadog/">[DevOps] k8s monitoring with Datadog</a></li><li><a href="https://blog.wonizz.com/2023/05/08/devops-istio-virtualhost/">[DevOps] Istio virtualhost 사용법</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/05/25/jenkins-k8s-cicd/">[DevOps] Docker Build Pipeline 구성하기</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2022/05/25/jenkins-k8s-cicd/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1915</post-id>	</item>
		<item>
		<title>[DevOps] k8s Horizontal POD autoscaling</title>
		<link>https://blog.wonizz.com/2022/05/18/devops-k8s-hpa/</link>
					<comments>https://blog.wonizz.com/2022/05/18/devops-k8s-hpa/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Wed, 18 May 2022 12:12:32 +0000</pubDate>
				<category><![CDATA[kubernetes]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=1911</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요 정리하는 개발자 워니즈입니다. 이번시간에는 쿠버네티스의 Pod의 Autoscaling에 대해서 정리를 해보는 시간을 갖도록 하겠습니다. HorizontalPodAutoscaler(HPA)는 CPU, 메모리 사용률 또는 일부 사용자 지정 메트릭을 기반으로 포드 수를 확장하는 Kubernetes의 별도 리소스 유형입니다. HPA는 애플리케이션 환경에서 유지 관리해야 하는 복제본 수를 최적화하는 데 도움이 되므로 부하 분산에 도움이 됩니다. HPA 컨트롤러는 주기적으로 메트릭을 확인합니다. 평균 CPU와 메모리가&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/05/18/devops-k8s-hpa/">[DevOps] k8s Horizontal POD autoscaling</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요 정리하는 개발자 워니즈입니다. 이번시간에는 쿠버네티스의 Pod의 <strong>Autoscaling</strong>에 대해서 정리를 해보는 시간을 갖도록 하겠습니다.

<strong>HorizontalPodAutoscaler(HPA)</strong>는 CPU, 메모리 사용률 또는 일부 사용자 지정 메트릭을 기반으로 포드 수를 확장하는 Kubernetes의 별도 리소스 유형입니다. HPA는 애플리케이션 환경에서 유지 관리해야 하는 복제본 수를 최적화하는 데 도움이 되므로 부하 분산에 도움이 됩니다.

HPA 컨트롤러는 주기적으로 메트릭을 확인합니다. 평균 CPU와 메모리가 너무 높아지면 대상 배포의 복제본 수를 늘리도록 k8에 지시합니다.

<h2>1. HPA 알고리즘</h2>

<h3>replica 계산 알고리즘</h3>

<pre><code class="line-numbers">desired_replica = ceil(current_replica * (현재 값/목표 값))
</code></pre>

위의 알고리즘을 이해하기 위해서 시나리오를 준비했습니다.

<strong>시나리오 1</strong>

응용 프로그램에 일부 비즈니스 요구 사항이 있고 물리적 제한을 기반으로 이상적인 CPU/메모리 수를 제시한다고 가정합니다. 작업자 노드에 대해 대상 CPU를 60% 미만으로 유지하려고 합니다. 그런 다음 트래픽이 급증하여 현재 사용률이 90%에 도달했습니다. 배포 개체에 3개의 복제본이 정의되어 있고 포드에 과부하가 걸립니다. 알고리즘을 사용하여 원하는 포드 수를 찾을 수 있습니다.

<pre><code class="line-numbers">목표 CPU 사용률: 60% 
현재 사용률: 90% 
현재 포드: 3 
원하는 포드 = ceil(current_pods * (현재 값/목표 값)) 
원하는 포드 = ceil(3*(.9/.6)) = 5
</code></pre>

이 시나리오에서 HPA 컨트롤러는 배포의 복제본을 5개로 변경하고 스케줄러는 2개의 포드를 더 추가하여 요구 사항을 업데이트합니다.

<strong>시나리오 2</strong>

일정 기간 후에 트래픽이 감소했고 현재 사용률이 20%로 떨어졌다고 가정해 보겠습니다. 추가 복제본이 자동으로 줄어들기를 바랍니다. HPA 컨트롤러가 어떻게 우리의 소원을 들어주는지 봅시다.

<pre><code class="line-numbers">대상 CPU 사용률: 60% 
현재 사용률: 20% 
현재 포드: 5 
원하는 포드 = ceil(5*(.3/.6)) = 2
</code></pre>

여기에서는 2개의 복제본만 있으면 충분하다고 판단하고 배포 컨트롤러에 이 수로 줄이도록 지시합니다. 그러나 배포 개체의 최소 복제본 수는 3입니다. 따라서 kubernetes는 이를 존중하고 복제본 수를 5에서 3으로 줄입니다.

<h2>2. k8s 에서의 오토스케일링</h2>

<h3>1) Cluster Autoscaler</h3>

<img decoding="async" src="https://miro.medium.com/max/1400/0*CyQVykoco5oiVlGP" alt="DevOps k8s Horizontal POD autoscaling 설명 이미지 1" />

Cluster Autoscaler는 resource부족으로 scheduling이 안된 pod(pending상태의 pod)가 존재할때 node를 scale out 합니다.

그리고 Cluster에 장시간동안 utilization이 낮은 node가 있고, 이 node에 있는 pod를 다른 node에 재배치할 수 있을때 node를 scale in 합니다.

CA는 10초에 한번씩 pod를 검사하며 빠르게 scale out, scale in을 합니다. 하지만 한번 node가 scale out 되면 scale in 검사를 하기까지 10분동안 대기를 하기때문에 scale out은 비교적 빠르게, scale in은 비교적 느리게 진행된다고 할 수 있습니다.

<ol>
<li>클러스터 자동 확장 처리 알고리즘이 Pending Pod를 확인합니다.</li>
<li>클러스터 자동 확장 처리에 의해 새로운 Worker Node를 요청합니다.</li>
<li>Kubernetes는 기본 인프라(ex, GCP, AWS, Azur)에 의한 프로비저닝된 새 노드를 감지합니다.</li>
<li>Kubernetes 스케쥴러는 보류 중인 포드를 새 노드에 할당 합니다.</li>
</ol>

<h3>2) VPA (Vertical Pod Autoscaling)</h3>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/global-uploads.webflow.com/5d2dd7e1b4a76d8b803ac1aa/5f5619d41fdbf118d1b83121_Vertical%20pod%20Autoscaling.png?w=1200&#038;ssl=1" alt="DevOps k8s Horizontal POD autoscaling 설명 이미지 2" />

VPA(Vertical Pod Autoscaling)는 컨테이너 리소스가 과소 또는 과도하게 활용되지 않도록 합니다. 최적화된 CPU 및 메모리 요청/제한 값을 권장하고 클러스터 리소스가 효율적으로 사용되도록 자동으로 업데이트할 수도 있습니다.

vpa는 pod의 resource 사용량에 맞게 resource request를 조절해서 pod가 node에 스케쥴링될때 적절한 크기의 resouce를 할당받을 수 있도록 합니다.

vpa는 hpa와 마찬가지로 metric server를 통해 pod들의 resource 사용량을 관찰합니다. 이 resource사용량이 일정기준 이상으로 늘어나면 pod를 scale out하고, 그 반대일때는 scale in합니다.

<a class="wp-editor-md-post-content-link" href="https://github.com/kubernetes/autoscaler/tree/master/vertical-pod-autoscaler" target="_blank" rel="noopener">VPA github</a>

<pre><code class="language-yaml line-numbers">resources:
   requests:
      memory: {{ .Values.minMem }}
      cpu: {{ .Values.minCpu }}
   limits:
      memory: {{ .Values.maxMem }}
      cpu: {{ .Values.maxCpu }}
</code></pre>

vpa는 deployment의 yaml 파일에서 request, limit의 값을 비율에 맞춰서 업데이트를 수행합니다.

<pre><code class="language-yaml line-numbers">apiVersion: "autoscaling.k8s.io/v1beta2"
kind: VerticalPodAutoscaler
metadata:
  name: test-vpa
spec:
  targetRef:
    apiVersion: "apps/v1"
    kind: Deployment
    name: test
  updatePolicy:
    updateMode: "Auto"
  resourcePolicy:
    containerPolicies:
      - containerName: '*'
        minAllowed:
          cpu: 100m
          memory: 50Mi
        maxAllowed:
          cpu: 1
          memory: 500Mi
        controlledResources: ["cpu", "memory"]
</code></pre>

<ul>
<li>Auto mode : VPA는 Pod의 리소스 사용량을 일정 주기 이상 모니터링 한 후에, 그 Metric을 기반으로, Pod resource의 request값을 변경해주는 방식.</li>
<li>Manual mode : VPA가 직접 request 내용을 변경하지 않고, 적절하게 필요한 request양을 추천해줍니다.</li>
</ul>

<pre><code class="language-yaml line-numbers"># kubectl get vpa [vpa name] -o yaml
recommendation:
    containerRecommendations:
    - containerName: my-rec-container
      lowerBound:
        cpu: 315m
        memory: 262144k
      target:
        cpu: 587m
        memory: 262144k
      Uncapped target:
        cpu: 587m
        memory: 262144k
     upperBound:
        cpu: 1000m
        memory: 500Mi
</code></pre>

<ul>
<li>Target: VPA에서 포드에 적용할 컨테이너에 대한 권장 CPU 요청 및 메모리 요청입니다.</li>
<li>Uncapped Target: VPA 정의에서 상한/하한을 구성하지 않은 경우 컨테이너에 대한 권장 CPU 요청 및 메모리 요청입니다.</li>
<li>lowerBound: 컨테이너에 대해 권장되는 최소 CPU 요청 및 메모리 요청입니다.</li>
<li>upperBound: 컨테이너에 대해 권장되는 최대 CPU 요청 및 메모리 요청입니다.</li>
</ul>

<h3>3) HPA (Horizontal Pod Autoscaling)</h3>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/global-uploads.webflow.com/5d2dd7e1b4a76d8b803ac1aa/5f5617f11c3d8e1aeff818c9_Horizontal%20Pod%20Autoscaling.png?w=1200&#038;ssl=1" alt="DevOps k8s Horizontal POD autoscaling 설명 이미지 3" />

HPA는 리소스 메트릭 API에서 포드당 리소스 메트릭(예: CPU, 메모리)을 가져오고 모든 대상 포드의 평균 값을 기반으로 현재 메트릭 값을 계산합니다. 현재 메트릭 값을 HPA 사양에 지정된 대상 메트릭 값과 비교하고 원하는 복제본 수를 확장하는 데 사용되는 비율을 생성합니다.

<ul>
<li>metric-server 로부터 생성된 pod의 metric을 기반으로 replica / Deployment / statefulset 과 같은 리소스에 대해 오토 스케일링이 가능하다.</li>
<li>HPA는 쿠버네티스 API리소스 및 컨트롤러로 구현됩니다.</li>
</ul>

<h4>HPA Configuration</h4>

<ul>
<li>behavior

<pre><code class="language-yaml line-numbers">behavior:
 scaleDown:
   stabilizationWindowSeconds: 300 ( 기본 5분 )
   policies:
   - type: Percent
     value: 10
     periodSeconds: 30
   - type: Pods
     value: 1
     periodSeconds: 120
   selectPolicy: Min
</code></pre>

<ul>
<li>stabilizationWindowSeconds : 안정화 윈도우는 메트릭이 계속해서 변할 때 replica의 개수가 너무 자주 변경되지 않도록 제한하기 위해서 사용.</li>
<li><strong>스케일링이 일어난 후, 5분동안 수집된 metric들 중에 가장 큰 수치 변화를 감지.</strong></li>
<li><strong>값이 0이라면, scaling 계산을 바로 하자마자 작업 시작.</strong></li>
<li>policy : percent, pods로 scale에 대한 정책 정의</li>
<li><strong>percent는 해당 시간동안에 퍼센트만큼을 증가/감소</strong></li>
<li><strong>pods는 해당 value만큼 갯수를 증가/감소</strong></li>
<li>select policy에 의해 2개 설정중 더 작은(min)값 선택</li>
<li>축소하는 동안 last 동안 가장 안전한(가장 큰) &#8220;desiredReplicas&#8221; 번호를 선택해야 합니다</li>
<li>확장하는 동안 last 동안 가장 안전한(가장 작은) &#8220;desiredReplicas&#8221; 번호를 선택해야 합니다</li>
</ul></li>
<li>metric

<ul>
<li>resource 정의 메트릭 : CPU, MEMORY</li>
</ul>

<pre><code class="language-yaml line-numbers">  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50
</code></pre>

<ul>
<li>metric-server에서 제공하는 pod의 resource에 대한 metric이고 주로 사용</p></li>
<li>사용자 정의 메트릭 : 네트워크 트래픽</p></li>
</ul>

<pre><code class="language-yaml line-numbers">type: Pods
pods:
  metric:
    name: packets-per-second
  target:
    type: AverageValue
    averageValue: 1k
</code></pre>

<ul>
<li>metric-server가 아닌 외부의 metric solution 공급업체(prometheus) 에서 제공하는 metric</li>
<li>https://github.com/kubernetes/metrics/blob/master/IMPLEMENTATIONS.md#custom-metrics-api</p></li>
<li>Object 메트릭</p></li>
</ul>

<pre><code class="language-yaml line-numbers">type: Object
object:
  metric:
    name: requests-per-second
  describedObject:
    apiVersion: networking.k8s.io/v1beta1
    kind: Ingress
    name: main-route
  target:
    type: Value
    value: 2k
</code></pre></li>
</ul>

<h2>2. HPA custom metric 적용</h2>

HPA를 사용하게 되면, CPU, Memory 이외의  Custom Metric을 이용하여 오토스케일링을 구성하고 싶을때가 있습니다. 커스텀 메트릭을 구성하기 위해서는 Prometheus Adapter를 별도로 설치해야 합니다.

<ul>
<li>custom metric을 사용하기 위해서는 prometheus-adapter 리소스를 사용하여 custom.metrics.k8s.io/v1beta1에 사용자 지정 어플리케이션 메트릭을 노출합니다. (<strong>kubernetes v1.16 이상</strong>)</li>
<li>prometheus adapter는 custom metrics를 별도의 API인 Aggregation Layer에 등록한 뒤, 원하는 모니터링 데이터를 Prometheus로부터 PromQL 형식을 통해 가져와 Custom Metrics API에 제공하는 역할을 합니다.

<ul>
<li>Prometheus Adapter가 Prometheus에 쿼리를 요청한 후, Kubernetes API에 해당 데이터를 등록하여 HPA에 사용할 수 있게 하는 방식</li>
</ul></li>
</ul>

<h3>설치 방법</h3>

<a class="wp-editor-md-post-content-link" href="https://github.com/prometheus-community/helm-charts/blob/main/charts/prometheus-adapter/README.md" target="_blank" rel="noopener">Prometheus Adapter github</a>

프로메테우스 공식 헬름 차트를 통하여 설치를 진행합니다. ReadMe를 참고하면 설치를 진행할수 있고,, values.yaml 파일의 수정을 통해서 설치를 진행합니다.

<pre><code class="language-yaml line-numbers">prometheus:
  url: http://prometheus-server
  port: 0
image:
  tag: latest
rules:
  custom:
     - seriesQuery: 'container_network_receive_packets_total{namespace!="",pod!=""}'
       resources:
          overrides:
              namespace: {resource: "namespace"}
              pod: {resource: "pod"}
          name:
                   matches: "container_network_receive_packets_total"
                   as: "network_in"
          metricsQuery: <<.Series>>{<<.LabelMatchers>>}
</code></pre>

<h3>Custom Metric 조회</h3>

<ul>
<li>prometheus-adapter 리소스를 사용하여 등록하면, <strong>custom.metrics.k8s.io/v1beta1</strong>애 사용자 지정 메트릭을 노출 시킵니다.</li>
</ul>

<pre><code class="language-yaml line-numbers">$ kubectl get --raw /apis/custom.metrics.k8s.io/v1beta1/namespaces/test-ns/pods/test-admin-74b4578f75-qvd7j/network_in | jq .
{
   "kind": "MetricValueList",
   "apiVersion": "custom.metrics.k8s.io/v1beta1",
   "metadata": {
   "selfLink": "/apis/custom.metrics.k8s.io/v1beta1/namespaces/link-me/pods/alpha-lbw-admin-74b4578f75-qvd7j/network_in"
},
"items": [
  {
     "describedObject": {
     "kind": "Pod",
     "namespace": "test-ns",
     "name": "test-admin-74b4578f75-qvd7j",
     "apiVersion": "/v1"
  },
   "metricName": "network_in",
   "timestamp": "2021-10-13T06:34:48Z",
   "value": "5367472m",
   "selector": null
  }
 ]
}
</code></pre>

<h2>3. 마치며..</h2>

쿠버네티스는 확실히 유연한 플랫폼인것 같습니다. 사용자가 지정한대로 resource 효율화를 달성하고 최적화의 개념으로 서비스를 안정적으로 운영할 수 있게 도움을 주는 것 같습니다. HPA를 아직 필자도 실서비스에 도입을 한것은 아니지만, 몇가지 MSA도입을 하게 되면 확실히 효과는 클 것으로 보고 있습니다. 나중에 도입을 하고나서 실제로 운영상에 도움이 되었는지 후기를 작성하도록 하겠습니다.

<h2>4. 참고</h2>

<a class="wp-editor-md-post-content-link" href="https://medium.com/dtevangelist/k8s-kubernetes%EC%9D%98-hpa%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-%EC%98%A4%ED%86%A0%EC%8A%A4%EC%BC%80%EC%9D%BC%EB%A7%81-auto-scaling-2fc6aca61c26" target="_blank" rel="noopener">[K8S] Kubernetes의 HPA를 활용한 오토스케일링(Auto Scaling)</a>
<a class="wp-editor-md-post-content-link" href="https://asishmm.medium.com/discussion-on-horizontal-pod-autoscaler-with-a-demo-on-local-k8s-cluster-81694c09f818" target="_blank" rel="noopener">Discussion on Horizontal Pod Autoscaler with a demo on local k8s cluster</a>
<a class="wp-editor-md-post-content-link" href="https://haereeroo.tistory.com/22?category=1184037" target="_blank" rel="noopener">https://haereeroo.tistory.com/22?category=1184037</a>
<a class="wp-editor-md-post-content-link" href="https://www.velotio.com/engineering-blog/autoscaling-in-kubernetes-using-hpa-vpa" target="_blank" rel="noopener">Autoscaling in Kubernetes using HPA and VPA</a>
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2023/05/09/devops-k8s-monitoring-with-datadog/">[DevOps] k8s monitoring with Datadog</a></li><li><a href="https://blog.wonizz.com/2021/12/20/devops-k8s-log-aggregation/">[DevOps] k8s Log 수집 시스템 구성</a></li><li><a href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a></li><li><a href="https://blog.wonizz.com/2023/05/11/devops-hubot-automation-1/">[DevOps] Hubot 적용기</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/05/18/devops-k8s-hpa/">[DevOps] k8s Horizontal POD autoscaling</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2022/05/18/devops-k8s-hpa/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1911</post-id>	</item>
		<item>
		<title>[Kubernetes] k8s master 서버 HA 구성하기</title>
		<link>https://blog.wonizz.com/2022/04/18/kubernetes-k8s-master-server-ha/</link>
					<comments>https://blog.wonizz.com/2022/04/18/kubernetes-k8s-master-server-ha/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 18 Apr 2022 00:49:33 +0000</pubDate>
				<category><![CDATA[kubernetes]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=1904</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 k8s master 서버의 가용성 환경 구성에 대해서 정리를 하고자 합니다. 필자는 kubespray를 통해서 cluster를 구축을 했는데요. 특별히 별도의 설정을 하지 않으며, master 1번 서버를 api-server로 사용하게 됩니다. 그러다보니 고가용성에서 문제가 발생을 하게 되어, LB를 연결하여 LB의 VIP를 바라보도록 설정하는 내용입니다. 1. 쿠버네티스 아키텍처 쿠버네티스는 control plane(master), storage system(etcd), 다수의 nodes(worker,&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/04/18/kubernetes-k8s-master-server-ha/">[Kubernetes] k8s master 서버 HA 구성하기</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 k8s master 서버의 가용성 환경 구성에 대해서 정리를 하고자 합니다. 필자는 <code>kubespray</code>를 통해서 cluster를 구축을 했는데요. 특별히 별도의 설정을 하지 않으며, <code>master 1번</code> 서버를 api-server로 사용하게 됩니다. 그러다보니 고가용성에서 문제가 발생을 하게 되어, LB를 연결하여 LB의 VIP를 바라보도록 설정하는 내용입니다.

<h2>1. 쿠버네티스 아키텍처</h2>

쿠버네티스는 <code>control plane(master)</code>, <code>storage system(etcd)</code>, <code>다수의 nodes(worker, kubelets)</code>로 이루어져 있습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/platform9.com/wp-content/uploads/2019/05/kubernetes-constructs-concepts-architecture.jpg?w=1200&#038;ssl=1" alt="k8s_architecture_1" />

여기 부분에서 <code>control plane(master)</code>에 좀더 집중을 해서 확인을 해보겠습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/platform9.com/wp-content/uploads/2019/05/Kubernetes-control-plane-taxonomy.jpg?w=1200&#038;ssl=1" alt="k8s_architecture_2" />

master 영역은 k8s의 개체를 기록하고 유지 관리하는 시스템입니다. 클러스터의 변경 사항에 응답하여 객체 상태를 지속적으로 관리합니다.

master 영역은 다음 세가지로 구성이 되어있습니다.

<ul>
<li>kube-apister

<blockquote>
  API 서버는 다양한 유형의 어플리케이션에 대한 수명 주기 오케스트레이션(확장, 업데이트 등)을 지원하는 API를 제공합니다. 클라이언트는 API 서버를 통해 인증하고 이를 노드 및 포트에 대한 프록시 / 터미널로 사용합니다.
</blockquote></li>
<li>kube-controller-manager

<blockquote>
  Controller Manager는 핵심 제어 루프를 실행하고 클러스터의 상태를 감시하며 원하는 상태로 드라이브 상태를 변경하는 데몬입니다.
</blockquote></li>
<li>Kube-scheduler

<blockquote>
  Scheduler는 클러스터의 노드 전체에 걸쳐 컨테이너의 스케쥴링을 담당합니다. 리소스 제한 또는 보장, 선호도 및 반선호도 사양과 같은 다양한 조건을 고려합니다.
</blockquote></li>
</ul>

<h2>2. 현상태의 문제점</h2>

필자가 운영하는 서비스에서는 <code>kubespray</code>를 통해서 k8s를 설치했습니다. 그런데 위의 아키텍처에서 <code>kube-apiserver</code>가 master의 대수만큼 존재를 하게 되는데 여기서 <code>1번서버</code>하고만 통신을 하도록 초기 구성이 되어있었습니다.

즉, 과한 통신량을 받게 되면 Master는 혼자서 감당하기 힘들며 1번 서버에 문제가 생겨 고장나면 <code>api-server</code>가 통신을 못하게 되므로 k8s cluster에 영향을 받게 됩니다. 따라서 이를 고가용성으로 Load Balancing에 api-server를 연결하여 LB와 통신을 하도록 변경하고자 합니다.

<a class="wp-editor-md-post-content-link" href="https://kubernetes.io/ko/docs/setup/production-environment/tools/kubeadm/ha-topology/" target="_blank" rel="noopener">고가용성 토폴로지 선택</a>

<img decoding="async" src="https://d33wubrfki0l68.cloudfront.net/d1411cded83856552f37911eb4522d9887ca4e83/b94b2/images/kubeadm/kubeadm-ha-topology-stacked-etcd.svg" alt="k8s_architecture_3" />

위의 구성과 같이 LB를 통해서 모든 <code>worker nodes</code>와 <code>client</code>들이 통신을 수행하도록 구성을 하고 <code>etcd</code>는 각 master 서버에 구성되는 <code>stacked etcd cluster</code>를 구성할 예정입니다.

<h2>2. LB 신규 생성</h2>

필자가 속한 회사에서는 사내의 Private Cloud가 존재하고 그곳에서 손쉽게 LB를 생성할 수 있습니다. 
LB의 6443 포트로 접속을 하면 3대의 master 서버로 분산을 해주도록 설정을 했습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2022/04/k8s_ha_1.png?w=1200&#038;ssl=1" alt="ha_1" />

<h2>3. k8s upgrade</h2>

이제 준비는 모두 됐고, k8s의 모든 설정들을 LB의 endpoint를 보도록 변경을 하고 해당 내용을 반영해주는 작업을 수행합니다.

<a class="wp-editor-md-post-content-link" href="https://stackoverflow.com/questions/65505137/how-to-convert-a-kubernetes-non-ha-control-plane-into-an-ha-control-plane" target="_blank" rel="noopener">How to convert a Kubernetes non-HA control plane into an HA control plane?</a>

위의 내용을 정리해오면서 알게 된것은 초기 k8s cluster 구축시기부터 HA로 구성을 해야한다는 것입니다. 필자는 Non-HA구성을 HA구성으로 전환하려는 것인데, 이는 추천하는 방식이 아니라고 합니다.

<h3>3-1. Upgrade the kube-apiserver certificate</h3>

kube-apiserver는 control plane 트래픽을 암호화 하는 인증서를 갖고, 이 인증서는 <code>SAN(Subject Alternative Name)</code> 이라고 알려진 객체를 갖고 있습니다. SAN은 API에 접근하는데 사용되는 IP리스트를 갖고 있습니다. 
그래서 초기 작업은 이 SAN의 IP리스트를 LB의 endpoint로 업데이트 하는 것입니다.

<pre><code class="language-yaml line-numbers">...
controlPlaneEndpoint: 10.128.174.74:6443
certificatesDir: /etc/kubernetes/ssl
imageRepository: k8s.gcr.io
...
  certSANs:
  - 10.128.174.74
...
</code></pre>

kube-apiserver를 업데이트하기 전에 <code>/etc/kubernetes/pki</code>의 apiserver 관련된 cert 파일을 지우거나 백업을 해둡니다.

<pre><code class="language-bash line-numbers">$ mkdir /etc/kubernetes/pki_bak
$ cd /etc/kubernetes
$ mv /etc/kubernetes/pki/apiserver.crt /etc/kubernetes/pki_bak
$ mv /etc/kubernetes/pkiapiserver.key /etc/kubernetes/pki_bak

#kubeadm을통한 인증서 갱신
$ kubeadm init phase certs apiserver --config kubeadm-config.yaml

</code></pre>

<h3>3-2. Update the kubelet, the scheduler and the controller manager kubeconfig files</h3>

다음스텝은 kube-apiserver와 통신하는 kubelet, scheduler 그리고 controller-manager를 모두 LB의 endpoint로 업데이트를 해주는 것입니다.

<ul>
<li>/etc/kubernetes/kubelet.conf</li>
<li>/etc/kubernetes/scheduler.conf</li>
<li>/etc/kubernetes/controller-manager.conf</li>
</ul>

위의 파일에서 <code>server:</code> 영역을 kube-apiserver에서 LB의 endpoint로 변경을 수행합니다.

<pre><code class="language-bash line-numbers"># kubelet restart 
systemctl restart kubelet 

# scheduler, controller-manager restart
kill -s SIGHUP $(pidof kube-controller-manager)
kill -s SIGHUP $(pidof kube-scheduler)
</code></pre>

<h3>3-3. Update the kube-proxy kubeconfig files</h3>

다음스텝은 <code>kube-proxy</code>의 <code>server:</code>영역을 LB의 endpoint로 업데이트를 수행합니다.

<pre><code class="language-bash line-numbers">$ kubectl edit cm kube-proxy -n kube-system
</code></pre>

변경하고나서 업데이트를 하는것을 잊지 말라고 되어있지만, 실제로 kube-proxy같은 경우 필자는 자동으로 업데이트가 되어있어 이부분은 스킵하고 지나갔습니다.

<h3>3-4. Update the kubeadm-config configmap</h3>

마지막 스텝으로는 모든 준비가 됐으므로, kubeadm을 통해서 클러스터에 대한 업그레이드를 진행합니다. 최초에 kubeadm-config를 수정했으므로 이를 반영해준다고 보면 됩니다.

<pre><code class="language-bash line-numbers">$ kubeadm upgrade apply --config kubeadm-config.yaml --ignore-preflight-errors all --force --v=5
</code></pre>

<h3>3-5. Update the cluster-info configmap</h3>

추가적인 내용인데, cluster 정보를 표기할 때, 이부분이 새로 작성한 LB의 endpoint로 노출이 되도록 설정을 업데이트 하는 내용입니다. master의 1대에서 작업을 하면 되고 아래의 커맨드를 통해서 업데이트 합니다.

<pre><code class="language-bash line-numbers">$ kubectl -n kube-public edit cm cluster-info
</code></pre>

<h3>3-5. 다른 마스터 노드 업그레이드</h3>

업그레이드는 클러스터의 모든 마스터를 업데이트하지 않고 현재 있는 마스터만 업그레이드를 진행합니다. 따라서 다른 2대의 마스터노드에서도 위의 작업을 동일하게 수행해줍니다.

<h2>4. 테스트</h2>

이번 HA 구성의 목적은 개별적인 <code>master node</code>의 api-server 프로세스가 내려가더라도 다른 노드를 통해서 k8s의 api 호출이 가능하도록 구성을 하는 것 입니다. 그렇기 때문에 테스트는 <code>master node</code>를 임의로 서비스를 내려두고 호출을 했을 경우, 정상적으로 되는지를 확인 해 봅니다.

<h3>4-1. 각 master 서버에서 실행</h3>

각 master 서버의 api-server를 한번 내려보고 재기동 되는 사이 바로 api 호출을 통해서 정상적으로 호출이 되는지를 확인 해봅니다.

<pre><code class="language-bash line-numbers"># master 1번 서버
$ kill -s SIGHUP $(pidof kube-apiserver)

# master 1번 서버 
$ kubectl get pod 
No resources found in default namespace.
</code></pre>

<h3>4-2. 각 master를 제외한 나머지 2대 서비스 중지</h3>

<pre><code class="language-bash line-numbers"># master 2,3번 서버 
$ kill -s SIGHUP $(pidof kube-apiserver)

# master 1번 서버 
$ kubectl get pod 
No resources found in default namespace.
</code></pre>

이전에는 <code>4-1</code>케이스 같은 경우, 정상적으로 호출이 되지 않았을 것입니다. 이제는 각 master 서버의 api-server를 바라보는 것이 아니라, LB의 end-point를 바라보고 있기 때문에 다른 하나가 문제가 발생을 하더라도 정상적으로 호출이 가능할 것 입니다.

<h2>5. 마치며..</h2>

이번시간에는 master 서버의 HA 구성에 대해서 정리를 해보았습니다. 서두에도 정리했듯이 non-HA구성에서 HA구성으로 가는 것은 지양하고 있습니다. 최초에 클러스터 구축시 HA를 고려하여 kubespray의 코드를 변경하는 것이 더 좋아 보입니다.

다음시간에는 kbuespray를 통한 node 증설에 대해서 정리를 해보도록 하겠습니다.

<h2>6. 참조</h2>

<a class="wp-editor-md-post-content-link" href="https://velog.io/@pingping95/Kubernetes-kubeadm-Master-%EA%B3%A0%EA%B0%80%EC%9A%A9%EC%84%B1" target="_blank" rel="noopener">kubeadm Master 3개 설정 (Haproxy)</a>

<a class="wp-editor-md-post-content-link" href="https://stackoverflow.com/questions/65505137/how-to-convert-a-kubernetes-non-ha-control-plane-into-an-ha-control-plane" target="_blank" rel="noopener">How to convert a Kubernetes non-HA control plane into an HA control plane?</a>

<a class="wp-editor-md-post-content-link" href="https://blog.honosoft.com/2020/01/31/kubeadm-how-to-upgrade-update-your-configuration/" target="_blank" rel="noopener">kubeadm – How to “upgrade” (update) your configuration</a>

<a class="wp-editor-md-post-content-link" href="https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/high-availability/" target="_blank" rel="noopener">Creating Highly Available Clusters with kubeadm</a>
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2020/01/03/kubernetes-helm-chart-template/">[Kubernetes] Helm Chart Template 정리</a></li><li><a href="https://blog.wonizz.com/2019/11/28/kubernetes-aws-eks-volume/">[Kubernetes] AWS EKS에 볼륨 마운트 해보기</a></li><li><a href="https://blog.wonizz.com/2023/05/09/devops-k8s-monitoring-with-datadog/">[DevOps] k8s monitoring with Datadog</a></li><li><a href="https://blog.wonizz.com/2022/05/25/jenkins-k8s-cicd/">[DevOps] Docker Build Pipeline 구성하기</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/04/18/kubernetes-k8s-master-server-ha/">[Kubernetes] k8s master 서버 HA 구성하기</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2022/04/18/kubernetes-k8s-master-server-ha/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1904</post-id>	</item>
	</channel>
</rss>
