<?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>AWS &#8211; WONIZZ.LOG</title>
	<atom:link href="https://blog.wonizz.com/category/tech/aws/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.wonizz.com</link>
	<description>AI 자동화를 직접 굴려 본 개발자의 실무 교훈</description>
	<lastBuildDate>Mon, 28 Sep 2026 05:42:11 +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>AWS &#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] RDS 비용 줄이기, 통합 4단계</title>
		<link>https://blog.wonizz.com/2026/09/24/rds-cost-reduction/</link>
					<comments>https://blog.wonizz.com/2026/09/24/rds-cost-reduction/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Thu, 24 Sep 2026 10:13:11 +0000</pubDate>
				<category><![CDATA[AWS]]></category>
		<category><![CDATA[DB마이그레이션]]></category>
		<category><![CDATA[MariaDB]]></category>
		<category><![CDATA[RDS]]></category>
		<category><![CDATA[비용절감]]></category>
		<guid isPermaLink="false">https://blog.wonizz.com/?p=3699</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>RDS 비용을 로컬 DB 통합으로 걷어낸 4단계 절차를 정리했습니다. 덤프 제외와 해시 대조, 컷오버 중 실제로 낸 사고 1건까지 그대로 적었습니다.</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2026/09/24/rds-cost-reduction/">[DevOps] RDS 비용 줄이기, 통합 4단계</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>청구서를 열 때마다 RDS 한 줄이 제일 굵은데 그 데이터베이스가 정말 관리형이어야 하는지 스스로 물어보신 적 있으신가요?</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번 글은 개인 블로그 한 대를 굴리면서 RDS 비용 항목을 통째로 걷어낸 과정을 4단계 절차로 정리한 기록입니다. 자랑하려고 쓰는 글이 아니라 어떤 순서로 무엇을 확인했는지 남기는 것이 목적이라서 중간에 제가 낸 사고 한 건도 숨기지 않고 적었습니다.</p>
<blockquote><p>
한 줄 요약입니다. 트래픽이 작은 단일 서버 사이트에서 RDS 비용의 대부분은 관리형 인스턴스 시간 요금이고 애플리케이션 서버에 이미 깔려 있는 DB로 합치면 그 줄이 통째로 사라집니다. 다만 무중단 전환이라는 말은 그 순간에도 쓰기가 들어온다는 뜻이라서 컷오버 직전에 다른 쓰기 주체를 멈추지 않으면 데이터가 갈라집니다.
</p></blockquote>
<p>먼저 결론 세 줄을 접어둡니다.</p>
<ul>
<li>관리형 DB를 쓰는 이유가 다중화나 자동 백업이 아니라 그냥 처음에 그렇게 만들어서라면 <strong>RDS 비용은 줄일 수 있는 고정비</strong>입니다.</li>
<li>옮길 때 쓸모없는 데이터는 지우는 것이 아니라 덤프 단계에서 안 가져가는 쪽이 안전하고 빠릅니다.</li>
<li>되돌릴 길을 남기는 비용은 아주 작으므로 최종 스냅샷 한 장은 남기고 지우는 편이 낫습니다.</li>
</ul>
<p>목차입니다.</p>
<ol>
<li>RDS 비용은 어디에서 새고 있나요</li>
<li>관리형 DB를 걷어내면 무엇이 같이 사라지나요</li>
<li>1단계, 지금 무엇이 돈을 쓰는지 확인한다</li>
<li>2단계, 옮길 데이터를 고른다</li>
<li>3단계, 무결성을 해시로 증명한다</li>
<li>4단계, 컷오버하고 되돌릴 길을 남긴다</li>
<li>RDS 비용을 줄이는 다른 선택지와 견주면 어떤가</li>
<li>안 되는 것, 중지로는 안 끊기고 컷오버 중에도 쓰기는 들어온다</li>
<li>RDS 비용 줄이기는 누구에게 맞고 누구에게는 굳이인가 그리고 필자의 결론</li>
</ol>
<h2>1. RDS 비용은 어디에서 새고 있나요</h2>
<p>개인 사이트에서 RDS 비용이 커지는 이유는 쿼리를 많이 날려서가 아닙니다. 관리형 데이터베이스는 트래픽이 0이어도 인스턴스가 떠 있는 시간만큼 과금되고 거기에 스토리지와 백업 스토리지가 따로 붙습니다. 그래서 하루 방문이 적은 블로그일수록 요청당 원가가 올라가고 청구서에서 RDS 비용이 차지하는 비중이 커지는 구조가 됩니다.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>과금 축</th>
<th>무엇으로 계산되나</th>
<th>트래픽이 0이면</th>
</tr>
</thead>
<tbody>
<tr>
<td>인스턴스 시간</td>
<td>인스턴스 클래스와 가동 시간</td>
<td>그대로 나온다</td>
</tr>
<tr>
<td>할당 스토리지</td>
<td>프로비저닝한 용량 기준</td>
<td>그대로 나온다</td>
</tr>
<tr>
<td>백업 스토리지</td>
<td>할당 용량을 넘는 분량</td>
<td>대체로 소액</td>
</tr>
<tr>
<td>데이터 전송</td>
<td>가용 영역을 넘는 통신량</td>
<td>거의 없다</td>
</tr>
</tbody>
</table>
</figure>
<p>여기서 제일 굵은 축은 첫 줄입니다. 관리형 DB의 가치는 장애 조치와 자동 백업과 패치 자동화인데 단일 인스턴스로 띄워 두었다면 그 가치의 절반은 애초에 사지 않은 셈입니다. <strong>그러면 RDS 비용은 쓰지 않는 기능의 구독료가 됩니다.</strong></p>
<p>정확한 단가는 리전과 시점마다 달라지므로 이 글에 숫자를 박아 넣지 않았습니다. 대신 자기 환경의 RDS 비용을 직접 계산하려면 두 곳만 보면 됩니다. 인스턴스 클래스별 시간 단가는 <a href="https://aws.amazon.com/rds/mysql/pricing/" target="_blank" rel="noopener">Amazon RDS for MySQL 요금 페이지</a>에 리전별로 나와 있고 스토리지와 백업까지 합친 월 예상액은 <a href="https://calculator.aws/" target="_blank" rel="noopener">AWS Pricing Calculator</a>에서 인스턴스 클래스와 용량을 넣으면 바로 나옵니다. 이 두 페이지를 근거로 잡아야 남이 쓴 블로그 숫자를 그대로 옮겨 적는 실수를 피할 수 있습니다.</p>
<h3>필자가 실제로 걷어낸 구성은 이렇습니다</h3>
<p>워드프레스 블로그 한 대였고 애플리케이션 서버는 소형 인스턴스 한 대였습니다. 데이터베이스만 별도의 소형 관리형 인스턴스로 떠 있었고 단일 가용 영역 구성이라 장애 조치 기능은 쓰고 있지 않았습니다. 정리하면 RDS 비용을 매달 내면서 관리형이 주는 핵심 이점은 하나도 쓰지 않는 상태였습니다.</p>
<h2>2. 관리형 DB를 걷어내면 무엇이 같이 사라지나요</h2>
<p>통합을 결심하기 전에 무엇을 포기하는지부터 적어야 합니다. RDS 비용이 사라지는 대신 아래 넷이 같이 사라집니다.</p>
<ul>
<li>자동 백업과 시점 복구입니다. 로컬 DB에서는 덤프를 거는 잡을 직접 만들어야 합니다.</li>
<li>마이너 버전 자동 패치입니다. 이제 DB 업그레이드 일정은 제가 챙겨야 하는 일이 됩니다.</li>
<li>장애 조치입니다. 원래 단일 인스턴스였다면 잃는 것이 없습니다.</li>
<li>자원 격리입니다. 이것이 가장 실질적인 대가인데 8번 항목에서 다시 적겠습니다.</li>
</ul>
<p>반대로 얻는 것은 세 가지입니다. 고정비에서 한 줄이 통째로 빠지고 애플리케이션과 DB 사이의 네트워크 왕복이 없어지며 DB 접속 경로가 서버 안쪽으로 들어가 외부에 열린 면이 줄어듭니다.</p>
<blockquote><p>
그래서 판단 기준은 단순합니다. 다중화와 자동 백업을 실제로 쓰고 있다면 RDS 비용은 기능값이고 쓰지 않는다면 그냥 고정비입니다.
</p></blockquote>
<h3>사라진 자동 백업을 무엇으로 메우나요</h3>
<p>여기가 통합에서 제일 미루기 쉬운 자리입니다. 관리형에서는 백업이 기본값으로 켜져 있어서 아무도 신경 쓰지 않는데 로컬로 내려오면 켜는 사람이 없으면 아무 일도 일어나지 않습니다. 최소 구성은 덤프를 하루 한 번 떠서 같은 디스크가 아닌 다른 저장소에 올리는 잡 하나입니다. 같은 서버의 다른 디렉터리에 두는 것은 백업이 아니라 복사본이고 디스크나 인스턴스가 통째로 날아가는 사고에서는 원본과 같이 사라집니다. 저는 이 숙제를 아직 끝내지 못했고 그 상태를 9번 항목에 그대로 적어 두었습니다.</p>
<h2>3. 1단계, 지금 무엇이 돈을 쓰는지 확인한다</h2>
<p>첫 단계는 옮기는 작업이 아니라 세는 작업입니다. 감으로 RDS 비용이 크다고 말하면 통합을 마친 뒤에도 무엇이 줄었는지 설명하지 못하고 다음에 같은 판단을 다시 할 근거도 남지 않습니다.</p>
<p>확인할 것은 셋입니다. 청구서의 서비스별 지출에서 데이터베이스 항목이 차지하는 비중을 먼저 보고 그 다음 인스턴스가 다중 가용 영역인지 단일인지를 콘솔에서 확인합니다. 마지막으로 애플리케이션 서버에 이미 DB 엔진이 깔려 있는지를 봅니다.</p>
<p>첫 번째 확인은 비용 관리 콘솔의 서비스별 보기에서 합니다. 여기서 봐야 할 것은 총액이 아니라 순위입니다. 데이터베이스가 1위인지 아닌지에 따라 이 작업의 값어치가 갈리고 2위 이하라면 RDS 비용보다 먼저 손댈 축이 따로 있다는 뜻입니다. 저는 컴퓨팅과 스토리지와 고정 아이피를 전부 합친 것과 데이터베이스 한 줄이 비슷한 크기였기 때문에 우선순위가 바로 정해졌습니다.</p>
<h3>서버에 DB가 이미 깔려 있는지 먼저 보세요</h3>
<p>제 경우 세 번째 확인에서 판이 끝났습니다. 서버가 Bitnami 워드프레스 스택이었는데 이 스택은 MariaDB를 함께 설치하고 구동까지 해 둡니다. 즉 데이터베이스 프로세스가 이미 서버 안에서 돌고 있었고 워드프레스만 바깥의 관리형 인스턴스를 바라보고 있었습니다.</p>
<p>이 구조에서 통합에 필요한 작업의 본체는 <code>wp-config.php</code>의 <code>DB_HOST</code> 한 줄 교체입니다. 새 서버를 띄우지도 않고 엔진을 새로 깔지도 않습니다. Bitnami 계열 이미지나 원클릭 설치본으로 서버를 만든 뒤 별도로 RDS를 붙였다면 지금 서버에 접속해 DB 프로세스가 떠 있는지부터 보시길 권합니다. <strong>RDS 비용을 내면서 쓰지 않는 DB 엔진을 같은 서버에 켜 두고 있을 가능성이 낮지 않습니다.</strong><br />
<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2026/09/01-vs.png?w=1200&#038;ssl=1" alt="RDS 비용 통합 전후의 접속 경로를 좌우로 대조한 구성도" /></p>
<h3>직접 확인 1, 로컬 DB의 정체를 먼저 확인했습니다</h3>
<p>서버 안에 있던 로컬 데이터베이스는 2023년에 설치되고 방치된 기본 스키마였습니다. 테이블 12개에 0.6MB였고 글 4개가 들어 있었으며 사이트 주소가 루프백으로 잡혀 있었습니다. 실제로 쓰이지 않는 껍데기임을 확인한 뒤에야 덮어쓰기로 방향을 잡았습니다. 이 확인을 건너뛰고 바로 부었다면 무엇을 지웠는지 모르는 상태가 됩니다.</p>
<h2>4. 2단계, 옮길 데이터를 고른다</h2>
<p>여기가 이 글에서 가장 재사용성이 높은 부분이라고 생각합니다. 제 DB는 1,017MB였는데 그 가운데 931MB가 스팸 가입 계정이었습니다. 2018년부터 열려 있던 회원가입 기능으로 구독자 권한 계정이 54만 개 넘게 쌓였고 사용자 메타 테이블에는 767만 행이 붙어 있었습니다. 실제 사람 계정은 네 개였습니다.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>테이블</th>
<th>통합 전 행 수</th>
<th>성격</th>
</tr>
</thead>
<tbody>
<tr>
<td>사용자 메타</td>
<td>767만 행</td>
<td>스팸 계정의 기본 프로필 키 11종</td>
</tr>
<tr>
<td>사용자</td>
<td>54만 행</td>
<td>구독자 권한이 대부분</td>
</tr>
<tr>
<td>글</td>
<td>3,042행</td>
<td>실제 콘텐츠</td>
</tr>
<tr>
<td>나머지 47개 테이블</td>
<td>합계 약 27MB</td>
<td>설정과 분류와 플러그인</td>
</tr>
</tbody>
</table>
</figure>
<p>삭제해도 되는지는 따로 판정했습니다. 구독자 권한 계정 가운데 글을 가진 계정과 댓글을 가진 계정이 각각 0이었기 때문에 재할당할 대상이 없었고 메타 행도 워드프레스 기본 프로필 키만 붙어 있었습니다. 이 판정 없이 사용자 테이블을 건드리면 남의 글의 작성자가 사라지는 사고로 이어집니다.</p>
<h3>지우지 말고 덤프에서 빼는 이유가 무엇일까요</h3>
<p>보통은 운영 DB에서 스팸 계정을 삭제한 다음 옮깁니다. 저는 지우지 않고 덤프 단계에서 제외했습니다. 이유가 셋입니다.</p>
<ol>
<li>운영 DB에 쓰기 작업이 0입니다. 살아 있는 사이트에서 대량 삭제를 돌리지 않습니다.</li>
<li>롤백이 한 줄입니다. 원본이 손대지 않은 상태로 남아 있으니 되돌릴 때 접속 주소만 바꾸면 됩니다.</li>
<li>가져오기가 곧 테이블 재구축이라 단편화가 저절로 정리됩니다. 별도로 최적화 명령을 돌릴 필요가 없습니다.</li>
</ol>
<p>명령은 세 줄입니다. 전체에서 사용자 계열 두 테이블을 빼고 받은 다음 남길 계정만 조건으로 걸어 따로 받습니다. <code>--where</code> 옵션의 동작은 <a href="https://dev.mysql.com/doc/refman/8.4/en/mysqldump.html" target="_blank" rel="noopener">MySQL 공식 mysqldump 문서</a>에 정의되어 있습니다.</p>
<pre class="wp-block-code"><code class="language-bash">OPT="--single-transaction --quick --skip-lock-tables --default-character-set=utf8mb4"
mariadb-dump $OPT --ignore-table=$DB.wp_users --ignore-table=$DB.wp_usermeta $DB > 01_main.sql
mariadb-dump $OPT --where="ID IN ($KEEP)" $DB wp_users > 02_users.sql
mariadb-dump $OPT --where="user_id IN ($KEEP)" $DB wp_usermeta > 03_usermeta.sql</code></pre>
<p>결과로 덤프 용량이 1,017MB에서 87.7MB가 됐습니다. 백업 스토리지와 복구 시간이 함께 줄어드는 것이라 RDS 비용을 정리하는 작업의 부산물치고는 꽤 큽니다.</p>
<h3>직접 확인 2, 엔진이 다르면 덤프를 먼저 읽습니다</h3>
<p>관리형 쪽은 MySQL 8.4였고 서버 안 로컬은 MariaDB 11.1이었습니다. 두 엔진은 이름이 비슷하지만 버전 게이트 주석 처리에서 갈립니다. MariaDB는 자기 버전 번호가 커서 MySQL이 넣어둔 <code>/*!8xxxx */</code> 조건부 주석을 조건 충족으로 보고 실행해 버립니다. 이것이 MySQL 8 덤프를 MariaDB에 넣을 때의 대표 사고 지점입니다.</p>
<p>그래서 파이프로 바로 붓지 않고 덤프 파일을 서버 디스크에 떨어뜨린 다음 읽었습니다.</p>
<pre class="wp-block-code"><code class="language-bash">grep -o '/\*!8[0-9]*' 01_main.sql | sort | uniq -c
grep -c 'utf8mb4_0900' 01_main.sql</code></pre>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>검사 항목</th>
<th>실측 결과</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>/*!8xxxx</code> 버전 게이트 주석</td>
<td>0건이고 전부 4.x 대 주석이었다</td>
</tr>
<tr>
<td>콜레이션</td>
<td><code>utf8mb4_unicode_520_ci</code> 단일이라 MariaDB가 받는다</td>
</tr>
<tr>
<td><code>utf8mb4_0900</code> 계열</td>
<td>0건</td>
</tr>
<tr>
<td><code>INVISIBLE</code>, <code>GENERATED ALWAYS</code>, <code>DEFINER=</code></td>
<td>전부 0건</td>
</tr>
</tbody>
</table>
</figure>
<p>MySQL 8의 기본 콜레이션인 <code>utf8mb4_0900_ai_ci</code>가 섞여 있었다면 MariaDB가 받지 못해 덤프를 다시 만들어야 했습니다. 제 사이트는 워드프레스가 옛 콜레이션을 쓰고 있어 통과했습니다. 여기서 걸리는 분이 있다면 그 상태로는 통합을 진행하지 마시고 콜레이션 변환부터 계획하셔야 합니다.</p>
<h2>5. 3단계, 무결성을 해시로 증명한다</h2>
<p>가져오기는 5초대에 끝났습니다. 문제는 그 다음입니다. 행 수가 같다는 것은 내용이 같다는 뜻이 아닌데 많은 이전 작업이 행 수 대조에서 멈춥니다.</p>
<p>저도 처음에는 행 수와 아이디 집합만 봤습니다. 그 방법으로는 아이디가 같고 내용이 다른 행을 잡지 못합니다. 그래서 검사를 한 층 더 넣었습니다.</p>
<h3>대조는 운영 DB가 아니라 검증용 스키마에서 합니다</h3>
<p>운영 DB를 건드리지 않으려고 검증 전용 스키마를 새로 만들고 덤프 세 개를 그대로 부었습니다. 이러면 덤프를 뜬 그 시점의 상태가 재현되므로 비교 축이 두 개로 갈립니다.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>대조 축</th>
<th>무엇을 묻는가</th>
</tr>
</thead>
<tbody>
<tr>
<td>검증용 스키마와 원본 DB</td>
<td>덤프가 놓친 것이 있나</td>
</tr>
<tr>
<td>검증용 스키마와 라이브 DB</td>
<td>가져오기가 실패한 것이 있나</td>
</tr>
</tbody>
</table>
</figure>
<p>대조 방법은 전 컬럼 해시입니다. 컬럼 목록을 <code>information_schema</code>에서 순서대로 뽑아 문자열로 이어 붙인 다음 행마다 해시를 내고 정렬해 집합 차분을 냅니다. NULL과 빈 문자열을 구분하려고 센티널 문자열을 끼워 넣었습니다.</p>
<pre class="wp-block-code"><code class="language-sql">SELECT MD5(CONCAT_WS('|', IFNULL(ID,'~N~'), IFNULL(post_name,'~N~'), IFNULL(post_content,'~N~')))
FROM wp_posts ORDER BY ID;</code></pre>
<p>실제로는 위처럼 컬럼 세 개가 아니라 테이블마다 전 컬럼을 동적으로 이어 붙였습니다. 개념만 보이려고 줄인 형태입니다.<br />
<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2026/09/02-steps-1.png?w=1200&#038;ssl=1" alt="덤프와 원본과 라이브를 해시로 3자 대조하는 절차도" /></p>
<h3>직접 확인 3, 48개 테이블 중 44개가 바이트 단위로 일치했습니다</h3>
<p>한글 본문이 들어 있는 글 테이블과 메타 테이블이 전부 해시 일치했습니다. <strong>MySQL 8.4에서 MariaDB 11.1로 넘어가면서 utf8mb4 한글이 깨지지 않았다는 것이 이렇게 실증됐습니다.</strong> 인코딩 변환은 가장 무섭고 가장 조용한 사고 유형이라 이 확인을 넣은 값을 했다고 봅니다.</p>
<p>차이가 난 것은 네 개 테이블 23행뿐이었고 정체가 전부 설명됐습니다. 그 가운데 20행은 컷오버 도중에 만들어진 글 하나의 부산물이었고 나머지는 만료된 임시 값과 크론 잠금 같은 휘발성 상태였습니다. 라이브 쪽에서는 핵심 10개 테이블에서 덤프에만 있고 라이브에 없는 기본 키가 0건이었습니다.</p>
<h3>실패한 검증도 적어 둡니다</h3>
<p>본문 해시를 비교할 때 수정 시각이 컷오버보다 이른 글만 거르는 조건을 양쪽에 걸었더니 45건 불일치가 나왔습니다. 처음에는 훼손을 의심했는데 원인은 필터였습니다. 컷오버 이후에 수정된 글이 라이브 쪽에서만 조건에서 빠져 대상 건수가 애초에 달랐던 것입니다. 본문 길이가 짧아진 글은 0건이었습니다.</p>
<p>교훈은 한 줄입니다. 대조 대상 건수가 양쪽에서 다르면 불일치를 보기 전에 그 차이부터 설명해야 합니다.</p>
<h2>6. 4단계, 컷오버하고 되돌릴 길을 남긴다</h2>
<p>접속 주소를 바꾸는 작업 자체는 한 줄입니다. 기존 주소 줄은 지우지 않고 주석으로 남겨 두면 롤백이 주석 두 개를 뒤집는 일이 됩니다. 서버 재시작도 필요 없었습니다.</p>
<h3>전환 완료 판정은 설정 파일이 아니라 트래픽으로 합니다</h3>
<p>설정 파일을 고쳤다고 전환이 끝난 것이 아닙니다. 캐시나 상주 프로세스가 옛 커넥션을 붙들고 있으면 파일만 바뀐 상태가 됩니다. 그래서 양쪽 DB의 누적 쿼리 카운터를 전후로 재고 델타를 봤습니다.</p>
<p>라이브 요청을 여덟 개 넣자 로컬 쪽 카운터만 네 자리로 올라갔고 관리형 쪽 델타는 측정 쿼리 두 개뿐이었습니다. 프로세스 목록에도 애플리케이션 커넥션이 남지 않았습니다. <strong>여기까지 봐야 트래픽이 어디로 가는지가 확정됩니다.</strong></p>
<p>판정을 더 굳히려고 관리형 인스턴스를 콘솔에서 중지시키고 사이트를 다시 쟀습니다. 25초 간격으로 폴링했더니 인스턴스가 실제로 도달 불가가 된 시점 이후에도 홈과 REST 응답과 로그인 화면과 사이트맵이 전부 200이었습니다. 원본이 꺼진 상태에서 사이트가 멀쩡한 것을 본 다음에야 삭제로 넘어갔습니다.</p>
<h3>직접 확인 4, 데이터가 메모리가 아니라 디스크에 있는지 봤습니다</h3>
<p>삭제 직전에 하나를 더 했습니다. 로컬 DB 프로세스를 죽였다가 다시 올린 다음 데이터가 그대로인지 본 것입니다. 통합 직후에는 캐시에 올라와 있던 것을 보고 있을 가능성을 배제할 수 없기 때문입니다.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>확인 항목</th>
<th>재시작 전</th>
<th>재시작 후</th>
</tr>
</thead>
<tbody>
<tr>
<td>DB 프로세스 아이디</td>
<td>기존 값</td>
<td>새 값으로 바뀜</td>
</tr>
<tr>
<td>발행 글 수와 전체 글 수</td>
<td>같음</td>
<td>같음</td>
</tr>
<tr>
<td>전체 본문 지문 해시</td>
<td>기준값</td>
<td>동일</td>
</tr>
<tr>
<td>사이트 응답</td>
<td>200</td>
<td>200</td>
</tr>
</tbody>
</table>
</figure>
<p>전체 본문 지문은 글마다 해시를 내고 그것들을 다시 한 번 해시한 값입니다. 프로세스가 실제로 새로 뜬 것을 아이디 변화로 확인했고 그 뒤에도 지문이 같았으니 데이터가 디스크 파일에 있다는 뜻입니다. 데이터 디렉터리가 루트 볼륨 위에 있어서 서버 이미지를 뜨면 DB도 함께 실린다는 점까지 같이 확인했습니다.</p>
<h3>삭제할 때 최종 스냅샷은 남기세요</h3>
<p>삭제 다이얼로그에서 최종 스냅샷 생성을 체크하고 이름에 날짜를 박았습니다. 자동 백업 보존은 해제했습니다. 최종 스냅샷과 겹치는데 백업 스토리지가 따로 붙기 때문입니다. 스냅샷은 완전 무료가 아니지만 실제 데이터가 1GB 남짓이면 인스턴스 시간 요금과는 자릿수가 다릅니다. RDS 비용을 줄이는 목적과 복구본을 남기는 목적이 여기서 미세하게 충돌하는데 저는 스냅샷 쪽을 택했습니다.</p>
<p>주의할 점이 하나 있습니다. 이 스냅샷은 계정이 살아 있는 동안만 유효합니다. 계정을 닫으면 같이 사라지므로 계정 자체를 정리할 계획이라면 스냅샷이 아니라 덤프 파일을 다른 곳에 내려두셔야 합니다.<br />
<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2026/09/03-timeline.png?w=1200&#038;ssl=1" alt="컷오버와 최종 스냅샷 보존까지의 순서를 정리한 흐름도" /></p>
<h2>7. RDS 비용을 줄이는 다른 선택지와 견주면 어떤가</h2>
<p>통합만이 답은 아닙니다. 제가 실제로 시도했거나 검토한 선택지를 견주면 이렇습니다.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>선택지</th>
<th>RDS 비용에 주는 효과</th>
<th>걸리는 지점</th>
</tr>
</thead>
<tbody>
<tr>
<td>인스턴스 클래스 축소</td>
<td>시간 요금이 줄지만 축은 남는다</td>
<td>메모리 하한에 곧 닿는다</td>
</tr>
<tr>
<td>인스턴스 중지</td>
<td>인스턴스 시간 요금만 멈춘다</td>
<td>최대 7일 뒤 자동 재기동된다</td>
</tr>
<tr>
<td>로컬 DB 통합</td>
<td>인스턴스 축이 통째로 사라진다</td>
<td>자원 경합과 백업이 내 일이 된다</td>
</tr>
<tr>
<td>관리형 유지</td>
<td>없다</td>
<td>다중화를 쓴다면 이쪽이 맞다</td>
</tr>
</tbody>
</table>
</figure>
<p>중지 선택지는 특히 오해하기 쉽습니다. 콘솔의 동의 문구에 이미 적혀 있는데 중지한 인스턴스는 일정 기간이 지나면 자동으로 다시 켜집니다. 저는 두 번 중지했고 두 번 다 되살아났습니다. 두 번째는 35분 만이었습니다. 이벤트 로그에는 복구 시작과 재시작이 연달아 찍혀 있었고 그 인스턴스가 마이너 버전 자동 업그레이드 대상이면서 유지 관리 보류 항목을 가지고 있었습니다. 강제 롤아웃 때문으로 보이지만 AWS 내부 동작을 제가 볼 수단은 없어서 원인은 미확인으로 둡니다.</p>
<p>확실한 것만 적으면 이렇습니다. 중지 직후에 상태가 중지됨으로 바뀐 것을 보고 RDS 비용을 끊었다고 판정하면 안 되고 몇 시간 뒤에 상태를 다시 확인해야 합니다.</p>
<p>중지 다이얼로그에는 함정이 하나 더 있었습니다. 확인 버튼만 누르면 아무 반응 없이 실패하는데 에러 배너도 뜨지 않습니다. 다이얼로그 안에 동의 체크박스가 따로 있고 그것을 먼저 체크해야 버튼이 동작합니다. 저는 두 번 조용히 실패한 뒤에야 원인을 찾았습니다. 콘솔 조작에서 상태가 안 바뀐 것을 성공으로 오판하지 않으려면 클릭한 다음 상태 문자열을 반드시 다시 읽어야 합니다.</p>
<h2>8. 안 되는 것, 중지로는 안 끊기고 컷오버 중에도 쓰기는 들어온다</h2>
<p>여기가 이 글에서 제일 중요하게 읽히길 바라는 절입니다. 성공한 절차만 적으면 다음 사람이 같은 자리에서 넘어집니다.</p>
<h3>컷오버 도중에 다른 쓰기 주체가 붙어 있었습니다</h3>
<p>삭제 직전 정밀 검사에서 원본에만 있는 글 1행과 메타 2행이 나왔습니다. 아이디 집합만 보면 그냥 세 행 차이인데 자연키로 대조하니 상황이 달랐습니다. 같은 아이디 번호를 양쪽 DB가 서로 다른 객체에 독립적으로 발급하고 있었습니다.</p>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>아이디</th>
<th>원본 쪽</th>
<th>로컬 쪽</th>
</tr>
</thead>
<tbody>
<tr>
<td>3593</td>
<td>초안 상태의 글</td>
<td>같은 글의 발행 상태</td>
</tr>
<tr>
<td>3594</td>
<td>이미지 첨부 레코드</td>
<td>전혀 다른 리비전</td>
</tr>
<tr>
<td>3595</td>
<td>리비전</td>
<td>없음</td>
</tr>
</tbody>
</table>
</figure>
<p>시각을 정리하니 원인이 분명했습니다. 덤프를 뜨고 접속 주소를 바꾼 뒤 2분이 지난 시점에 원본 쪽에 새 글 레코드가 기록되어 있었습니다. 같은 시간대에 다른 자동화 작업이 이 블로그에 글을 올리고 있었고 컷오버 직후 남아 있던 요청이 옛 경로로 들어간 것입니다. 그 결과 두 데이터베이스가 같은 자동 증가 구간을 각자 소비했습니다.</p>
<blockquote><p>
제가 놓친 것은 기술이 아니라 절차였습니다. 무중단 전환이라 안전하다고 봤는데 무중단이라는 말은 그 순간에도 쓰기가 들어온다는 뜻입니다.
</p></blockquote>
<p>실제 피해는 크지 않았습니다. 이미지 파일 다섯 종이 디스크에 남았는데 로컬 DB에 첨부 레코드가 없어 미디어 라이브러리에 안 보이는 상태가 됐습니다. 해당 글은 정상 발행됐고 대표 이미지도 다른 첨부를 쓰고 있어 독자에게 보이는 손상은 없었습니다. 그래도 운이 좋았던 것이지 절차가 막아준 것이 아닙니다.</p>
<h3>같은 사고를 막는 절차 세 줄</h3>
<ul>
<li>컷오버 전에 크론과 발행 파이프라인과 자동화 세션을 먼저 멈춥니다. 붙어 있는 쓰기 주체를 목록으로 적고 하나씩 끕니다.</li>
<li>행 수 일치를 전환 완료 근거로 쓰지 않습니다. 덤프 시점 이후에도 원본이 쓰기를 계속 받으면 그 일치는 금방 깨집니다.</li>
<li>아이디 집합 비교와 자연키 비교를 같이 돌립니다. 파일 경로나 슬러그처럼 사람이 만든 키가 있어야 같은 번호 다른 내용을 잡습니다.</li>
</ul>
<h3>메모리는 줄고 경합은 새로 생깁니다</h3>
<p>통합 직후 서버의 사용 가능 메모리는 오히려 줄었습니다. 통합 전 496MB였던 것이 401MB가 되어 95MB가 빠졌는데요, 워드프레스가 바깥 DB로 커넥션을 유지하던 몫은 사라졌지만 로컬 DB 프로세스가 새로 차지하는 상주 메모리가 그보다 컸기 때문입니다. 그 상주 메모리 자체는 100MB 아래였으니 감소 폭은 예상 범위 안이었습니다. 그런데 이 숫자는 지금 트래픽 기준입니다. 방문이 늘면 웹 서버와 DB가 같은 메모리 풀을 나눠 쓰게 되고 그때는 둘 중 하나가 밀립니다. 관리형을 쓸 때는 이 경합이 아예 없었으니 <strong>RDS 비용을 줄이면서 산 위험이 정확히 이것입니다.</strong></p>
<h3>통합해도 안 풀리는 것도 있습니다</h3>
<p>통합은 RDS 비용을 없애지만 그 서버가 원래 안고 있던 문제까지 고쳐주지 않습니다. 제 경우 리다이렉션 플러그인이 참조하는 테이블 두 개가 없어서 요청마다 DB 에러가 쌓이고 있었는데 이것은 관리형 쪽에도 똑같이 없던 선행 결함이었습니다. 이전 작업 중에 발견한 문제를 이전 탓으로 오인하지 않으려면 통합 전 상태를 먼저 기록해 두는 편이 낫습니다.</p>
<h2>9. RDS 비용 줄이기는 누구에게 맞고 누구에게는 굳이인가 그리고 필자의 결론</h2>
<p>먼저 맞는 쪽입니다. 단일 가용 영역으로 관리형 DB를 쓰고 있고 애플리케이션 서버에 DB 엔진이 이미 깔려 있으며 데이터가 수 기가바이트 이하인 개인 사이트라면 이 4단계는 하루 안에 끝납니다. 얻는 것은 매달 반복되는 고정비 한 줄이고 잃는 것은 지금도 쓰지 않던 기능입니다.</p>
<p>굳이인 쪽도 분명합니다. 다중 가용 영역을 켜 두었거나 시점 복구를 실제로 써 본 적이 있거나 DB가 여러 애플리케이션의 공용이라면 RDS 비용은 기능에 대한 값이므로 걷어낼 대상이 아닙니다. 서버 메모리가 이미 빠듯하다면 더욱 그렇습니다.</p>
<h3>그래서 필자는 무엇을 하기로 했는가</h3>
<p><strong>필자는 이 블로그에서 관리형 DB를 다시 쓰지 않기로 했습니다.</strong> 통합 뒤 데이터베이스가 애플리케이션과 같은 인스턴스에 올라왔으니 메모리 경합이 새 위험으로 들어온 것이 사실이고 앞으로 트래픽이 늘면 가장 먼저 흔들릴 자리도 거기입니다. 그 대가를 알고도 받아들였습니다. 지금 이 사이트에서 관리형이 주는 이득은 쓰지 않는 기능이었고 매달 나가는 RDS 비용은 실재하는 지출이었기 때문입니다.</p>
<p>동시에 아직 안 한 것도 적어 둡니다. 로컬 DB의 상시 백업 잡을 아직 만들지 않았습니다. 최종 스냅샷과 이전 작업 때 뜬 덤프 파일이 남아 있어 당장의 복구본은 있지만 그것은 이전 시점에서 멈춘 사진이고 어제 쓴 글은 지켜주지 않습니다. 이 글을 쓰는 시점에서 가장 급한 숙제가 그것이라고 봅니다. RDS 비용을 걷어내는 순간 백업은 관리형이 대신 해주던 일에서 제 일로 넘어오는데 그 인수인계를 아직 안 끝낸 상태입니다.<br />
<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2026/09/04-cards-1.png?w=1200&#038;ssl=1" alt="RDS 비용 통합 후 남은 숙제를 정리한 체크리스트 이미지" /><br />
비슷한 계열로 요금과 무료 한도를 직접 재본 글이 셋 있습니다. 리뷰 카테고리의 <a href="https://blog.wonizz.com/2026/09/15/elevenlabs-free-limit/">일레븐랩스 무료 10분과 제한 5가지</a>는 무료 구간의 상한이 어디서 끊기는지를 재본 글이고 <a href="https://blog.wonizz.com/2026/09/05/perplexity-free-limit/">퍼플렉시티 무료 한도와 Pro 차이 5가지</a>는 유료 전환 전에 무엇을 확인해야 하는지를 정리한 글입니다. 단가 구조를 등급별로 쪼갠 <a href="https://blog.wonizz.com/2026/09/11/gpt-image-2-5-pricing-quality/">GPT Image 2.5 요금과 화질 5단계</a>도 같은 축입니다. 쓰는 돈의 정체를 먼저 재고 나서 줄이는 순서라는 점에서 이 글과 이어집니다.</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2026/09/24/rds-cost-reduction/">[DevOps] RDS 비용 줄이기, 통합 4단계</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/24/rds-cost-reduction/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3699</post-id>	</item>
		<item>
		<title>[DevOps] System Design assignment</title>
		<link>https://blog.wonizz.com/2022/08/08/devops-system-design-assignment/</link>
					<comments>https://blog.wonizz.com/2022/08/08/devops-system-design-assignment/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 08 Aug 2022 11:10:14 +0000</pubDate>
				<category><![CDATA[AWS]]></category>
		<category><![CDATA[kubernetes]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=1955</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>Hello, I&#8217;m WONIZZ, the developer of organizing things. In this session, we are going to organize the contents related to the architecture required by many companies. This is a summary of arhitting for url shortner, which usually requires a lot. I wrote the contents that I actually did the assignment myself, and I can learn&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/08/08/devops-system-design-assignment/">[DevOps] System Design assignment</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>
Hello, I&#8217;m WONIZZ, the developer of organizing things. In this session, we are going to organize the contents related to the architecture required by many companies.
This is a summary of arhitting for url shortner, which usually requires a lot.

I wrote the contents that I actually did the assignment myself, and I can learn many things while doing the assignment, so I post it to record it on my blog.

<h2>1. Traffic and System Capacity</h2>

<h3>Traffic</h3>

<ul>
<li>Assuming <em>200:1 read/write</em> ratio</li>
<li>Number of unique shortened links generated per month = 100 million</li>
<li>Number of unique shortened links generated per seconds = 100 million /(30 days * 24 hours * 3600 seconds ) ~ <strong>40 URLs/second</strong></li>
<li>With 200:1 read/write ratio, number of redirections = 40 URLs/s * 200 = <strong>8000 URLs/s</strong></li>
</ul>

<h3>Storage</h3>

Assuming lifetime of service to be 50 years and with 100 million shortened links creation per month

<ul>
<li>total number of data points/objects in system will be = 100 million/month * 50 (years) * 12 (months) = <strong>60 billion</strong></li>
</ul>

Assuming size of each data object (<em>Short url, long url, created date</em> etc.) to be 500 bytes long

<ul>
<li>total require storage = 60 billion * 500 bytes =<strong>30TB</strong></li>
</ul>

<h3>Memory</h3>

Following Pareto Principle, better known as the 80:20 rule for caching. (80% requests are for 20% data)

Since we get 8000 read/redirection requests per second, we will be getting 700 million requests per day:

<ul>
<li>8000/s * 86400 seconds =<strong>~700 million</strong></li>
</ul>

To cache 20% of these requests, we will need ~70GB of memory.

<ul>
<li>0.2 * 700 million * 500 bytes = <strong>~70GB</strong></li>
</ul>

<h3>Estimates</h3>

<table>
<thead>
<tr>
  <th>Category</th>
  <th>Estimation</th>
</tr>
</thead>
<tbody>
<tr>
  <td>Shortened URLs generated</td>
  <td>40/s</td>
</tr>
<tr>
  <td>Shortened URLs generated in 50 years</td>
  <td>60 billion</td>
</tr>
<tr>
  <td>Total URL requests/redirections</td>
  <td>8000/s</td>
</tr>
<tr>
  <td>Storage for 100 years</td>
  <td>30TB</td>
</tr>
<tr>
  <td>Cache memory</td>
  <td>70GB</td>
</tr>
</tbody>
</table>

<h2> </h2>

<h2>2. Pseudo Code</h2>

<h3>Java cod for generating 7 characters long tiny url with a counter</h3>

<strong>base 62</strong> are [0–9][a-z][A-Z]

<pre><code class="language-text line-numbers">URL with length 5, will give 62⁵ = ~916 Million URLs
URL with length 6, will give 62⁶ = ~56 Billion URLs
URL with length 7, will give 62⁷ = ~3500 Billion URLs
</code></pre>

Since we required to produce <strong>120 billion</strong> URLs, with <strong>7 characters</strong> in base62 we will get ~<strong>3500 Billion URLs</strong>. Hence each of tiny url generated will have 7 characters

<pre><code class="language-java line-numbers">public class Codec {
Long counter = 1L;
Map<Long, String> indexToUrl = new HashMap<Long, String>();
Map<String, Long> urlToIndex = new HashMap<String, Long>();
String base62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

  // Encodes a URL to a shortened URL.
  public String encode(String longUrl) {
      if (urlToIndex.containsKey(longUrl)) {
          return "http://tinyurl.com/"+base62Encode(urlToIndex.get(longUrl));
      }
      else {
          indexToUrl.put(counter, longUrl);
          urlToIndex.put(longUrl, counter);
          counter++;
          return "http://tinyurl.com/"+base62Encode(urlToIndex.get(longUrl));
      }
  }

  // Decodes a shortened URL to its original URL.
  public String decode(String shortUrl) {
      String base62Encoded = shortUrl.substring(shortUrl.lastIndexOf("/") + 1);
      long decode = 0;
      for(int i = 0; i < base62Encoded.length(); i++) {
          decode = decode * 62 + base62.indexOf("" + base62Encoded.charAt(i));
      }
      return indexToUrl.get(decode);
  }

  private String base62Encode(long value) {
      StringBuilder sb = new StringBuilder();
      while (value != 0) {
          sb.append(base62.charAt((int)(value % 62)));
          value /= 62;
      }
      while (sb.length() < 6) {
          sb.append(0);
      }
      return sb.reverse().toString();
  }
}
</code></pre>

start with a counter (A Large number <strong>100000000000</strong> in base 10 which <strong>1L9zO9O</strong> in base 62) and increment counter every-time we get request for new short url

<h2>3. Database Schema</h2>

We can use a relational database as our backend store but since we don’t have joins between objects and we require huge storage size (<strong>60TB</strong>) along with high writes (<strong>40 URL’s per seconds</strong>) and read (<strong>8000/s</strong>) speed, a NoSQL store (MongoDB, Cassandra etc.) will be better choice.

<strong>Data Related to user</strong>

<table>
<thead>
<tr>
  <th>Name</th>
  <th>Type</th>
  <th>Desc</th>
</tr>
</thead>
<tbody>
<tr>
  <td>User ID</td>
  <td>Int</td>
  <td>A unique user id or API key to make user globally distinguishable</td>
</tr>
<tr>
  <td>Name</td>
  <td>Varchar</td>
  <td>The name of the user</td>
</tr>
<tr>
  <td>Email</td>
  <td>Varchar</td>
  <td>The email id of the user</td>
</tr>
<tr>
  <td>Creation Date</td>
  <td>Datetime</td>
  <td>The date on which the user was registered</td>
</tr>
</tbody>
</table>

<strong>Data Related to ShortLink</strong>

<table>
<thead>
<tr>
  <th>Name</th>
  <th>Type</th>
  <th>Desc</th>
</tr>
</thead>
<tbody>
<tr>
  <td>Short URL</td>
  <td>Varchar</td>
  <td>7 character long unique short URL</td>
</tr>
<tr>
  <td>Original URL</td>
  <td>Varchar</td>
  <td>The original long URL</td>
</tr>
<tr>
  <td>User ID</td>
  <td>Int</td>
  <td>The unique user id or API key of the user who created the short URL</td>
</tr>
</tbody>
</table>

We can use a relational database as our backend store but since we don’t have joins between objects and we require huge storage size (60TB) along with high writes (40 URL’s per seconds) and read (8000/s) speed, a NoSQL store (AWS DynamoDB, Cassandra etc.) will be better choice.

<h2>4. Key Generation Service (KGS)</h2>

a standalone <strong>Key Generation Service (KGS)</strong> that generates random seven-letter strings beforehand and stores them in a databas
Whenever we want to shorten a URL, we will take one of the already-generated keys and use it. This approach will make things quite simple and fast.

<h3>concurrency problem solution</h3>

As soon as KGS gives keys to one of the servers, it can move them to the used keys table. KGS can always keep some keys in memory to quickly provide them whenever a server needs them.

<h3>SPOF of KGS problem solution</h3>

To solve this, we can have a standby replica of KGS. Whenever the primary server dies, the standby server can take over to generate and provide keys.

<h2>5. Cache</h2>

We can use some off-the-shelf solution like Memchached, Before hitting backend storage, the application servers can quickly check if the cache has the desired URL.
As estimated above, we need 70GB memory to cache 20% of daily traffic. Since a modern-day server can have 256GB memory, we can easily fit all the cache into one machine.

Whenever there is a cache miss, our servers would be hitting a backend database. Whenever this happens, we can update the cache and pass the new entry to all the cache replicas

<h3>cache policy</h3>

Least Recently Used (LRU) can be a reasonable policy for our system. Under this policy, we discard the least recently used URL first.

To further increase the efficiency, we can replicate our caching servers to distribute the load between them.

<h2>6. Load Balancer ( LB )</h2>

<ol>
<li>Between Clients and Application servers</li>
<li>Between Application Servers and database servers ( AWS Managed )</li>
<li>Between Application Servers and Cache servers ( AWS Managed )</li>
</ol>

<h3>Pros of LB</h3>

<ul>
<li>Balancing of Traffic( distributes incoming requests equally among backend servers. )</li>
<li>if a server is dead, LB will take it out of the rotation and will stop sending any traffic to it.</li>
<li>If a server is overloaded or slow, the LB will not stop sending new requests to that server</li>
</ul>

<h2>7. System Design</h2>

<img data-recalc-dims="1" height="909" width="1024" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2022/08/system_design_for_urlshortner.png?resize=1024%2C909&#038;ssl=1" alt="system_design_for_urlshortner" /> system_design_for_urlshortner&#91;/caption&#93;

<h2>8. Conclusion</h2>

While carrying out this assignment, I learned a lot of things to consider in various system design situations.
In particular, I was able to learn about the concerns and the reasons for the design, such as rough traffic requirements, cache layer, and LB selection.
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2019/12/20/kubernetes-helm/">[Kubernetes] Helm 알아보기</a></li><li><a href="https://blog.wonizz.com/2019/08/12/docker-kubernetes/">[Kubernetes] 쿠버네티스란?</a></li><li><a href="https://blog.wonizz.com/2024/07/24/devops-kubernetes-hpa/">[DevOps] Kubernetes HPA 실전 적용</a></li><li><a href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/08/08/devops-system-design-assignment/">[DevOps] System Design assignment</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/08/08/devops-system-design-assignment/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1955</post-id>	</item>
		<item>
		<title>[DevOps] python boto3 s3 upload 작성</title>
		<link>https://blog.wonizz.com/2022/02/17/devops-python-boto3-s3-upload-script/</link>
					<comments>https://blog.wonizz.com/2022/02/17/devops-python-boto3-s3-upload-script/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Thu, 17 Feb 2022 01:13:23 +0000</pubDate>
				<category><![CDATA[AWS]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=1874</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>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 간단한 python script에 대해서 소개를 하려고 합니다. 파이썬은 필자가 관심도 많고 즐겨서 사용하는 언어입니다. 그러다보니 손쉽게 활용해서 무엇인가를 만들때 자주 사용하고 있습니다. next.js를 빌드하고나서 나오는 결과물(build asset)에 대해서 s3에 upload를 하고 그것을 CDN(ex. cloudfront)과 같은 서비스를 연결하여 서빙을 하는 구조로 만들었습니다. 1. 빌드 배포 구성 필자가 사전에 구성하는 프로임워크는 Next.js로&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/02/17/devops-python-boto3-s3-upload-script/">[DevOps] python boto3 s3 upload 작성</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>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 간단한 python script에 대해서 소개를 하려고 합니다. 파이썬은 필자가 관심도 많고 즐겨서 사용하는 언어입니다. 그러다보니 손쉽게 활용해서 무엇인가를 만들때 자주 사용하고 있습니다.</p>
<p>next.js를 빌드하고나서 나오는 결과물(build asset)에 대해서 s3에 upload를 하고 그것을 CDN(ex. cloudfront)과 같은 서비스를 연결하여 서빙을 하는 구조로 만들었습니다.</p>
<h2>1. 빌드 배포 구성</h2>
<p>필자가 사전에 구성하는 프로임워크는 <strong>Next.js</strong>로 기존에 직접 구성을 해보거나, 개발을 해본적은 없었습니다. 하지만 React.js를 이용해서 개발을 진행해봤었고, 소스상으로는 큰 차이는 보이지가 않았었습니다.</p>
<p>필자는 S3 정적 웹 호스팅을 통해서 웹을 작성한 적이 있었습니다.</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/2020/04/13/reactjs-s3-web-hosting/">[Reactjs] S3 웹호스팅 이용하기</a></li>
</ul>
<p>필자가 현재 고민하는 구성에 대해서 또다시 고민을 하고 있다니.. 위의 포스팅을 보고나서, 아차! 저런질문을 했었고 여저런 결론을 내렸구나 싶었습니다.</p>
<ul>
<li>npm start(Dev server)로 구성할지</li>
<li>S3 web hosting을 사용할지</li>
<li>nginx로 web serving을 할지</li>
</ul>
<p>위의 선택지가 있었고, 이번에는 간단한 웹페이지를 구성하는 형식이라 <strong>npm start</strong>로 구성을 하기로했습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2022/02/next_js1.png?w=1200&#038;ssl=1" alt="DevOps python boto3 s3 upload 작성" /></p>
<p>위와 같이 구성을 할생각이고, 필자 같은 경우는 kubernetes를 직접 클러스터링으로 구성하였고, 트래픽의 흐름은 다음과 같습니다.</p>
<ul>
<li>Route 53(DNS Resolving)</li>
<li>Akamai CDN edge -> LB(Origin)</li>
<li>k8s : Ingress Layer -> Application SVC -> Application POD</li>
<li>build asset(css, js, images) : Cloudfront -> S3 reference</li>
</ul>
<p>간단한 웹페이지(서비스 티저용)이지만, S3 웹호스팅으로 구성을 할까 하다가 dev server 구성으로 한번 해보고 어떤 부분이 구성상에 더 좋은 지 경험을 해보고 싶었습니다.</p>
<p>오늘 소개하고자 하는 부분은 위의 영역중에서도 <strong>build asset</strong>을 올려둘 S3 upload와 관련된 내용이고, 이부분을 어떤식으로 구성을 했는지에 대해서 정리를 하려고 합니다.</p>
<h2>2. s3 upload script 작성</h2>
<p>application에 대한 dockerfile 작성 시, next.js는 build를 수행하고 나면 특정 폴더에 asset들이 export됩니다.<br />
next build를 수행하게 되면 결과물들이 <strong>.next</strong>폴더에 생성되게 됩니다.</p>
<pre><code class="language-bash line-numbers">.next/static/chunks/pages
.next/static/media
.next/static/css
</code></pre>
<p>필자는 이중에서도 위와 같이 <strong>.next/static</strong>영역에 출력이 되는 부분을 S3로 업로드를 하고 싶었습니다. 그래서 python을 활용하여 s3 upload를 할 수 있는 스크립트를 작성하기로 했습니다.</p>
<pre><code class="language-python line-numbers">import boto3
from botocore.client import Config
import os
import sys

access_key = 'xxxxxxxxxxxxxx'
secret_key = 'xxxxxxxxxxxxxx'
s3_host = 'https://test-dev.com'
source = '.next/static'
target = '/assets/_next/static'
rootfolder="teaser"
bucket = 'test-dev'

config = Config(signature_version='s3',
        s3={'addressing_style': 'path'})

#connect to S3
s3 = boto3.client('s3',
        aws_access_key_id = access_key,
        aws_secret_access_key = secret_key,
        endpoint_url = s3_host,
        config=config)
</code></pre>
<p>위의 코드는 S3에 연결하는 내용입니다.</p>
<p>필자는 <strong>boto3</strong>패키지를 이용해서 S3에 간단하게 연결을 하기로했고, 여기서 가장 중요한것은 S3로 접근하기 위한 Access key, Secret key 입니다. 이부분은 AWS console상에서 확인 할 수 있습니다.</p>
<pre><code class="language-python line-numbers">def s3upload(appName):
    uploadFileNames = []
    for root, dirs, files in os.walk(appName + "/" + source, topdown=False):
       for name in files:
          fname=os.path.join(root, name)
          print fname
          uploadFileNames.append(fname)

    # start uploading
    for filename in uploadFileNames:
        mimetype = mimetypes.guess_type(filename)
        sourcepath = filename
        destpath = filename
        targetpath = sourcepath.replace(source, target).replace("./", rootfolder)
        print 'Uploading %s to VERDA VOS bucket %s, mimeType : %s' % \
              (sourcepath, bucket, mimetype[0])
        s3.upload_file(sourcepath, bucket, targetpath, ExtraArgs={'ACL': 'public-read', 'ContentType': mimetype[0]})
</code></pre>
<p>위의 코드는 S3로 실제로 업로드를 하는 내용의 코드 입니다. S3는 object storage이기 때문에 요소 한개한개를 개별로 올려줘야 합니다. 위의 코드는 굉장히 심플합니다.</p>
<pre><code class="language-python line-numbers">for root, dirs, files in os.walk(appName + "/" + source, topdown=False):
</code></pre>
<p>특정 경로 ( <strong>./.next/static</strong>)과 같은 경로에 빌드의 산출물이 출력이 됩니다. 그곳에 있는 모든 파일들을 하나씩 순차적으로 순회하면서 특정 변수 <strong>uploadFileNames</strong>에다가 해당 내용들을 담습니다.</p>
<pre><code class="language-python line-numbers">for filename in uploadFileNames:
</code></pre>
<p>그리고 해당 변수에서 하나씩 path들을 꺼내서 실제 S3로 업로드를 하는 method를 호출합니다.</p>
<pre><code class="language-python line-numbers">s3.upload_file(sourcepath, bucket, targetpath, ExtraArgs={'ACL': 'public-read', 'ContentType': mimetype[0]})
</code></pre>
<h2>3. CDN 연결</h2>
<p>S3에 정상적으로 업로드가 됐으면, 이제 이러한 파일들을 빠르게 엣지를 연결하여 서빙 해줄 수 있도록 CDN을 연결합니다.</p>
<p>사내의 private cloud에서는 손쉽게 S3와 CDN을 붙일 수 있는 서비스를 제공해주고 있습니다. 따라서 이 섹션에서는 별도로 정리할 내용이 없으나, S3 앞단에 CDN을 연결한다는 것을 알아 둘 필요가 있습니다.</p>
<ul>
<li>build asset(css, js, images) : Cloudfront -> S3 reference</li>
</ul>
<p>이제 어플리케이션에서서 요청하는 resource(css, js 등)은 cloudfront의 URL을 참조하게 되고 클라이언트 입장에서는 빠르게 엣지에서 리소스들을 받기 때문에 어플리케이션 퍼포먼스가 좋아지고 자연스럽게 유저에게도 만족도를 줄 수 있습니다.</p>
<h2>4. application path 수정</h2>
<p>next.js 에서는 asset prefix라는 것을 제공해주고 있습니다. 따라서 위에 올린 S3 앞단의 CDN 도메인으로 호출을 할  수 있도록 적절하게 어플리케이션에서는 path를 수정해줘야 합니다.</p>
<p><a class="wp-editor-md-post-content-link" href="https://nextjs.org/docs/api-reference/next.config.js/cdn-support-with-asset-prefix" target="_blank" rel="noopener">CDN Support with Asset Prefix</a></p>
<p>위의 내용에 따라 runtime시에 argument를 전달하게 되고 어플리케이션에서는 전달받은 argument를 기반으로 셋팅하게 됩니다.</p>
<pre><code class="language-javascript line-numbers">const path = require('path')
const isProduction = process.env.NODE_ENV === 'production'

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  publicRuntimeConfig: {
    DOSI_CDN: process.env.DOSI_CDN
  },
  sassOptions: {
    includePaths: [path.join(__dirname, 'styles')],
    prependData: `@import "src/styles/mixins";`
  },
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/,
      use: ['@svgr/webpack']
    })

    /**
     * next.js doesn't know alias, so extends webpack config
     * {@link https://webpack.js.org/configuration/resolve}
     */
    config.resolve.alias['~'] = path.join(__dirname, 'src')

    return config
  },
  assetPrefix: isProduction ? `${process.env.S3_CDN}/teaser/assets` : ''
}

module.exports = nextConfig
</code></pre>
<p>필자는 S3에 업로드 할 당시 <strong>teaser/assets/_next/static</strong>라는 경로로 올렸고 앞의 S3_CDN 도메인을 붙여서 엣지로부터 리소스를 가져오도록 구성했습니다.</p>
<pre><code class="language-javascript line-numbers"> assetPrefix: isProduction ? `${process.env.S3_CDN}/teaser/assets` : ''
</code></pre>
<p>위의 부분에서 어플리케이션 runtime시에 할당받은 변수를 넣어줌으로써 CDN url로 path를 수정하게 됩니다.</p>
<h2>5. 마치며..</h2>
<p>S3 업로드와 관련된 스크립트 작성과 더불어 next.js 빌드는 어떤식으로 되는지 그 산출물이 어떤형태로 떨어지는지에 대해서 정리를 해보았습니다. DevOps 업무를 하면서 기존에는 주로 Back-end의 어플리케이션에 대해서만 CI / CD를 구성해줬었는데, Front-end에 대해서도 구성을 하면서 많은 부분을 배울 수 있는 기회였던 것 같습니다.</p>
<h2>6. 참조</h2>
<p><a class="wp-editor-md-post-content-link" href="https://blog.actin.kr/devlog/2020/01/21/boto3-copy-folder/" target="_blank" rel="noopener">Python boto3 복사, 업로드, 동기화 유용한 기능</a></p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/02/17/devops-python-boto3-s3-upload-script/">[DevOps] python boto3 s3 upload 작성</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/02/17/devops-python-boto3-s3-upload-script/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1874</post-id>	</item>
		<item>
		<title>[DevOps] logstash S3 로그 수집</title>
		<link>https://blog.wonizz.com/2020/09/28/logsatsh-s3-access/</link>
					<comments>https://blog.wonizz.com/2020/09/28/logsatsh-s3-access/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 28 Sep 2020 01:05:07 +0000</pubDate>
				<category><![CDATA[AWS]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1457</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>안녕하세요? 정리하는 개발자 워니즈입니다. 오랜만에 글을 작성하려니, 어떤 내용부터 어떻게 쓸지 고민을 하다가 최근들어서 하고있는 내용을 정리하기로 했습니다. 오늘은 Logstash라는 주제로 정리를 해볼까 합니다. 로그스태시는 원천 데이터 파일로부터 특정 처리를 수행하고 그 결과에 대해서 적재해주는 구조입니다. 이전에 필자가 아래의 내용으로 포스팅을 한적이 있습니다. 로그를 수집하고 해당 내용을 분석하는 대시보드를 작성하는 내용으로 전체적으로 ELK 스택이 어떻게&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/09/28/logsatsh-s3-access/">[DevOps] logstash S3 로그 수집</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>안녕하세요? 정리하는 개발자 워니즈입니다. 오랜만에 글을 작성하려니, 어떤 내용부터 어떻게 쓸지 고민을 하다가 최근들어서 하고있는 내용을 정리하기로 했습니다.</p>
<p>오늘은 <strong>Logstash</strong>라는 주제로 정리를 해볼까 합니다. 로그스태시는 원천 데이터 파일로부터 특정 처리를 수행하고 그 결과에 대해서 적재해주는 구조입니다.</p>
<p>이전에 필자가 아래의 내용으로 포스팅을 한적이 있습니다. 로그를 수집하고 해당 내용을 분석하는 대시보드를 작성하는 내용으로 전체적으로 ELK 스택이 어떻게 동작하는지를 보았습니다.</p>
<p><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2019/10/07/elk-log-anlysis/">ELK를 활용한 로그 분석</a></p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/09/%EB%A1%9C%EA%B7%B8%EC%8A%A4%ED%83%9C%EC%8B%9C_1.png?w=1200&#038;ssl=1" alt="DevOps logstash S3 로그 수집 설명 이미지 1" /></p>
<p>이번에는 Logstash에 좀더 집중해서 보려고 합니다. 로그스태시를 사용하기 위해서는 기존의 docker-elk compose 파일을 통해서 올리도록 하겠습니다.</p>
<h2>1. Logstash 설치 방법</h2>
<p>기본적으로 설명드리는 내용은 docker daemon이 설치된 VM에서 하는 내용입니다. elk docker-compose 내용중에 logstash만 남기고, 내용을 모두 삭제하여 다음과 같이 만들어줄 예정입니다 .</p>
<h3>1-1. 폴더 tree</h3>
<pre><code class="line-numbers">├── docker-compose.yml
├── docker-stack.yml
├── extensions
│   ├── apm-server
│   │   ├── apm-server-compose.yml
│   │   ├── config
│   │   │   └── apm-server.yml
│   │   ├── Dockerfile
│   │   └── README.md
│   ├── curator
│   │   ├── config
│   │   │   ├── curator.yml
│   │   │   └── delete_log_files_curator.yml
│   │   ├── curator-compose.yml
│   │   ├── Dockerfile
│   │   ├── entrypoint.sh
│   │   └── README.md
│   ├── logspout
│   │   ├── build.sh
│   │   ├── Dockerfile
│   │   ├── logspout-compose.yml
│   │   ├── modules.go
│   │   └── README.md
│   └── README.md
├── LICENSE
├── logstash
│   ├── config
│   │   └── logstash.yml
│   ├── data
│   │   └── plugins
│   │       └── inputs
│   │           └── s3
│   │               ├── sincedb_1d7494114df033e1769f7a13894328e3
│   │               └── sincedb_c134b2a92a773825e5ce19bfb9ee390a
│   ├── Dockerfile
│   └── pipeline
│       └── logstash.conf
├── README.md
└── ts
    └── es.log
</code></pre>
<p>기본적으로 docker-elk 스택을 다운받아서 불필요한 내용은 지우는 방식으로 진행했습니다.</p>
<p><a class="wp-editor-md-post-content-link" href="https://github.com/deviantony/docker-elk" target="_blank" rel="noopener">Docker ELK 공식 깃헙</a></p>
<p>위에 깃헙 폴더를 그대로 다운받으면, elk 내용이 안에 모두 있는데 불필요한 파일들은 삭제 했습니다. 또한, docker-compose.yaml 파일중에서도 elasticsearch와 kibana에 대한 내용은 모두 삭제를 했습니다.</p>
<p>그리고 실제로 건드리게 되는 부분은 <strong>logstash > pipeline > logstash.conf</strong> 파일 입니다. 여기서 필요한 configure작업을 진행하고, 해당 내용을 컨테이너로 올린 logstash에서 사용하도록 하는 내용입니다.</p>
<h2>2. Logstash conf파일 정리</h2>
<p>로그스태시는 기본적으로 inpu, filter, output으로 이루어져있습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/09/%EB%A1%9C%EA%B7%B8%EC%8A%A4%ED%83%9C%EC%8B%9C_2.png?w=1200&#038;ssl=1" alt="DevOps logstash S3 로그 수집 설명 이미지 2" /></p>
<p>좌측의 원천 데이터로부터 내용을 Logstash가 Pulling을 통해서 수집하고 Filter라는 영역에서 연산처리를 진행한다음에 Output으로 데이터를 전송하게 됩니다.</p>
<p>지금 필자가 만들어 가려는것은 다음과 같은 내용입니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/09/%EB%A1%9C%EA%B7%B8%EC%8A%A4%ED%83%9C%EC%8B%9C_3.png?w=1200&#038;ssl=1" alt="DevOps logstash S3 로그 수집 설명 이미지 3" /></p>
<p>AWS LB의 로그 수집을 켜두게 되면, S3에 해당 내용이 gz으로 압축되어 기록이 되게 됩니다. 그러면, 해당 S3 파일을 읽어서 Logstash 에서 연산처리를 진행하고 ElasticSearch로 수집을 하게 됩니다. 그렇게 한 후, Kibana를 통해서 Visualize를 수행하게 됩니다.</p>
<h3>2-1. logsatsh.conf 내용</h3>
<ul>
<li>Input</li>
</ul>
<pre><code class="line-numbers">input {
   s3 {
       access_key_id => "{개별 key id}"
       secret_access_key => "{개별 access key}"
       region => "ap-northeast-2"
       bucket => "p6-prd-ap-alb-accesslog"
       type => "s3_ap_access"

   }
   s3 {
       access_key_id => "{개별 key id}"
       secret_access_key => "{개별 access key}"
       region => "eu-central-1"
       bucket => "p6-prd-eu-alb-accesslog"
       type => "s3_eu_access"

   }
}
</code></pre>
<p>input은 크게 2개로 구성이 되어서, AP지역과 EU지역으로 수집을 하게 됩니다.</p>
<ul>
<li>filter</li>
</ul>
<pre><code class="line-numbers">filter {
        grok {
                match => [ "message", '%{NOTSPACE} %{TIMESTAMP_ISO8601:inner_timestamp} %{NOTSPACE:loadbalancer} %{IP}:%{NUMBER} (%{IP}:%{NUMBER}) %{NUMBER} %{NUMBER} %{NUMBER} %{NUMBER:elb_status_code:int} %{NUMBER:backend_status_code:int} %{NUMBER:received_bytes:int} %{NUMBER:se
nt_bytes:int} \"%{WORD:method} %{URIPROTO:uri_proto}://(?:%{USER:user}(?::[^@]*)?@)?(?:%{URIHOST:uri_domain})?%{URIPATH:url_path}%{URIPARAM:url_params}? HTTP/%{NOTSPACE}\" \"%{DATA:agent}\"' ]        }
         #url parameter 변환
         mutate { gsub =>  ["url_params","\?","" ] }
         mutate { split => {"url_params" => "&" } }
         ruby {
                        code => "
                                #변수 선언
                                pathArr = event.get('url_path')
                                paramArr = event.get('url_params')

                                #siteCode 처리
                                parameter = []
                                if pathArr.length > 1
                                        event.set('site_code', pathArr.split('/')[1])
                                end

                                #parameter 처리
                                if !paramArr.nil? and paramArr.length > 1
                                        paramArr.each do |item|
                                                parameter.push(item.split('=')[0])
                                        end
                                end
                                event.set('parameter', parameter)
                        "
        }
        date { match => [ "timestamp", "dd/MMM/yyyy:HH:mm:ss Z" ]}
        mutate { remove_field => [ "message","url_params"]}
}
</code></pre>
<p>사실 필자가 이번 포스팅에 가장 강조하는 부분은 filter 입니다.  이 내용은 아래에서 하나씩 풀어서 정리를 하도록 하겠습니다. 간단하게 말하면, S3로부터 온 원데이터(message)를 ruby 스크립트를 통해서 원하는 데이터를 자르는 내용입니다.</p>
<ul>
<li>output</li>
</ul>
<pre><code class="line-numbers">output {
        stdout {
                codec => rubydebug
        }

        if "p6_s3_ap_access" in [type] {
                elasticsearch {
                        hosts => ["{elasticsearch IP}"]
                        index => "p6_s3_ap_access-%{+YYYYMMdd}"
                }
        } else if "p6_s3_eu_access" in [type] {
                elasticsearch {
                        hosts => ["{elastciserach IP}"]
                        index => "p6_s3_eu_access-%{+YYYYMMdd}"
                }
        }
}
</code></pre>
<p>output 같은 경우는 elasticsearch로 넣을 수 있도록 셋팅을 합니다.</p>
<h2>3. logstash.conf 분석</h2>
<pre><code class="line-numbers"> grok {
                match => [ "message", '%{NOTSPACE} %{TIMESTAMP_ISO8601:inner_timestamp} %{NOTSPACE:loadbalancer} %{IP}:%{NUMBER} (%{IP}:%{NUMBER}) %{NUMBER} %{NUMBER} %{NUMBER} %{NUMBER:elb_status_code:int} %{NUMBER:backend_status_code:int} %{NUMBER:received_bytes:int} %{NUMBER:se
nt_bytes:int} \"%{WORD:method} %{URIPROTO:uri_proto}://(?:%{USER:user}(?::[^@]*)?@)?(?:%{URIHOST:uri_domain})?%{URIPATH:url_path}%{URIPARAM:url_params}? HTTP/%{NOTSPACE}\" \"%{DATA:agent}\"' ]        }
</code></pre>
<p>grok 같은 경우는 disect plugin입니다. 들어온 포맷을 하나의 인자로 인식하고 지정된 format에 맞게 하나씩 요소를 잘라줍니다.</p>
<p>실제로 들어오는 문자열을 확인해보겠습니다.</p>
<pre><code class="line-numbers">https 2020-09-03T23:59:57.034675Z app/my-alb/0000000000000000 xx.xxx.xx.xxx:48579 xx.x.xxx.xx:30301 0.000 0.012 0.000 200 200 3995 290627 "GET https://www.samsung.com:443/us/galaxybooks/?cid=smp-mktg-stc-mob-us-facebookinstagram-na-08032020-123197-979858-278640164-135765666&dclid=CNr_wOSYzusCFcq1fgodukAChQ HTTP/1.1" "Mozilla/5.0 (Linux; Android 8.1.0; LM-X212(G) Build/OPM1.171019.026; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/81.0.4044.138 Mobile Safari/537.36 
</code></pre>
<p>위의 내용이 원본 데이터인 message로 인식이 되게 되고, 하나씩 disect를 진행합니다.</p>
<p>아래의 내용에 맞춰서 grok pattern이 정의 됩니다.</p>
<pre><code class="line-numbers">%{NOTSPACE} 
%{TIMESTAMP_ISO8601:inner_timestamp} 
%{NOTSPACE:loadbalancer} 
%{IP}:%{NUMBER} 
(%{IP}:%{NUMBER}) 
%{NUMBER} 
%{NUMBER} 
%{NUMBER} 
%{NUMBER:elb_status_code:int} 
%{NUMBER:backend_status_code:int} 
%{NUMBER:received_bytes:int} 
%{NUMBER:sent_bytes:int} 
\"%{WORD:method} %{URIPROTO:uri_proto}://(?:%{USER:user}(?::[^@]*)?@)?(?:%{URIHOST:uri_domain})?%{URIPATH:url_path}%{URIPARAM:url_params}? HTTP/%{NOTSPACE}\"
\"%{DATA:agent}\"
</code></pre>
<pre><code class="line-numbers">https 
2020-09-03T23:59:57.034675Z 
app/my-alb/0000000000000000 
xx.xxx.xx.xxx:48579 
xx.x.xxx.xx:30301 
0.000 
0.012 
0.000 
200 
200 
3995 
290627 
"GET https://www.samsung.com:443/us/galaxybooks/?cid=smp-mktg-stc-mob-us-facebookinstagram-na-08032020-123197-979858-278640164-135765666&dclid=CNr_wOSYzusCFcq1fgodukAChQ HTTP/1.1" 
"Mozilla/5.0 (Linux; Android 8.1.0; LM-X212(G) Build/OPM1.171019.026; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/81.0.4044.138 Mobile Safari/537.36"
</code></pre>
<p><a class="wp-editor-md-post-content-link" href="https://github.com/logstash-plugins/logstash-patterns-core/blob/master/patterns/grok-patterns" target="_blank" rel="noopener">grok-pattern 정의</a></p>
<p>위의 깃헙에 들어가보면, grok 요소의 pattern을 정의를 해두었습니다. 하나씩 맞춰서 가져와서 사용하면 됩니다. 실제 들어오는 내용과 grok pattern을 맞춰서 보기 편하게 위와 같이 두었습니다.</p>
<ul>
<li>request url 처리</li>
</ul>
<pre><code class="line-numbers">"%{WORD:method} %{URIPROTO:uri_proto}://(?:%{USER:user}(?::[^@]*)?@)?(?:%{URIHOST:uri_domain})?%{URIPATH:url_path}%{URIPARAM:url_params}? HTTP/%{NOTSPACE}\"
</code></pre>
<p>위의 부분이 중요한데, request url 같은 경우는 <strong>&#8221; &#8220;</strong> 와 같이 들어오기 때문에 이스케이프 처리를 좌우측으로 해주었습니다. 그리고 다시 url내부에서도 domain + path + params로 disect 하도록 정의를 해두었습니다.</p>
<ul>
<li>parameter 처리</li>
</ul>
<pre><code class="line-numbers">mutate { gsub =>  ["url_params","\?","" ] }
mutate { split => {"url_params" => "&" } }
</code></pre>
<p>parameter에 대한 처리를 위해서는 위와 같이 처리를 진행했습니다. <strong>?</strong> 이후에 오는 문자열은 parameter로 인식하게 해두었고, 여러개가 이어서 <strong>&amp;</strong>문자열이  오는부분에 대해서 split을 사용하여 잘라두었습니다.</p>
<pre><code class="line-numbers"> ruby {
                        code => "
                                #변수 선언
                                pathArr = event.get('url_path')
                                paramArr = event.get('url_params')

                                #siteCode 처리
                                parameter = []
                                if pathArr.length > 1
                                        event.set('site_code', pathArr.split('/')[1])
                                end

                                #parameter 처리
                                if !paramArr.nil? and paramArr.length > 1
                                        paramArr.each do |item|
                                                parameter.push(item.split('=')[0])
                                        end
                                end
                                event.set('parameter', parameter)
                        "
        }
</code></pre>
<p>그리고 중요한 내용이 바로 위의 내용입니다. 하고자 하는것은 parameter로 들어온 내용을 key만 elastic에 넣어서 보고 싶은 내용입니다.</p>
<p>url_path를 위에서 받게 되면, <strong>/us/galaxybooks/</strong> 여기까지 받아지게 됩니다. 그리고 해당 내용에서 제일 앞의 내용을 가져와서 site_code로 넣는 내용이 추가 되어있습니다.</p>
<p>url_params를 위에서 받게 되면, array형태로 받아지고, ruby 스크립트를 통해서 array를 하나씩 돌면서, <strong>=</strong> 문자열로 잘라서, key값만 가져오도록 처리를 하고 있습니다.  그리고 최종적으로 parameter로 넣는 내용이 추가 되어있습니다.</p>
<p>그리고 최종적으로 elasticsearch로 넣는 작업이 output에 명시가 되어있습니다.</p>
<h2>4. kibana에서 데이터 확인</h2>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/09/%EB%A1%9C%EA%B7%B8%EC%8A%A4%ED%83%9C%EC%8B%9C_4.png?w=1200&#038;ssl=1" alt="DevOps logstash S3 로그 수집 설명 이미지 4" /></p>
<p>키바나의 discover라는 탭을 통해서 위와 같이 지정해 놓은 index pattern에 따라서 확인이 가능합니다. S3에서의 access log를 계속해서 적재 하고 있는것을 볼 수 있습니다 .</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/09/%EB%A1%9C%EA%B7%B8%EC%8A%A4%ED%83%9C%EC%8B%9C_5.png?w=1200&#038;ssl=1" alt="DevOps logstash S3 로그 수집 설명 이미지 5" /></p>
<p>하나의 데이터를 확인해보면, 위와 같이 위에서 disect 했던 내용이 모두 정상적으로 적재 되어있는 것을 볼 수 있습니다.<br />
parameter같은 경우는 없게 되면 비어있는 값이 노출 됩니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/09/%EB%A1%9C%EA%B7%B8%EC%8A%A4%ED%83%9C%EC%8B%9C_6.png?w=1200&#038;ssl=1" alt="DevOps logstash S3 로그 수집 설명 이미지 6" /></p>
<p>최종적으로 위와 같이 대시보드로 작성을 해볼 수 가 있습니다. 이렇게 하게 되면, 외부 트래픽에 대해서 어떻게 들어오는지를 한눈에 볼 수 있습니다.</p>
<h2>5. 마치며..</h2>
<p>이번 포스팅은 로그스태시의 사용법중 루비스크립트를 통해서 작성하는 방법에 대해서 알아보았습니다. 루비스크립트로 가져온 원본 데이터를 적재 적소에 활용 할 수 있게끔 filter 작업을 진행했습니다. 그리고 elastic에 데이터를 적재하고 kibana로 표현을 해보았습니다.</p>
<p>다음 이시간에는 kibana의 visualize부터 dashboard 작성법에 대해서 정리를 해보도록 하겠습니다.</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/09/28/logsatsh-s3-access/">[DevOps] logstash S3 로그 수집</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/09/28/logsatsh-s3-access/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1457</post-id>	</item>
		<item>
		<title>[토이프로젝트] 3편 : API 구현</title>
		<link>https://blog.wonizz.com/2020/08/31/toy-project-3/</link>
					<comments>https://blog.wonizz.com/2020/08/31/toy-project-3/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 31 Aug 2020 06:09:15 +0000</pubDate>
				<category><![CDATA[React.js]]></category>
		<category><![CDATA[AWS]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1444</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>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 지난 토이프로젝트에서 대한 실기능에 대해서 정리를 하고자 합니다. 주로 DynamoDB에 접근을 해서 데이터를 조작하는 API들에 대해서 소개를 하고자 합니다. AWS에서는 정말 손쉽게 기능구현을 하도록 서비스를 만들어둔거 같습니다 .</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/08/31/toy-project-3/">[토이프로젝트] 3편 : API 구현</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>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 지난 토이프로젝트에서 대한 실기능에 대해서 정리를 하고자 합니다. 주로 DynamoDB에 접근을 해서 데이터를 조작하는 API들에 대해서 소개를 하고자 합니다. AWS에서는 정말 손쉽게 기능구현을 하도록 서비스를 만들어둔거 같습니다 .

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/08/lambda_1.png?w=1200&#038;ssl=1" alt="토이프로젝트 3편 : API 구현 설명 이미지 1" />

크게는 기능적으로 3가지에 대해서 정리를 할예정입니다.

<ul>
<li>도서 / 예약 목록 가져오기</li>
<li>도서 예약 처리</li>
<li>도서 반납 처리</li>
</ul>

사실 기능적으로는 엄청 간단한 기능입니다.하지만, 실질적으로 람다에서 다이나모DB를 어떻게 접근하느지에 대해서 정리를 해보도록 하겠습니다.

<h2>1. cloud9을 통한 Lambda 제어</h2>

람다를 사용하다가 보면, 부딪히게 되는 문제가 있습니다. nodemodule을 압축해서 올려야 하는 문제가 있는데, 로컬에서는 잘 돌아간다고 해도 실제로 모듈을 압축해서 올리면 동작하지 않는 문제들도 있었습니다 .

이런부분을 손쉽게 해결할 수 있는 부분이 바로 AWS에서 제공하는 IDE를 활용하는 것입니다. 실행하게 되면, CloudFormation을 통해서 EC2를 생성하게 됩니다. 별다른 방화벽 오픈도 없이 바로 작업이 가능해집니다 .

<ul>
<li>실행하기</li>
</ul>

<ol>
<li>[AWS] > [Cloud9] 에 접속을 합니다.</li>
<li>[Create environment]를 선택합니다.</li>
<li>Name environment의 Name을 임의로 지정합니다. Description은 아무거나 입력해도 됩니다.</li>
<li>[Create enviroment]를 선택하여 최종 생성합니다.</li>
</ol>

그 외 나머지 설정들은 Default로 셋팅을 하면됩니다 .

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/08/lambda_2.png?w=1200&#038;ssl=1" alt="토이프로젝트 3편 : API 구현 설명 이미지 2" />

사실 여기서부터는 terminal에 접속한 형태대로 작업을 하시면 됩니다.

<ol>
<li>화면 오른쪽 위 메뉴 중 <code>AWS Resources</code>를 선택합니다.</p></li>
<li>Lambda(us-east-1)/<code>Remote Functions</code> 목록의 <code>{임의의 function}</code>를 <code>Import</code>합니다.</p></li>
<li>불러온 람다 함수로 접근하기 위해 터미널(Terminal)을 이용합니다.(

<pre><code class="line-numbers">package.json
</code></pre>

을 생성하고 dynamodb-doc 모듈을 설치합니다.)

<ol>
<li><code>$ cd getbook</code></li>
<li><code>$ npm init -y</code></li>
<li><code>$ npm i dynamodb-doc</code></li>
</ol></li>
<li><code>index.js</code>을 아래 코드와 같이 수정합니다.</p></li>
</ol>

<pre><code class="line-numbers">//모듈 선언.
const doc = require('dynamodb-doc');
const dynamo = new doc.DynamoDB();

exports.handler = (event, context, callback) => {
    const payload = {
        TableName: 'book'
    }
    dynamo.scan(payload, (err, data) => {
                callback(null, {
                    'statusCode': 200,
                    'headers': {'Content-Type': 'application/json; charset=UTF-8', 'access-control-allow-origin': '*'},
                    'body': JSON.stringify(data)
                });
            });
};
</code></pre>

<ol start="5">
<li>작성한 람다 함수를 버전으로 배포합니다.

<ul>
<li>Lambda(us-east-1)/<code>Local Functions</code> 목록의 <code>getbook</code>를 <code>Deploy</code>합니다.</li>
</ul></li>
</ol>

<h2>2. lambda 권한 부여</h2>

람다를 초기에 생성하게 되면, 임의의 역할이 부여 됩니다. 해당 역할 그룹에 접속한 후, Dynamodb에 대한 fullacces권한을 부여합니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/08/lambda_3.png?w=1200&#038;ssl=1" alt="토이프로젝트 3편 : API 구현 설명 이미지 3" />

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/08/lambda_4.png?w=1200&#038;ssl=1" alt="토이프로젝트 3편 : API 구현 설명 이미지 4" />

<h2>3. api gateway 연결</h2>

lambda function 들이 모두 만들어졌기에(위의 작업에서 목록조회, 반납, 대여 기능을 모두 완료 한 뒤) 앞에 gateway를 통해서 연결을 지어주면, 이 관문을 모두 통과해서 작업을 수행하게 됩니다.

<pre><code class="line-numbers">Amazon API Gateway는 고객이 API Gateway에서 사용할 수 있는 REST API보다 최대 71% 저렴한 고성능 RESTful API를 신속하게 구축할 수 있도록 HTTP API를 발표했습니다. HTTP API는 AWS Lambda 함수 또는 HTTP 백엔드로 프록시를 통해 전송하는 API를 구축하는 데 최적화되어 서버리스 워크로드에 적합합니다.
</code></pre>

위의 내용은 2019년 12월 경에 발표된 내용이다. API Gateway를 들어가보면, HTTP API가 신설 되어있습니다. 필자가 구축한 내용처럼 간단하게 http만으로 통신을 하도록 구현해두면, 손쉽게 구축할 수 있는 타입으로 나와있습니다.

실제로 생성하게 된 후, [개발] > [통합] 부분에 들어가면 경로 라우팅이 가능하게 셋팅을 할 수 있습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/08/lambda_5.png?w=1200&#038;ssl=1" alt="토이프로젝트 3편 : API 구현 설명 이미지 5" />

위와 같이 셋팅을 하게 되면, API gateway 도메인을 통해서 들어오는 하위 URI들에 대해서는 뒷단에 Lambda를 연결해서 결과를 return 합니다. 손쉽게 lamda들을 apigateway를 통해서 연결을 지어줬고, 바로 appliication에서 사용할 수 있도록 연결해두었습니다.

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

이번시간에는 API영역을 어떻게 구현하는지 lambda + apigateway + dynamodb에 대해서 정리를 해보았습니다. 상세한 소스 구현단계가 아니라 어떤식의 흐름으로 연결되는지를 정리하다보니 내용이 많이 간소화 되어있습니다. 소스의 정확한 내용은 <a class="wp-editor-md-post-content-link" href="https://github.com/wonizz/lambda-example" target="_blank" rel="noopener">워니즈 깃헙 : 람다 예제</a>에서 확인 할 수 있습니다.
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2020/05/06/reactjs-aws-cloudfront-cdn-apply/">[Reactjs] AWS CloudFront를 통한 CDN 적용</a></li><li><a href="https://blog.wonizz.com/2020/04/06/reactjs-redux-project-props-state/">[Reactjs] 리액트 정리 3편 : state &#038; props</a></li><li><a href="https://blog.wonizz.com/2020/05/19/reactjs-build-and-deploy/">[Reactjs]  AWS Codepipeline을 통한 배포</a></li><li><a href="https://blog.wonizz.com/2020/05/11/reactjs-aws-route53-domain/">[Reactjs] AWS Route53을 통한 도메인 연결</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/08/31/toy-project-3/">[토이프로젝트] 3편 : API 구현</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/08/31/toy-project-3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1444</post-id>	</item>
		<item>
		<title>[토이프로젝트] 1편 : 간단한 게시판 만들기</title>
		<link>https://blog.wonizz.com/2020/07/28/toy-project-1/</link>
					<comments>https://blog.wonizz.com/2020/07/28/toy-project-1/#comments</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Tue, 28 Jul 2020 01:41:56 +0000</pubDate>
				<category><![CDATA[AWS]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1406</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>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 간단한 토이프로젝트 만들어보기라는 주제로 글을 연재해볼까 합니다. 필자가 속한 부서에서 작은 도서관 이라는 개념으로 도서를 대여하고 있는데, 그동안은 모든것을 수기로 작성을 해왔었습니다. 필자도 매번 책을 빌릴 때면, 기록하는 것이 너무나 귀찮았었고, 특히 이력관리가 정확하게 되지 않다보니, 누가 어떤 책을 빌려갔는지가 정확하게 추적이 되지 않았습니다. 그래서 이번에는 간단하게 0원으로 운영하는 서버리스&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/07/28/toy-project-1/">[토이프로젝트] 1편 : 간단한 게시판 만들기</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>작은 도서관</strong> 이라는 개념으로 도서를 대여하고 있는데, 그동안은 모든것을 수기로 작성을 해왔었습니다.</p>
<p>필자도 매번 책을 빌릴 때면, 기록하는 것이 너무나 귀찮았었고, 특히 이력관리가 정확하게 되지 않다보니, 누가 어떤 책을 빌려갔는지가 정확하게 추적이 되지 않았습니다.</p>
<p>그래서 이번에는 <strong>간단하게 0원으로 운영하는 서버리스 어플리케이션</strong> 을 구축하여 작게나마 도움이 되도록 해보았습니다.</p>
<p>지난 글은 아래를 참고 부탁드립니다.</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/2020/07/28/toy-project-1/">토이프로젝트 1편 : 기획 및 아키텍처</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/2020/08/11/toy-project-2/">토이프로젝트 2편 : 로그인 모듈(jwt)</a></li>
</ul>
<h2>1. 아키텍처</h2>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/07/toypjt_1.png?w=1200&#038;ssl=1" alt="서버리스아키텍처" /></p>
<p>정말 심플그자체입니다.</p>
<ul>
<li>S3</li>
<li>API GW + Lambda</li>
<li>Dynamodb</li>
</ul>
<p>크게는 위와 같이 3개의 구획으로 나위어져 있습니다.</p>
<p>S3에서는 front-end 소스로부터 빌드된 static한 파일들이 올라갑니다. (idnex.html + build js ..)</p>
<p>API GW + Lambda 에서능 화면에 출력할 데이터를 가져오고 혹은 데이터를 수정하는 역할을 합니다.</p>
<p>Dynamodb 는 데이터원천이 적제되는 Database 입니다.</p>
<p>위와같은 아키텍처를 서버리스 구성시에 굉장히 많이 사용하긴 합니다.</p>
<h2>2. 기획</h2>
<p>사실 기획이라는게 필요하나 싶을정도로 간단한 어플리케이션을 구축하는 프로젝입니다. 어떻게보면 게시판류의 기능이라고 볼 수 도 있습니다.</p>
<p>전체적인 페이지는</p>
<ul>
<li>로그인</li>
<li>도서 리스트 페이지</li>
<li>나의 도서 예약 페이지</li>
</ul>
<p>로 크게 3가지 페이지로 구성이 되어있고,</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/07/toypjt_2.png?w=1200&#038;ssl=1" alt="도서리스트" /></p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/07/toypjt_3.png?w=1200&#038;ssl=1" alt="토이프로젝트 1편 : 간단한 게시판 만들기 설명 이미지 1" /></p>
<p>요소의 기능은</p>
<ul>
<li>로그인 / 로그아웃 / 회원가입 기능</li>
<li>도서 예약 기능</li>
<li>도서 반납 기능</li>
<li>페이징 기능</li>
</ul>
<p>으로 구분 되어있습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/07/toypjt_4.png?w=1200&#038;ssl=1" alt="대여하기" /></p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/07/toypjt_5.png?w=1200&#038;ssl=1" alt="토이프로젝트 1편 : 간단한 게시판 만들기 설명 이미지 2" /></p>
<p>로그인 기능은 어디서나 볼 수 있으므로 첨부 하지 않았습니다.</p>
<h2>3. 설계</h2>
<p>설계는 크게 아래와 같이 2부분에 대해서 진행을 했습니다.</p>
<ul>
<li>DynamoDB 테이블 설계</li>
<li>API 스펙 설계</li>
</ul>
<p>위와 같이 생각을 하고 간단하게 다음과 같이 진행했습니다.</p>
<p>[DB 설계]</p>
<ol>
<li>User</li>
</ol>
<pre><code class="line-numbers">{
  "email": "test@test.com",
  "name": "wonizz",
  "password": "vMLhwE7ZamUj1dwF+bSauQ=="  // 패스워드 암호화
}
</code></pre>
<ol start="2">
<li>Book</li>
</ol>
<pre><code class="line-numbers">{
  "duedate": "2020-06-09",
  "reservationYN": "N",   //y 예약가능 , N 불가
  "title": "쿠버네티스패턴",
  "author" : "안승규"
}
</code></pre>
<ol start="3">
<li>Rental</li>
</ol>
<pre><code class="line-numbers">{
  "rentalno" : 1111
  "booktitle": "쿠버네티스패턴",
  "duedate": "2020-05-14",
  "email": "dong_won.lee@samsung.com",
  "rsrvdate": "2020-05-24"
  "rental_compdate" : "2020-05-28"
}
</code></pre>
<p>[API 스펙 설계]</p>
<p>http api 설계 원칙은 따로 정의된것은 없고, 각 프로젝트마다 상황에 맞춰서 진행을 하면됩니다.</p>
<p>아래의 내용처럼 여러가지 가능한 설계 원칙을 세우고 수행을 하는 것이 좋습니다.</p>
<p><a class="wp-editor-md-post-content-link" href="https://github.com/yoondo/http-api-design/tree/master/ko" target="_blank" rel="noopener">Heroku 플랫폼 API 설계 원칙 (한국어) </a></p>
<p>규칙이 없다면, 통상적인 설계 작업에 따라 진행합니다. 필자는 다음과 같이 진행했습니다.</p>
<ul>
<li>로그인</li>
</ul>
<pre><code class="line-numbers">//login : 로그인 API

[request parameter]
{
    "email": "test221@test.com",
    "password": "1231"
}

[response] - 200 / 정상 로그인
{
    "user": {
        "id": "test221@test.com",
        "name": "wonizz",
        "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InNrZGkua2ltQHNhbXN1bmcuY29tIiwibmFtZSI6Iuq5gOyEoOyasCIsImlhdCI6MTU5MDcyODcxMiwiZXhwIjoxNTkwNzMwNTEyLCJpc3MiOiJnZXRfdG9rZW5fY29udHJvbGxlciJ9.TL2TafWc9ivw5ZDqObwU49rjJf5X1JnneZ0GohGa7VU"
    }
}

[response] - 400 / parameter missed
{
    "message": "required parameter is missed"
}

[response] - 500
{
    "message": "Internal Server Error"
}

예제 : https://8xk6c6vlz2.execute-api.ap-northeast-2.amazonaws.com/login
</code></pre>
<ul>
<li>유저 등록</li>
</ul>
<pre><code class="line-numbers">//register : 유저 등록 API
{
    "email": "test221@test.com",
    "name": "dlehddnjs",
    "password": "1234"
}

[response] - 200 / 정상 유저 등록
{
    "user": {
        "email": "test221@test.com",
        "username": "dlehddnjs",
        "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InRlc3QyMjFAdGVzdC5jb20iLCJpYXQiOjE1OTA3Mjg4NzgsImV4cCI6MTU5MDczMDY3OCwiaXNzIjoiZ2V0X3Rva2VuX2NvbnRyb2xsZXIifQ.5snUeOV6zzr7_RwuSC6gQeFi1NBImjkXaXF_WGCTgvw"
    }
}

[response] - 400 / parameter missed
{
    "message": "required parameter is missed"
}

[response] - 500
{
    "message": "Internal Server Error"
}

예제 : https://8xk6c6vlz2.execute-api.ap-northeast-2.amazonaws.com/register
</code></pre>
<ul>
<li>유저 정보 조회(JWT 토큰 방식)</li>
</ul>
<pre><code class="line-numbers">//userinfo : 토큰값 유효성 검증 
{
    "token": "eyJhbiOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InRlc3QyMjFAdGVzdC5jb20iLCJuYW1lIjoiZGRkZGRkMTExMjIiLCJpYXQiOjE1OTAyMTM0MTAsImV4cCI6MTU5MDIxNTIxMCwiaXNzIjoiZ2V0X3Rva2VuX2NvbnRyb2xsZXIifQ.1-wekORpzeMtkC3SHJ2ZkrvnrFkwD_JgyjMKm4hn7ZE"
}

[response] - 200 / 정상 토근 
{
    "user": {
        "id": "test221@test.com",
        "iat": 1590728878,
        "exp": 1590730678,
        "iss": "get_token_controller"
    }
}


[response] - 400 / parameter missed
{
    "message": "required parameter is missed"
}

[response] - 401 / unauthorized
{
    "message": "invalid token"
}

[response] - 500
{
    "message": "Internal Server Error"
}

예제 : https://8xk6c6vlz2.execute-api.ap-northeast-2.amazonaws.com/userinfo
</code></pre>
<p>이외에</p>
<ul>
<li>도서 리스트 / 나의 대출 예약 리스트</li>
<li>대출 / 반납</li>
</ul>
<p>관련한 API 들이 있습니다.</p>
<h2>4. 개발</h2>
<p>개발기술 요소에는 다음의 다음과 같이 생각했습니다</p>
<ul>
<li>Font-end : React + Redux</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/07/toypjt_6.png?w=1200&#038;ssl=1" alt="React+Redux" /></p>
<ul>
<li>Back-end : Node.js + Dynamodb</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/07/toypjt_7.png?w=1200&#038;ssl=1" alt="Node.js + Dyanmodb" /></p>
<p>필자의 블로그에는 해당 기술요소에 대한 설명이 간단하게 되어있습니다. 다만 이번에 새로이 DynamoDB를 사용해보면서, api를 어떤 식으로 만들어야되는지 고민을 하고 작성해보는 시간을 갖을 수 있었습니다.</p>
<p>각 람다 API는 다음의 기록해두었습니다.</p>
<p><a class="wp-editor-md-post-content-link" href="https://github.com/wonizz/lambda-example" target="_blank" rel="noopener">Node.js + Dynamodb 연계 소스 </a></p>
<p>API 기능들에 대해서는 얼추 완성이 되어있고, 다음의 URL로 호출을 하면 됩니다.</p>
<h2>5. 테스트</h2>
<p>아직 프론트엔드가 완성이 되지 않아서, 테스트를 진행하고 있지는 못합니다. 다만, 이번에 작성하면서 동시에 TDD를 도입해볼까 생각중입니다. 테스트 코드까지 같이 작성하여, 내가 작성한 코드가 운영으로 반영되기 이전에 테스트 코드를 통해서 정상동작에 대한 여부를 체크하도록 해보려고 합니다.</p>
<p>주로 많이 사용하는 것이 mocha, jest, jasmine 등이 있는 것 같습니다. 다음시간에 좀더 학습을 하고 같이 병행을 해볼까 합니다.</p>
<h2>6. 마치며..</h2>
<p>이번에는 간단하게 토이프로젝트를 기획해보고, 구상한대로 바로바로 구현을 해보면서 마치 장난감을 갖고 놀듯 만들어 볼 생각입니다. 아직은 Back-end 위주로 완성을 하는 단계이고, 좀더 구체화된 소스코드나 화면개발이 완료되면 그때 그때 정리해서 포스팅 하도록 하겠습니다.</p>
<p>이번 포스팅은 전체적인 아웃라인에 해당하는 내용으로 각 단계에 맞춰서 다른 프로젝트를 가더라도 진행을 해보면 좋을것 같습니다.</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/07/28/toy-project-1/">[토이프로젝트] 1편 : 간단한 게시판 만들기</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/07/28/toy-project-1/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1406</post-id>	</item>
		<item>
		<title>[Reactjs]  AWS Codepipeline을 통한 배포</title>
		<link>https://blog.wonizz.com/2020/05/19/reactjs-build-and-deploy/</link>
					<comments>https://blog.wonizz.com/2020/05/19/reactjs-build-and-deploy/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Tue, 19 May 2020 02:43:49 +0000</pubDate>
				<category><![CDATA[React.js]]></category>
		<category><![CDATA[AWS]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1231</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>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 CI/CD에 대해서 정리를 해보고자 합니다. 프로젝트를 진행하면서, 매번 수동으로 빌드를 수행했었고, 해당 파일을 S3로 올려주는 작업을 진행했었습니다. 그러다보니 굉장히 불편한 점이 많이 있었습니다. 그래서 생각한 아이디어는 branch를 우선 2개(development &#38; master)로 운영을 하고, 개발 브랜치에 푸시가 될 때는 빌드가 된 파일을 dev s3로 올려주고, master 브랜치로 pull request로 머지가 될&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/05/19/reactjs-build-and-deploy/">[Reactjs]  AWS Codepipeline을 통한 배포</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>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 CI/CD에 대해서 정리를 해보고자 합니다. 프로젝트를 진행하면서, 매번 수동으로 빌드를 수행했었고, 해당 파일을 S3로 올려주는 작업을 진행했었습니다. 그러다보니 굉장히 불편한 점이 많이 있었습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/deploy_pipe_2.png?w=1200&#038;ssl=1" alt="Reactjs  AWS Codepipeline을 통한 배포 설명 이미지 1" /></p>
<p>그래서 생각한 아이디어는 branch를 우선 2개(development &amp; master)로 운영을 하고, 개발 브랜치에 푸시가 될 때는 빌드가 된 파일을 dev s3로 올려주고, master 브랜치로 pull request로 머지가 될 때, github actions를 통해서 prd s3로 올려주어 서비스를 하도록 하는 것이였습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/deploy_pipe_1.png?w=1200&#038;ssl=1" alt="Reactjs  AWS Codepipeline을 통한 배포 설명 이미지 2" /></p>
<p>위에 보시는 것처럼 Master 브랜치로 pull request를 통해서 merge가 될때는 github actions가 수행되도록 yaml 파일을 작성해두었습니다. 필자의 블로그의 아래 내용을 참고 해주시기 바랍니다.</p>
<p><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2020/01/08/reactjs-github-actions-deploy/">github actions로 S3 웹호스팅 배포하기</a></p>
<p>지난 글들은 아래를 참고 해주시면 됩니다.</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="http://blog.wonizz.com/2020/01/06/reactjs-redux-project/">리액트 정리 1편 : redux project 소개(1)</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="http://blog.wonizz.com/2020/03/26/reactjs-redux-project-2/">리액트 정리 2편 : redux project 소개(2)</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="http://blog.wonizz.com/2020/04/06/reactjs-redux-project-props-state/">리액트 정리 3편 : state &#038; props</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/2020/04/13/reactjs-s3-web-hosting/">리액트 정리 4편 : S3 웹호스팅</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="http://blog.wonizz.com/2020/01/08/reactjs-github-actions-deploy/">리액트 정리 5편 : 소스 배포 &#8211; github actions </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="http://blog.wonizz.com/2020/04/21/lambda-edge-guide/">리액트 정리 6편 : 람다 이미지 리사이징</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="http://blog.wonizz.com/2020/05/06/reactjs-aws-cloudfront-cdn-apply/">리액트 정리 7편 : CDN 적용</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="http://blog.wonizz.com/2020/05/11/reactjs-aws-route53-domain/">리액트 정리 8편 : 도메인 연결</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="http://blog.wonizz.com/2020/05/16/reactjs-build-and-deploy/">리액트 정리 9편 : Codepipline을 통한 배포</a></li>
</ul>
<h2>1. GitHub Actions에서는 한개의 브랜치가 컨트롤이 가능하던데요?</h2>
<p>저는 CI/CD는 Github actions로 끝내려 했습니다. 그런데 개발 브랜치에 개발 내용을 푸시를 하고나서 확인할 방법이 없었습니다. 물론 로컬에서 최대한 확인을 하고나서 서버상에 올려 체크를 하는것인데, 바로 운영에 올려서 확인할 방법이 도저히 생각나지 않았습니다.</p>
<p>Github Actions에서는 또한, 한개의 project에 대해서만 액션을 제공해주기 떄문에, 개발 브랜치에 또다른 CI/CD를 적용해야만 했습니다.</p>
<p><a class="wp-editor-md-post-content-link" href="https://github.com/wonizz/productmoor-frontend" target="_blank" rel="noopener">토이프젝트 깃헙</a></p>
<p>위의 내용에서 보시면, github actions에 대한 yaml 파일을 확인 할 수 있습니다.</p>
<pre><code class="line-numbers">name: React build
on: 
  push:                               # master Branch에서 push 이벤트가 일어났을 때만 실행
    branches:
      - master
</code></pre>
<p>브랜치를 master로 지정을 해두었기 때문에 Actions 자체는 master를 배포하는데 사용하기로 했습니다.</p>
<p>그렇다면, dev branch는 어떻게 빌드를 하고 배포를 할까요? 필자는 여기서 아마존 프리티어에서 제공해주는 서비스를 최대한 이용해보자고 마음먹었습니다.</p>
<p>그리고 찾아보면 결과 아래와 같은 서비스들을 무료로 사용할 수 있었습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/deploy_pipe_3.png?w=1200&#038;ssl=1" alt="Reactjs  AWS Codepipeline을 통한 배포 설명 이미지 3" /></p>
<p>사실, Code Deploy까지는 쓸 이유가 없는게, CodeBuild에서 S3로 업로드 할수 있는 내용이 있어서,따로 쓰지 않았습니다</p>
<h2>2. aws CodePipeline과 CodeBuild 만들기</h2>
<p>[AWS Console 접속] > [AWS CodePipeline 접속] > [파이프라인 생성] 클릭</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/deploy_pipe_4.png?w=1200&#038;ssl=1" alt="Reactjs  AWS Codepipeline을 통한 배포 설명 이미지 4" /></p>
<p>아래와 같이 셋팅을 해줍니다.</p>
<ul>
<li>파이프라인 이름</li>
<li>IAM 역할 필요 : 현재 역할이 없으므로 신규 생성합니다.</li>
<li>기본 위치 : github 소스를 pull받고 업로드할 S3를 지정해줍니다.(커스텀은 사용자 지정위치)</li>
<li>기본 AWS 관리형 키</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/deploy_pipe_5.png?w=1200&#038;ssl=1" alt="Reactjs  AWS Codepipeline을 통한 배포 설명 이미지 5" /></p>
<p>target 소스 위치가 github에 있기 때문에 oauth를 통해서 연결 지어주는 내용입니다. 손쉽게 클릭으로 github을 연동 할 수 있고, 연동을 하게 되면, 어떤 프로젝트와 어떤 브랜치를 사용할 것인지를 선택해 줍니다.</p>
<p>선택한 저장소의 브랜치에서 변경이 감지되면 파이프라인이 동작하기 위해서 Github 웹훅을 선택해줍니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/deploy_pipe_6.png?w=1200&#038;ssl=1" alt="Reactjs  AWS Codepipeline을 통한 배포 설명 이미지 6" /></p>
<p>다음은 빌드내용입니다. CodeBuild를 사용하기로 했으니, 공급자는 CodeBuild를 선택해 줍니다. 현재는 CodeBuild에 대한 내용을 생성하지 않았기 때문에 신규로 생성해주기 위해서 <strong>프로젝트 생성</strong>을 클릭 해줍니다.</p>
<p>그럼 자연스럽게 CodeBuild로 이동해서 생성하는 화면이 나옵니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/deploy_pipe_7.png?w=1200&#038;ssl=1" alt="Reactjs  AWS Codepipeline을 통한 배포 설명 이미지 7" /></p>
<p>빌드할 프로젝트 이름을 입력합니다</p>
<ul>
<li>프로젝트 이름</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/deploy_pipe_8.png?w=1200&#038;ssl=1" alt="Reactjs  AWS Codepipeline을 통한 배포 설명 이미지 8" /></p>
<p>빌드할 환경을 설정하는 영역입니다.</p>
<p>필자는 운영체제를 Ubuntu로 했고 나머지는 기본값을 했습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/deploy_pipe_9.png?w=1200&#038;ssl=1" alt="Reactjs  AWS Codepipeline을 통한 배포 설명 이미지 9" /></p>
<p>Build Spec같은 경우는 직접 입력해주는 방식을 선택했습니다.</p>
<pre><code class="line-numbers">version: 0.2
phases:
  install:
    commands:
      - echo Insatlling NPM Packages and wget Enviorment File
      - npm install
  build:
    commands:
      - echo Build started on `date`
      - npm run build
  post_build:
    commands:
      - aws s3 sync ./build s3://dev-productmoor --acl public-read
artifacts:
  files:
    - '**/*'
  name: build-$(date +%Y-%m-%d) 
  base-directory: build
cache:
  paths:
    - "node_modules/**/*"
</code></pre>
<p>하나씩 내용을 살펴보기로 하겠습니다.</p>
<pre><code class="line-numbers">version: 0.2
phases:
  install:
    commands:
      - echo Insatlling NPM Packages and wget Enviorment File
      - npm install
</code></pre>
<ul>
<li>npm install : package.json으로부터 필요한 내용을 받습니다.</li>
</ul>
<pre><code class="line-numbers">  build:
    commands:
      - echo Build started on `date`
      - npm run build
</code></pre>
<ul>
<li>npm run build : 실제 소스파일을 컴파일해서 /build 폴더 하위로 빌드 파일을 생성합니다.</li>
</ul>
<pre><code class="line-numbers">  post_build:
    commands:
      - aws s3 sync ./build s3://dev-productmoor --acl public-read
</code></pre>
<ul>
<li>s3 업로드 : 빌드한 파일을 s3로 직접 업로드 합니다.</li>
</ul>
<pre><code class="line-numbers">artifacts:
  files:
    - '**/*'
  name: build-$(date +%Y-%m-%d) 
  base-directory: build
</code></pre>
<ul>
<li>build 파일 압축 후 업로드 : 배포 후 문제가 생겼을때를 대비하여, 항상 배포된 파일들은 zip파일로 압축하여 이력을 갖고 있습니다.</li>
</ul>
<p>끝으로, 로그 관련된 내용은 cloudwatch를 선택하고 넘어갑니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/deploy_pipe_10.png?w=1200&#038;ssl=1" alt="Reactjs  AWS Codepipeline을 통한 배포 설명 이미지 10" /></p>
<p>배포는 이미 Codebuild에서 수행하기로 했으므로(S3 업로드), 따로 구성을 하지 않고 넘어갑니다.</p>
<p>마지막으로 검토를 하게 되고 최종 생성을 클릭하여 생성합니다.</p>
<h2>3. 빌드 테스트</h2>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/deploy_pipe_11.png?w=1200&#038;ssl=1" alt="Reactjs  AWS Codepipeline을 통한 배포 설명 이미지 11" /></p>
<p>최종적으로 파이프라인을 생성하게 되면, source를 pull받고 codebuild를 수행하게 됩니다.</p>
<p>위와 같이 정상적으로 배포가 진행이 됩니다.</p>
<h2>4. 최종 CI/CD 구성도</h2>
<p>개발/운영으로 2개의 브랜치를 나눴고, 각기 다른 서비스(깃헙액션, 코드파이프라인)을 통해서 빌드와 배포를 구성했습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/deploy_pipe_12.png?w=1200&#038;ssl=1" alt="Reactjs  AWS Codepipeline을 통한 배포 설명 이미지 12" /></p>
<p>위쪽이 운영용이고, 아랫쪽이 개발용입니다. 필자가 생각한 방식은 개발에서 검증이 다 마치면, code를 마스터로 pull request를 요청할 수 있고, 역시 웹훅 방식으로 github actions가 동작하면서 운영으로 바로 배포가 되도록 했습니다.</p>
<p>S3 앞단에 cloudfront가 있기 때문에 운영으로 잘못된 소스가 나가더라도, 캐시가 플러시 되지 않는한 문제가 생기지 않을것이라고 생각했습니다.</p>
<h2>5. 마치며..</h2>
<p>이번시간에는 CI/CD를 어떻게 구성하였는지에 대해서 정리를 했습니다. 확실히 AWS에서 제공해주는 서비스들을 사용하다보면 한개의 서비스를 만들어서 운영하는데까지 정말 편리하다고 생각이 듭니다. CI/CD를 구성해놓고 보니, 좀더 편리성을 찾고자 배포 알람에 대해서 생각해보게 되었습니다.</p>
<p>그래서 다음시간에는 AWS에서 최근에 서비스를 제공하는 Chatops를 통해서 Slack으로 연계하는 내용에 대해서 정리를 해보도록 하겠습니다.</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/05/19/reactjs-build-and-deploy/">[Reactjs]  AWS Codepipeline을 통한 배포</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/05/19/reactjs-build-and-deploy/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1231</post-id>	</item>
		<item>
		<title>[Reactjs] AWS Route53을 통한 도메인 연결</title>
		<link>https://blog.wonizz.com/2020/05/11/reactjs-aws-route53-domain/</link>
					<comments>https://blog.wonizz.com/2020/05/11/reactjs-aws-route53-domain/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 11 May 2020 07:46:03 +0000</pubDate>
				<category><![CDATA[React.js]]></category>
		<category><![CDATA[AWS]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1208</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>안녕하세요? 정리하는 개발자 워니즈입니다. 개인으로 진행하는 프로젝트가 드디어! 👏👏 도메인 연결만을 남겨두고 있습니다. 지금까지 했던 것을 다시 정리하면, 어플리케이션 제작(Reactjs) 이미지 오리진 서버 (S3) 이미지 캐시 서버 (CloudFront) : 람다 엣지 사용 인증서 작성(아마존 인증서) 인증서 연결(CloudFront &#8211; 아마존 인증서 연결) 도메인 연결(Route53 &#8211; CloudFront 연결) 인증서 연결에 대한 내용은 간략해서 따로 정리를 하지는 않았지만,&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/05/11/reactjs-aws-route53-domain/">[Reactjs] AWS Route53을 통한 도메인 연결</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>안녕하세요? 정리하는 개발자 워니즈입니다. 개인으로 진행하는 프로젝트가 드디어! 👏👏 도메인 연결만을 남겨두고 있습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/route52_1.png?w=1200&#038;ssl=1" alt="Reactjs AWS Route53을 통한 도메인 연결 설명 이미지 1" /></p>
<p>지금까지 했던 것을 다시 정리하면,</p>
<ul>
<li>어플리케이션 제작(Reactjs)</li>
<li>이미지 오리진 서버 (S3)</li>
<li>이미지 캐시 서버 (CloudFront) : 람다 엣지 사용</li>
<li>인증서 작성(아마존 인증서)</li>
<li>인증서 연결(CloudFront &#8211; 아마존 인증서 연결)</li>
<li>도메인 연결(Route53 &#8211; CloudFront 연결)</li>
</ul>
<p>인증서 연결에 대한 내용은 간략해서 따로 정리를 하지는 않았지만, CloudFront 관련 정리 포스팅에서 보시면,</p>
<p>[CloudFront] > [Edit Distribution] > [SSL Certificate] > [Custom SSL Certificate] 선택하여 생성하신 인증서를 심어주면, 동작하게 됩니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/route53_2.png?w=1200&#038;ssl=1" alt="Reactjs AWS Route53을 통한 도메인 연결 설명 이미지 2" /></p>
<p>지난 글들은 아래를 참고 해주시면 됩니다.</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="http://blog.wonizz.com/2020/01/06/reactjs-redux-project/">리액트 정리 1편 : redux project 소개(1)</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="http://blog.wonizz.com/2020/03/26/reactjs-redux-project-2/">리액트 정리 2편 : redux project 소개(2)</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="http://blog.wonizz.com/2020/04/06/reactjs-redux-project-props-state/">리액트 정리 3편 : state &#038; props</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/2020/04/13/reactjs-s3-web-hosting/">리액트 정리 4편 : S3 웹호스팅</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="http://blog.wonizz.com/2020/01/08/reactjs-github-actions-deploy/">리액트 정리 5편 : 소스 배포 &#8211; github actions </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="http://blog.wonizz.com/2020/04/21/lambda-edge-guide/">리액트 정리 6편 : 람다 이미지 리사이징</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="http://blog.wonizz.com/2020/05/06/reactjs-aws-cloudfront-cdn-apply/">리액트 정리 7편 : CDN 적용</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="http://blog.wonizz.com/2020/05/11/reactjs-aws-route53-domain/">리액트 정리 8편 : 도메인 연결</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="http://blog.wonizz.com/2020/05/16/reactjs-build-and-deploy/">리액트 정리 9편 : Codepipline을 통한 배포</a></li>
</ul>
<h2>1. Route53이란 무엇인가요?</h2>
<p>자 그럼, 이제 Route53이 어떤 서비스 인지 간략하게 정리를 해보도록 하겠습니다.</p>
<blockquote><p>
  Route53이란 ec2, elb, s3 cloudfront와 연동가능한 dns서비스를 말합니다.
</p></blockquote>
<p>아쉽게도 프리티어에서는 사용이 불가한 서비스 입니다. 필자도 해당 블로그를 운영하면서 동시에 CLoudFront + Route53 조합으로 가려고 해봤는데, 비용이 발생하는걸로 바로 포기를 했습니다.</p>
<p>운이 좋게 개인 프로젝트를 진행할 기회가 생겨서 이번기회에 Route53을 사용해볼 수 있었습니다.</p>
<p>쉽게 이야기해서 DNS를 제공해주는 서비스라고 보시면됩니다. DNS라는 것은 사용자 입장에서 IP를 외워 둘수 없기 때문에 알기 쉬운 도메인과 해당 인스턴스 혹은 ELB등을 연결지어주는 서비스라고 보시면됩니다.</p>
<h3>1-1. 도메인 연결하는 방법</h3>
<ul>
<li>A Record</li>
</ul>
<p>일반적으로 많이 사용하는 IPv4방식(예 &#8211; 123.123.456.456)의 IP주소로 연결해 줍니다. 현재 가장 많이 쓰이고 있는 방법입니다.</p>
<ul>
<li>AAAA Record</li>
</ul>
<p>IPv6방식(예 &#8211; 1234:2345:3456:4567:5678)의 IP주소에 연결을 하여 줍니다. IPv6의 주소를 사용하고 있는 경우에만 관련됩니다.</p>
<ul>
<li>CNAME Record</li>
</ul>
<p>별칭이라는 이야기를 하는데, 쉽게 말씀드리면 다른 도메인 주소를 지정한 주소로 연결할 수 있게끔 해줍니다.</p>
<ul>
<li>DDNS Record</li>
</ul>
<p>개인 서버를 운영하거나 공인 IP가 유동적인 경우에는 변경된 아이피 주소를 주기적으로 갱신하여 줍니다. A Record방식과 연결방식에는 차이가 없지만 자동으로 변경된 아이피를 갱신하는냐, 아니면 직접 입력을 하느냐의 차이입니다.</p>
<ul>
<li>웹 포워딩</li>
</ul>
<p>아이피주소가 아닌 웹 주소로 직접 연결을 합니다. 웹 포워딩의 장점은 복잡한 주소를 한번에 연결할 때 편합니다. 하지만 원래 주소를 감춰서 보여주지 못합니다. (억지로 감추면 멀쩡한 웹페이지 해상도가 꼬이는 등 별별 현상이 다 일어나더군요.)</p>
<p>위의 방식들은 원래의 주소(IP주소)를 감춰서 보여주기 때문에 원래의 주소가 노출 될 일은 없지만 웹 포워딩은 원래 주소가 노출되는 불편한 점을 가지고 있습니다.</p>
<p><a class="wp-editor-md-post-content-link" href="https://velog.io/@noyo0123/Route53-%EC%97%90%EC%84%9C-host-zone-a-%EB%A0%88%EC%BD%94%EB%93%9C%EB%9E%80-adk21ictsb" target="_blank" rel="noopener">출처 : 도메인과 네임서버 그리고 Route53이란?</a></p>
<h2>2. Route53과 CloudFront 연결하기</h2>
<p>Route53을 연결하기에 앞서서 CloudFont에서 해야될 선작업을 먼저 정리하겠습니다.</p>
<ul>
<li>CloudFront 수정</li>
</ul>
<p>[CloudFonrt] > [Edit Distribution] 을 클릭합니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/route53_3.png?w=1200&#038;ssl=1" alt="Reactjs AWS Route53을 통한 도메인 연결 설명 이미지 3" /></p>
<p>그리고 나서, 위에 보시는 것처럼 <strong>Alternate Domain Names</strong>를 입력해줍니다. 그 아래 빨간 박스는 위에서 설명드린 <strong>ACM 인증</strong> 관련 된 내용입니다.</p>
<ul>
<li>Route53 도메인 연결</li>
</ul>
<p>[Route53] > [Hosted Zones] 을 클릭합니다. 기존에 domain을 Route53을 통해서 생성하였기 때문에 호스팅 영역에 존재하는 목록이 있습니다. 해당 목록을 클릭하고 들어갑니다.  [레코드 세트 생성] 을 클릭한뒤에 아래와 같이 원하는 도메인 이름을 선정합니다.</p>
<ol>
<li>이름 : www.productmoor.com</li>
<li>유형 : A &#8211; IPv4 주소</li>
<li>별칭 : 예</li>
<li>별칭 대상 : 클라우트 프론트 주소</li>
</ol>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/Route53_4.png?w=1200&#038;ssl=1" alt="Reactjs AWS Route53을 통한 도메인 연결 설명 이미지 4" /></p>
<p>입력을 한 뒤, 저장을 합니다.</p>
<ul>
<li>테스트</li>
</ul>
<p>https://www.productmoor.com 으로 접속을 해봅니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/Route53_5.png?w=1200&#038;ssl=1" alt="Reactjs AWS Route53을 통한 도메인 연결 설명 이미지 5" /></p>
<p>정상적으로 인증서도 노출이 되고, 서비스도 잘 되는 것을 볼 수 있습니다.</p>
<h2>3. 마치며..</h2>
<p>드디어.. 필자가 지난 3개월정도 제작한 어플리케이션에 대하여 서비스를 하기 시작했습니다. 아직은 미흡하지만, 그래도 처음으로 제작하는 리액트 어플리케이션이였고 서버리스로 구성을 하면서 AWS 서비스에 대해서 이것저것 배울 수 있는 좋은 기회였던 것 같습니다.</p>
<p>더군다나, 여러가지 목표도 생기기 시작했습니다. 이번에 깃헙을 통해서 어플리케이션을 제작했는데 대다수의 외부 개발자들이 1일 1커밋을 목표로 하시는 분들이 많이 있는것 같습니다. 저는 아직은 그렇게 까지는 못하더라도 1주일 2회 커밋이라도 노력을 해볼 예정입니다.</p>
<p>추가적으로 아마존 서비스들이 무궁무진하게 많아서, 여러가지 서비스들에 대해서 좀더 알아 보는 것이 목표로 생겼습니다. AWS 에서의 어플리케이션 개발은 전통적으로 수행하던 개발보다 확실히 편리해진 것 같습니다.</p>
<p>개발자가 하나하나 신경써줘야될 부분들을 매니지드로 넘기면서 동시에 인프라까지 관리를 할 수 있는 것 같습니다.</p>
<p>총 8편으로 구성된 이번 포스팅에서 미흡한 부분도 있지만, 중간중간 업데이트를 할 예정입니다. 많은 관심 부탁 드립니다^^</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/05/11/reactjs-aws-route53-domain/">[Reactjs] AWS Route53을 통한 도메인 연결</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/05/11/reactjs-aws-route53-domain/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1208</post-id>	</item>
		<item>
		<title>[Reactjs] AWS CloudFront를 통한 CDN 적용</title>
		<link>https://blog.wonizz.com/2020/05/06/reactjs-aws-cloudfront-cdn-apply/</link>
					<comments>https://blog.wonizz.com/2020/05/06/reactjs-aws-cloudfront-cdn-apply/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Wed, 06 May 2020 00:34:26 +0000</pubDate>
				<category><![CDATA[React.js]]></category>
		<category><![CDATA[AWS]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1194</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>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 AWS의 CDN 서비스인 CloudFront 에 대해서 정리하도록 하겠습니다. 지난 글들은 아래를 참고 해주시면 됩니다. 리액트 정리 1편 : redux project 소개(1) 리액트 정리 2편 : redux project 소개(2) 리액트 정리 3편 : state &#038; props 리액트 정리 4편 : S3 웹호스팅 리액트 정리 5편 : 소스 배포 &#8211; github actions&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/05/06/reactjs-aws-cloudfront-cdn-apply/">[Reactjs] AWS CloudFront를 통한 CDN 적용</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>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 AWS의 CDN 서비스인 <strong>CloudFront</strong> 에 대해서 정리하도록 하겠습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/cloudfront_0.png?w=1200&#038;ssl=1" alt="cloudfront_0" /></p>
<p>지난 글들은 아래를 참고 해주시면 됩니다.</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="http://blog.wonizz.com/2020/01/06/reactjs-redux-project/">리액트 정리 1편 : redux project 소개(1)</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="http://blog.wonizz.com/2020/03/26/reactjs-redux-project-2/">리액트 정리 2편 : redux project 소개(2)</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="http://blog.wonizz.com/2020/04/06/reactjs-redux-project-props-state/">리액트 정리 3편 : state &#038; props</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/2020/04/13/reactjs-s3-web-hosting/">리액트 정리 4편 : S3 웹호스팅</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="http://blog.wonizz.com/2020/01/08/reactjs-github-actions-deploy/">리액트 정리 5편 : 소스 배포 &#8211; github actions </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="http://blog.wonizz.com/2020/04/21/lambda-edge-guide/">리액트 정리 6편 : 람다 이미지 리사이징</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="http://blog.wonizz.com/2020/05/06/reactjs-aws-cloudfront-cdn-apply/">리액트 정리 7편 : CDN 적용</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="http://blog.wonizz.com/2020/05/11/reactjs-aws-route53-domain/">리액트 정리 8편 : 도메인 연결</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="http://blog.wonizz.com/2020/05/16/reactjs-build-and-deploy/">리액트 정리 9편 : Codepipline을 통한 배포</a></li>
</ul>
<p>필자가 진행하는 토이프로젝트는 이미지들이 주를 이루는 웹페이지입니다. 이미지들을 <strong>S3</strong>에 적재를 하고 해당 URL로 호출을 홰서 화면에 노출시켜주는 것입니다.</p>
<p>그런데, 이미지들이 모두 원본으로 올라가있고, 더군다나 사이즈가 굉장히 크기 때문에 사용자 경험에서 최악을 제공했습니다.</p>
<p>아무래도 <strong>Cache Layer</strong> 가 필요한 시점이였고, 가장 손쉽게 적용할 수 있는 것이 AWS의 CloudFront라고 생각했습니다.</p>
<h2>1. CloudFont란 무엇인가요?</h2>
<blockquote><p>
  빠르고 고도로 안전하며 프로그래밍 가능한 콘텐츠 전송 네트워크(CDN)</p>
<p>  Amazon CloudFront는 개발자 친화적 환경에서 짧은 지연 시간과 빠른 전송 속도로 데이터, 동영상, 애플리케이션 및 API를 전 세계 고객에게 안전하게 전송하는 고속 콘텐츠 전송 네트워크(CDN) 서비스입니다.
</p></blockquote>
<p>CloudFont는 다른 AWS의 서비스 와도 통합이 됩니다. 필자는 S3를 Origin으로 사용하고 CloudFront가 CDN역할을 하여 엣지 서비스를 하는 것으로 서비스를 연결할 예정입니다.</p>
<h2>2. CloudFront 설정 방법</h2>
<p>[AWS Console 접속] > [CloudFront 접속] > [Create Distribution 클릭]</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/cloudfront_1.png?w=1200&#038;ssl=1" alt="CloudFront_1" /></p>
<ul>
<li>첫번째는 .html, .css, .js 등의 배포 속도를 높이는 기능입니다.</li>
<li>두번째는 Adobe Flash Media Server의 RTMP 프로토콜을 사용하여 스트리밍 미디어 파일의 배포 속도를 높이는 서비스인데, 2020년 12월 31일부로 EOS 된다고 합니다.</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/cloudfront_2.png?w=1200&#038;ssl=1" alt="CloudFont_2" /></p>
<p>[Create Distribution] 으로 들어오게 되면, 위와 같은 화면이 보입니다. 화면상에서는 크게 3개의 셋팅으로 구성되어있습니다.</p>
<ul>
<li>Origin Settings : 오리진을 어느곳으로 Mapping을 할 것인가요?</li>
<li>Default Cache Behavior Settings : Cache 정책 및 Layer에 대한 셋팅은 어떻게 할것인가요?</li>
<li>Distribution Settings : WAF, 인증서, Root Object에 대한 셋팅은 어떻게 할 것인가요?</li>
</ul>
<p>사실 위에서 <strong>빨강 박스</strong> 표시해둔곳만 셋팅하고 넘어가면됩니다. 추후에 인증서 + 도메인 연결을 위해서 변경을 수행합니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/cloudfront_3.png?w=1200&#038;ssl=1" alt="cloudfront_3" /></p>
<ul>
<li>Price Class &#8211; 퍼포먼스에 비례해서 가격이 오릅니다.</li>
<li>Alternate Domain Names &#8211; 해당 Distribution을 통해 사용할 도메인을 등록 해 줍시다.</li>
<li>SSL Certificate &#8211; Custom SSL Certificate를 선택하면 ACM에서 설정한 인증서를 불러올 수 있습니다.</li>
</ul>
<p>[Distribution Settings] 에서 위와 같이 셋팅합니다. 아직 인증서를 발급 받지 않았기 때문에 기본 cloudfront 인증서와 Root Object에서 &#8220;index.html&#8221; 을 입력해줍니다.</p>
<p>모든 셋팅이 완료 되면 우측하단에 [Create Distribution] 을 클릭하여 최종 CloudFront에 대한 배포를 수행합니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/05/cloudfront_4.png?w=1200&#038;ssl=1" alt="cloudfront_4" /></p>
<p>대략 10분이 지나면, 위의 메시지와 같이 상태코드가 [Deployed]로 변경이 됩니다. 그렇게 되면 Cloudfront를 통해서 S3의 내용을 캐싱을 하여 내려받게 됩니다.</p>
<h2>3. 테스트 수행하기</h2>
<p>정상적으로 Distribution이 완료가 되면, 다음과 같이 Cloudfront 도메인을 통해서 접속을 수행해봅니다. 필자 같은 경우 S3의 이미지들이 올려져 있고, 또한, reactjs로 build한 파일들이 올려져 있습니다.</p>
<p>모든 내용은 public access가 가능하도록 셋팅이 되어있습니다.</p>
<p>아직 도메인을 달아서 cloudfront 도메인을 공유 하지 못하지만, 정상적으로 호출이 수행됩니다! 이제 추가적으로 할 작업은 cloudfront에 ACM(인증서)를 셋팅하고 앞단에 Route53을 통해서 도메인을 연결하면됩니다.</p>
<p>Route53 -> CloudFront(With ACM) -> S3 의 순서로 호출이 수행됩니다.</p>
<h2>4. 마치며&#8230;</h2>
<p>필자가 지금까지 Reactjs앱을 제작하고, S3 웹호스팅을 통해서 직접 S3에서 호출을 수행하였습니다. 그러던중에 캐시 레이어가 필요하여 CloudFront를 도입하게 되었고 마지막 작업으로 ACM(인증서)와 Route53으로 최종 도메인 연결 작업을 할 예정입니다.</p>
<p>구축부터 인프라 구성까지 서버리스로 구성하다보니 최대한 개발에만 집중할 수 있었고, 확실히 아마존 서비스가 편리하게 구성이 되어있다는 걸 다시한번 더 느끼게 되었습니다.</p>
<p>다음 이시간에는 ACM과 Route53을 통한 도메인 연결에 대해서 정리하겠습니다.</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/05/06/reactjs-aws-cloudfront-cdn-apply/">[Reactjs] AWS CloudFront를 통한 CDN 적용</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/05/06/reactjs-aws-cloudfront-cdn-apply/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1194</post-id>	</item>
		<item>
		<title>[Reactjs] AWS Lambda@Edge 이미지 리사이징</title>
		<link>https://blog.wonizz.com/2020/04/21/lambda-edge-guide/</link>
					<comments>https://blog.wonizz.com/2020/04/21/lambda-edge-guide/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Tue, 21 Apr 2020 09:34:11 +0000</pubDate>
				<category><![CDATA[AWS]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1153</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>안녕하세요? 정리하는 개발자 워니즈입니다. 이번 시간에는 필자가 토이 프로젝트로 진행하는 프로젝트에서 있었던 이슈에 대해서 이야기를 하고, 어떻게 해결을 했는지 정리해보도록 하겠습니다. 지난 글들은 아래를 참고 해주시면 됩니다. 리액트 정리 1편 : redux project 소개(1) 리액트 정리 2편 : redux project 소개(2) 리액트 정리 3편 : state &#038; props 리액트 정리 4편 : S3 웹호스팅 리액트&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/04/21/lambda-edge-guide/">[Reactjs] AWS Lambda@Edge 이미지 리사이징</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>안녕하세요? 정리하는 개발자 워니즈입니다. 이번 시간에는 필자가 토이 프로젝트로 진행하는 프로젝트에서 있었던 이슈에 대해서 이야기를 하고, 어떻게 해결을 했는지 정리해보도록 하겠습니다.</p>
<p>지난 글들은 아래를 참고 해주시면 됩니다.</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="http://blog.wonizz.com/2020/01/06/reactjs-redux-project/">리액트 정리 1편 : redux project 소개(1)</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="http://blog.wonizz.com/2020/03/26/reactjs-redux-project-2/">리액트 정리 2편 : redux project 소개(2)</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="http://blog.wonizz.com/2020/04/06/reactjs-redux-project-props-state/">리액트 정리 3편 : state &#038; props</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/2020/04/13/reactjs-s3-web-hosting/">리액트 정리 4편 : S3 웹호스팅</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="http://blog.wonizz.com/2020/01/08/reactjs-github-actions-deploy/">리액트 정리 5편 : 소스 배포 &#8211; github actions </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="http://blog.wonizz.com/2020/04/21/lambda-edge-guide/">리액트 정리 6편 : 람다 이미지 리사이징</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="http://blog.wonizz.com/2020/05/06/reactjs-aws-cloudfront-cdn-apply/">리액트 정리 7편 : CDN 적용</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="http://blog.wonizz.com/2020/05/11/reactjs-aws-route53-domain/">리액트 정리 8편 : 도메인 연결</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="http://blog.wonizz.com/2020/05/16/reactjs-build-and-deploy/">리액트 정리 9편 : Codepipline을 통한 배포</a></li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/04/aws_lambda_edge_5.png?w=1200&#038;ssl=1" alt="Reactjs AWS Lambda@Edge 이미지 리사이징 설명 이미지 1" /></p>
<p>필자가 진행하는 프로젝트는 <strong>전세계 가구 브랜드를 전시하는 웹사이트</strong> 입니다. 이미지 기반의 Masonry 형식의 Grid View를 활용하다 보니, 첫 홈페이지 로딩시 수십개의 이미지들이 로딩되면서, Grid View가 살짝 깨지는 현상이 있었습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/04/aws_lambda_edge_1.png?w=1200&#038;ssl=1" alt="Reactjs AWS Lambda@Edge 이미지 리사이징 설명 이미지 2" /></p>
<p>좌측이 실제 화면이고, 실제 첫 페이지 로딩시에 리소스가 <strong>7.3mb</strong>를 호출하여 사용하는 만큼 네트워크 비용도 많이 들고, 사용자 경험 입장에서는 최악의 로딩을 제공하고 있었습니다.</p>
<p>그래서 생각했던것들은 다음과 같습니다.</p>
<ul>
<li>크롤서버에서 직접 Resizing을 수행한 뒤, S3에 이미지를 적재 한다.</li>
<li>람다를 두고, 적재된 이미지를 Resizing하고 특정 경로에 다싱 업로드를 수행한다.</li>
</ul>
<p>위의 방법들은 어찌 됐든, <strong>Backend</strong>에서 직접 처리 후, 원본 이미지를 변경해주는 작업이였습니다.</p>
<p>조금더 구글링을 하다보니, 필자와 같은 고민을 했던 여러 스타트업 회사들이 있었고, 그중에서도 가장 적합하게 찾은것이 <strong>당근마켓</strong>에서 게재한 블로그 내용입니다.</p>
<p><a class="wp-editor-md-post-content-link" href="https://medium.com/daangn/lambda-edge%EB%A1%9C-%EA%B5%AC%ED%98%84%ED%95%98%EB%8A%94-on-the-fly-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EB%A6%AC%EC%82%AC%EC%9D%B4%EC%A7%95-f4e5052d49f3" target="_blank" rel="noopener">AWS Lambda@Edge에서 실시간 이미지 리사이즈 &amp; WebP 형식으로 변환</a></p>
<h2>1. AWS Lambda@Edge가 무엇인가요?</h2>
<p>Lambda@Edge는 AWS CloudFront의 기능입니다. 이름에서도 느껴지듯이 람다이지만, 엣지쪽에 배치를 하여 사용자 경험을 최상으로 끌어내겠다는 것입니다. 별도의 API Gateway없이, CloudFront에 의해 생성된 이벤트를 트리거로 하여 함수를 실행할 수 있습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/04/aws_lambda_edge_4.png?w=1200&#038;ssl=1" alt="Reactjs AWS Lambda@Edge 이미지 리사이징 설명 이미지 3" /></p>
<p>CloudFront+Lambda@Edge를 사용하여 구현하기 위해서는 Origin response(원본 응답)에 대해서 이벤트 트리거를 사용하였습니다. CloudFront에 최초 접속했을때, 캐시된 내용이 있으면 응답하면 되고, 없으면 Origin에게 요청을 수행하여 돌아오는 응답에 대해서 람다 연산을 수행하고, 그 내용을 캐싱하고 사용자에게 응답하는 것입니다.</p>
<h2>2. AWS Lambda@Edge 구현</h2>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/04/aws_lambda_edge_3.png?w=1200&#038;ssl=1" alt="Reactjs AWS Lambda@Edge 이미지 리사이징 설명 이미지 4" /></p>
<p>필자가 최초 구현했을 당시에는, S3를 직접 호출하여 이미지를 사용자에게 내려주고 있었습니다. 그러다보니 Origin으로 요청이 계속해서 들어가게 되어있는 구조였습니다. (<strong>빨강색 표시</strong>)</p>
<p>하지만, CloudFront를 중간에 넣었고, 이미지에 대한 Resiznig 구현으로 AWS Lambda@Edge를 넣게 되었습니다.</p>
<p>따라서, 구현하고자 하는 내용은 아래와 같습니다.</p>
<p>Lambda@Edge를 이용해 다음과 같이 쿼리스트링을 옵션으로 요청에 따라 실시간으로 이미지의 크기(w, h), 품질(q), 파일 형식(포맷, f)을 변경할 수 있도록 구성하고자 합니다.</p>
<h2>2-1. IAM 정책/역할/신뢰관계 생성</h2>
<ul>
<li>정책생성</li>
</ul>
<ol>
<li>IAM으로 접속합니다.</li>
<li><strong>정책생성</strong>을 선택합니다.</li>
<li><strong>JSON</strong>을 선택하여 아래 정책을 입력합니다.</li>
<li>정책의 이름(<strong>ResizingImages</strong>)과 설명을 작성합니다.</li>
<li><strong>정책 생성</strong>버튼을 클릭합니다.</li>
</ol>
<pre><code class="line-numbers">{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "iam:CreateServiceLinkedRole",
                "lambda:GetFunction",
                "lambda:EnableReplication",
                "cloudfront:UpdateDistribution",
                "s3:GetObject",
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents",
                "logs:DescribeLogStreams"
            ],
            "Resource": "*"
        }
    ]
}
</code></pre>
<ul>
<li>역할 생성</li>
</ul>
<ol>
<li><strong>역할 만들기</strong>를 선택합니다.</li>
<li>&#8216;이 역할을 사용할 서비스&#8217;로 <strong>Lambda</strong>를 선택합니다.</li>
<li>목록 중 위에서 생성한 정책 <strong>ResizingImages</strong>를 선택합니다.</li>
<li>역할의 이름(ResizingImages)과 설명을 작성합니다.</li>
<li><strong>역할 만들기</strong>버튼을 클릭합니다.</li>
</ol>
<ul>
<li>신뢰 관계(정책) 수정</li>
</ul>
<p>서비스 보안 주체 <code>lambda.amazonaws.com</code> 및 <code>edgelambda.amazonaws.com</code>에 권한을 위임하기 위해 IAM 역할을 수정합니다.</p>
<ol>
<li>나의 역할 목록에서 생성했던 <strong>ResizingImages</strong>를 선택합니다</li>
<li><strong>신뢰 관계</strong> 탭의 <strong>신뢰 관계 편집</strong>을 선택합니다.</li>
<li>아래의 정보를 입력합니다.</li>
<li><strong>업데이트</strong> 버튼을 클릭합니다.</li>
</ol>
<pre><code class="line-numbers">{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "edgelambda.amazonaws.com",
          "lambda.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
</code></pre>
<h3>2-2. AWS Lambda@Edge 생성하기</h3>
<ol>
<li>리전은 <strong>미국 동부(버지니아 북부) /us-east-1</strong> 만 허용 됩니다.</li>
<li><strong>함수 생성</strong> 버튼을 클릭합니다.</li>
<li><strong>함수 이름(ResizingImages)</strong> 를 입력합니다.</li>
<li>런타입(<strong>Node.js 10.x</strong>)를 선택합니다.</li>
<li><strong>실행 역할 선택 또는 생성</strong>
<ul>
<li>실행 역할 : 기존 역할 사용</li>
<li>기존 역할 : ResizingImages</li>
</ul>
</li>
<li><strong>함수 생성</strong> 버튼을 클릭합니다.</li>
<li>제한 시간을 <strong>3초</strong>로 설정하면 최초 요청(Cache miss)에 연산이 많아지면 연산이 되지 않을 수 있으니, <strong>10초</strong>로 설정합니다.</li>
<li><strong>저장</strong> 버튼을 클릭합니다.</li>
</ol>
<h3>2-3. Cloud 9 을 이용한 Lambda 함수 작성</h3>
<p>개발의 편의성을 위해서 AWS에서 제공해주는 <code>IDE</code>툴인 Cloud 9 을 사용해보도록 하겠습니다.</p>
<p>람다 코드를 작성하기 위해 새로운 Cloud 9 환경을 설정합니다.</p>
<ol>
<li><strong>Create environment</strong>를 선택합니다.</li>
<li>Name environment의 Name(ResizingImages)과 Description을 입력합니다.</li>
<li>다음과 같이 Configure settings를 설정합니다.
<ul>
<li>Create a new instance for environment (EC2)</li>
<li>t2.micro (1 GiB RAM + 1 vCPU)</li>
<li>Amazon Linux</li>
<li>After 30 minutes (default)</li>
</ul>
</li>
<li><strong>Create environment</strong>를 클릭합니다.</li>
</ol>
<p>약 5분 정도 기다리게 되면, IDE화면이 노출되고 하단부에는 Terminal까지 켜지게 됩니다. 임시 EC2를 생성하게 된것이고, 기존에 EC2를 생성하게 되면 SG부터 접속까지 이러저러한 불편을 없애준 서비스라고 보시면 됩니다.</p>
<ol>
<li>화면 오른쪽 위 메뉴중 <strong>AWS Resources</strong>를 선택합니다.</p>
</li>
<li>mbda(us-east-1)/<code>Remote Functions</code> 목록의 <code>ResizingImages</code>를 <code>Import</code>합니다.</p>
</li>
<li>불러온 람다 함수로 접근하기 위해 터미널(Terminal)을 이용합니다.(
<pre><code class="line-numbers">package.json
</code></pre>
<p>을 생성하고 Sharp 모듈을 설치합니다.)</p>
<ol>
<li><code>$ cd ResizingImages</code></li>
<li><code>$ npm init -y</code></li>
<li><code>$ npm i sharp</code></li>
</ol>
</li>
<li><code>index.js</code>을 아래 코드와 같이 수정합니다.</p>
</li>
<li>작성한 람다 함수를 $LATEST 버전으로 배포합니다.</p>
</li>
</ol>
<ul>
<li>Lambda(us-east-1)/<code>Local Functions</code> 목록의 <code>ResizingImages</code>를 <code>Deploy</code>합니다.</li>
</ul>
<p>[람다 소스]</p>
<pre><code class="line-numbers">'use strict';

const querystring = require('querystring'); // Don't install.
const AWS = require('aws-sdk'); // Don't install.
const Sharp = require('sharp');

const S3 = new AWS.S3({
  region: '<YOUR_BUCKET_REGION>'
});
const BUCKET = '<YOUR_BUCKET_NAME>';

exports.handler = async (event, context, callback) => {
  const { request, response } = event.Records[0].cf;
  // Parameters are w, h, f, q and indicate width, height, format and quality.
  const params = querystring.parse(request.querystring);

  // Required width or height value.
  if (!params.w && !params.h) {
    return callback(null, response);
  }

  // Extract name and format.
  const { uri } = request;
  const [, imageName, extension] = uri.match(/\/?(.*)\.(.*)/);

  // Init variables
  let width;
  let height;
  let format;
  let quality; // Sharp는 이미지 포맷에 따라서 품질(quality)의 기본값이 다릅니다.
  let s3Object;
  let resizedImage;

  // Init sizes.
  width = parseInt(params.w, 10) ? parseInt(params.w, 10) : null;
  height = parseInt(params.h, 10) ? parseInt(params.h, 10) : null;

  // Init quality.
  if (parseInt(params.q, 10)) {
    quality = parseInt(params.q, 10);
  }

  // Init format.
  format = params.f ? params.f : extension;
  format = format === 'jpg' ? 'jpeg' : format;

  // For AWS CloudWatch.
  console.log(`parmas: ${JSON.stringify(params)}`); // Cannot convert object to primitive value.
  console.log(`name: ${imageName}.${extension}`); // Favicon error, if name is `favicon.ico`.

  try {
    s3Object = await S3.getObject({
      Bucket: BUCKET,
      Key: decodeURI(imageName + '.' + extension)
    }).promise();
  } catch (error) {
    console.log('S3.getObject: ', error);
    return callback(error);
  }

  try {
    resizedImage = await Sharp(s3Object.Body)
      .resize(width, height)
      .toFormat(format, {
        quality
      })
      .toBuffer();
  } catch (error) {
    console.log('Sharp: ', error);
    return callback(error);
  }

  const resizedImageByteLength = Buffer.byteLength(resizedImage, 'base64');
  console.log('byteLength: ', resizedImageByteLength);

  // `response.body`가 변경된 경우 1MB까지만 허용됩니다.
  if (resizedImageByteLength >= 1 * 1024 * 1024) {
    return callback(null, response);
  }

  response.status = 200;
  response.body = resizedImage.toString('base64');
  response.bodyEncoding = 'base64';
  response.headers['content-type'] = [
    {
      key: 'Content-Type',
      value: `image/${format}`
    }
  ];
  return callback(null, response);
};
</code></pre>
<h2>3. CloudFront 옵션 변경</h2>
<p>필자는 기존에 CloudFront까지는 생성해두고, Distribution을 수행하여 테스트까지 마친 상태였습니다.</p>
<ol>
<li>CloudFonrt로 이동해 해당 Distribution을 선택합니다.</li>
<li><strong>Behaviors</strong> 탭에서 <strong>Create Behavior</strong>를 선택합니다.</li>
<li>다음과 같이 수정합니다.</li>
</ol>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/04/aws_lambda_edge_6.png?w=1200&#038;ssl=1" alt="Reactjs AWS Lambda@Edge 이미지 리사이징 설명 이미지 5" /></p>
<p>2번째, 3번째 박스에서 보시면</p>
<p>리소스를 캐싱할때 쿼리스트링을 분리해서 캐싱하는 것이고, 쿼리스트링 내용은(w:너비, h:높이, q:품질, f:포맷) 에 대한 내용입니다.</p>
<h2>4. 람다 새 버전 게시</h2>
<p>이제 람다엣지를 생성하였고, 클라우드 프론트까지 준비가 되었으니, 실제 엣지로 람다를 배포하고, 클라우드 프론트와 연결하여 사용하면 됩니다.</p>
<ol>
<li>Lambda 탭으로 이동합니다.</li>
<li>함수 목록에서 <code>ResizingImages</code>를 선택합니다.</li>
<li>오른쪽 위 메뉴 중 ‘작업’의 <code>새 버전 게시</code>를 선택합니다.</li>
<li>‘$LATEST의 새 버전 게시’의 ‘버전 설명’을 입력하고 새로운 버전을 <code>게시</code>합니다.</li>
<li>게시된 새 버전의 ARN 복사(<code>ARN - arn:aws:lambda~~~:ResizingImages:1</code>, 화면 오른쪽 위)하여 CloudFront에 연결해야 합니다.
</li>
<li>
<p>CloudFront로 이동해 해당 Distribution을 선택합니다.</p>
</li>
<li><code>Behaviors</code> 탭에서 기본 Behavior를 체크하고 <code>Edit</code>를 선택합니다.</li>
<li>다음과 같이 수정 후 <strong>Yes, Edit</strong> 버튼을 클릭합니다.
<ul>
<li>Lambda Function Associations:
<ul>
<li>Lambda Function ARN: Lambda 함수에서 복사한 ARN 입력(<code>arn:aws:lambda~~~:ResizingImages:1</code>)</li>
</ul>
</li>
</ul>
</li>
</ol>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/04/aws_lambda_edge_7.png?w=1200&#038;ssl=1" alt="Reactjs AWS Lambda@Edge 이미지 리사이징 설명 이미지 6" /></p>
<h2>5. 테스트</h2>
<p>최종적인 아키텍처는 다음과 같습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/04/aws_lambda_edge_11.png?w=1200&#038;ssl=1" alt="Reactjs AWS Lambda@Edge 이미지 리사이징 설명 이미지 7" /></p>
<p>최초 사용자는 Domain을 통해서 요청을 하게 되고 (Route53)에 의해 CloudFront쪽으로 요청이 진행됩니다. 그럼 CloudFront에서는 Cache Layer로서 동작을 하고, 없으면 Origin(S3)에서 원본을 가져옵니다. 이때 Origin Response를 돌아오면서 <strong>Lambda@Edge</strong>를 거치고, Resizing된 이미지를 Cache Layer에 가져다 둡니다.</p>
<p>5-10분후에 클라우드 프론트 변경내용이 Deployed 상태로 변경이 되면, 모든 작업은 끝이 났습니다. 캐시 되기 전에 S3 오리진에 직접 호출한 내용과 CloudFront를 호출하여 호출한 내용에 대한 차이는 다음과 같습니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/04/aws_lambda_edge_8.png?w=1200&#038;ssl=1" alt="Reactjs AWS Lambda@Edge 이미지 리사이징 설명 이미지 8" /></p>
<p><strong>원본 최초 호출시 : 17.4kb</strong></p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/04/aws_lambda_edge_9.png?w=1200&#038;ssl=1" alt="Reactjs AWS Lambda@Edge 이미지 리사이징 설명 이미지 9" /></p>
<p><strong>람다 엣지 최초 호출시 : 1.4kb</strong></p>
<h2>6. 마치며&#8230;</h2>
<p>이번시간에는 람다 엣제를 통한 온디멘드 이미지 리사이징에 대해서 정리해봤습니다. 확실히 아마존에서는 여러가지 고민을 많이 하고 서비스를 만들어 내는것 같습니다. 개발자입장에서는 잘 만들어진 서비스를 가져다가 붙이기만 하면되니 훨씬 편해진 것 같습니다.</p>
<p>만약, 리사이징에 대하여 직접 구현하려면 서버도 생성하고, 개발환경도 셋팅하고 코딩도 해야되고 할 것이 엄청 많은데, 간단하게 코딩에만 집중하여 서버리스로 구현하니, 생산성도 엄청 증가한 것 같습니다.</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/04/21/lambda-edge-guide/">[Reactjs] AWS Lambda@Edge 이미지 리사이징</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/04/21/lambda-edge-guide/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1153</post-id>	</item>
	</channel>
</rss>
