<?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>Linux &#8211; WONIZZ.LOG</title>
	<atom:link href="https://blog.wonizz.com/category/tech/linux/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.wonizz.com</link>
	<description>DEVELOPMENT &#38; LIFE LOG</description>
	<lastBuildDate>Fri, 21 Aug 2026 15:45:41 +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>Linux &#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] Nginx Lua module 사용법</title>
		<link>https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/</link>
					<comments>https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/#respond</comments>
		
		<dc:creator><![CDATA[워니]]></dc:creator>
		<pubDate>Thu, 18 Jul 2024 06:09:28 +0000</pubDate>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[Linux]]></category>
		<guid isPermaLink="false">https://blog.wonizz.com/?p=2248</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 nginx lua module에 대해서 정리를 해보도록 하겠습니다. lua script는 이전에 nginx 관련 세미나를 들으면서 알게 됐던 내용인데요. nginx의 config에 마치 개발 코드를 작성하듯 script를 넣어서 제어할 수 있는 부분이 꽤나 인상적이였습니다. 필자의 회사에서도 nginx의 lua script를 통해서 제어가 필요한 요청을 받았습니다. 이를 해결하고자 lua module 탑재를 진행하게 됐습니다. Nginx에 관한&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/">[DevOps] Nginx Lua module 사용법</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>nginx lua module</strong>에 대해서 정리를 해보도록 하겠습니다. lua script는 이전에 nginx 관련 세미나를 들으면서 알게 됐던 내용인데요. nginx의 config에 마치 개발 코드를 작성하듯 script를 넣어서 제어할 수 있는 부분이 꽤나 인상적이였습니다.</p>
<p>필자의 회사에서도 nginx의 lua script를 통해서 제어가 필요한 요청을 받았습니다. 이를 해결하고자 lua module 탑재를 진행하게 됐습니다.</p>
<p>Nginx에 관한 시리즈 포스팅은 아래에서 확인이 가능합니다.</p>
<ul>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/02/09/devops-nginx-compile-installation/">[DevOps] Nginx 컴파일 설치</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/">[DevOps] ansible nginx config 배포 구성</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/08/10/linux-logrotate/">[DevOps] Nginx Logrotation 설정</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/08/17/devops-nginx-geoip-module/">[DevOps] Nginx GeoIP 모듈 적용</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/10/19/devops-nginx-log-aggregation-dashboard/">[DevOps] Nginx Log Aggregation &#038; Dashboard</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/">[DevOps] Nginx Lua module 사용법</a>
  </li>
</ul>
<h2>1. Nginx Lua module 이란?</h2>
<p><strong>lua-nginx-module</strong>은 Nginx에 Lua 스크립팅 기능을 추가하는 모듈입니다. 이를 통해 Nginx의 요청 처리 흐름에 Lua 코드를 삽입하여 다양한 작업을 수행할 수 있습니다. OpenResty 프로젝트의 일부로, 고성능 웹 애플리케이션을 구축하는 데 유용합니다.</p>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2024/07/nginx_lua_1.png?w=1200&#038;ssl=1" alt="DevOps Nginx Lua module 사용법" /></p>
<h3>주요 기능</h3>
<ul>
<li>동적 컨텐츠 생성: Lua 스크립트를 사용하여 요청에 대한 동적 응답을 생성할 수 있습니다.</li>
<li>고급 접근 제어 : 요청 헤더, 쿠키, IP 주소 등을 기반으로 접근 제어 로직을 구현할 수 있습니다.</li>
<li>응답 필터링 및 수정 : 응답 본문을 필터링 하거나 수정할 수 있습니다.</li>
<li>복잡한 인증 및 인가 : 외부 인증 서버와 통신하여 복잡한 인증 및 인가 로직을 구현할 수 있습니다.</li>
<li>로깅 및 모니터링 : 맞춤 로깅 메커니즘을 구현하고, 실시간 트래픽 모니터링 데이터를 수집할 수 있습니다.</li>
</ul>
<p>공식 github은 아래에서 확인이 가능합니다.</p>
<p><a class="wp-editor-md-post-content-link" href="https://github.com/openresty/lua-nginx-module" target="_blank" rel="noopener">openresty / lua-nginx-module</a></p>
<h2>2. Nginx Lua module 설치</h2>
<p>필자는 nginx를 직접 compile 해서 사용하고 있습니다. container 기반에 이미 만들어진 이미지를 활용하는것이 훨씬 효율적일 수 있습니다. 필자는 custom module을 추가함에 있어 자유도가 있기 때문에 native로 운영중에 있습니다.</p>
<p>그럼 본격적으로 각 스텝별로 설치 가이드를 작성해보겠습니다.</p>
<ul>
<li>LuaJIT 설치
<ul>
<li><code>lua-nginx-module</code>을 사용하기 위해선, LuaJIT 또는 Lua 5.1 이상이 필요합니다. LuaJIT를 사용하는 것이 일반적으로 권장되며, 성능상의 이점이 있습니다.</li>
</ul>
</li>
</ul>
<pre><code class="language-bash line-numbers"># LuaJIT-2.0.5 설치
wget http://luajit.org/download/LuaJIT-2.0.5.tar.gz
wget https://line-objects-internal.com/fileshare/logs/LuaJIT-2.0.5.tar.gz

# 압축 해제 및 설치
tar -xvzf LuaJIT-2.0.5.tar.gz
cd LuaJIT-2.0.5
make
make install

# LuaJIT 설치 후, LuaJIT 라이브러리 경로를 시스템 라이브러리 경로에 추가
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
luajit -v
</code></pre>
<ul>
<li>Nginx와 <code>ngx_devel_kit</code> (NDK)</li>
</ul>
<pre><code class="language-bash line-numbers"># NDK 설치 
wget https://github.com/simplresty/ngx_devel_kit/archive/v0.3.1.tar.gz
tar -zxvf v0.3.1.tar.gz
</code></pre>
<ul>
<li><code>lua-resty-core</code>와 <code>lua-resty-lrucache</code>를 설치</li>
</ul>
<pre><code class="language-bash line-numbers"># lua-resty-core 설치
git clone https://github.com/openresty/lua-resty-core.git
cd lua-resty-core
make install

# lua-resty-lrucache 설치
git clone https://github.com/openresty/lua-resty-lrucache.git
cd lua-resty-lrucache
make install
</code></pre>
<ul>
<li><code>lua-nginx-module</code> 설치</li>
</ul>
<pre><code class="language-bash line-numbers"># lua module 다운로드
git clone https://github.com/openresty/lua-nginx-module.git
</code></pre>
<p>위의 작업들은 사전에 필요한 라이브러리 및 모듈을 다운로드, 설치 하는 과정에 대해서 설명했습니다.</p>
<p>이제 본격적으로 Nginx를 re-compile을 수행하여 module을 탑재합니다.</p>
<ul>
<li>Nginx Compile</li>
</ul>
<pre><code class="language-bash line-numbers">export LUAJIT_LIB=/usr/local/lib
export LUAJIT_INC=/usr/local/include/luajit-2.0

# Version Info
NGINX_VERSION=1.20.1
PCRE_VERSION=8.44
OPENSSL_VERSION=1.1.1l
ZLIB_VERSION=1.2.11
NGINX_PATH=/home1/irteam/apps/nginx-${NGINX_VERSION}


# Nginx Compile
./configure --prefix=${NGINX_PATH} \
    --user=irteamsu --group=irteamsu \
    --with-http_ssl_module \
    --with-http_stub_status_module \
    --with-http_realip_module \
    --with-http_v2_module \
    --add-dynamic-module=/pkgs/ngx_http_geoip2_module \
    --with-ld-opt="-Wl,-rpath,/usr/local/lib -lpcre" \
    --add-dynamic-module=/pkgs/lua-nginx-module \
    --add-dynamic-module=/pkgs/ngx_devel_kit-0.3.1 \
    --with-pcre=/pkgs/pcre-${PCRE_VERSION} \
    --with-openssl=/pkgs/openssl-${OPENSSL_VERSION} \
    --with-zlib=/pkgs/zlib-${ZLIB_VERSION}

# Nginx Install
make -j2
make install
</code></pre>
<h2>3. Nginx Config 수정</h2>
<p>위의 과정을 통해서 nginx binary에 lua module을 탑재했습니다. lua module을 사용할 수 있도록 import 합니다.</p>
<pre><code class="language-bash line-numbers"># add necessary `lua_package_path` directive to `nginx.conf`, in the http context
load_module modules/ndk_http_module.so;
load_module modules/ngx_http_lua_module.so;

events {
    worker_connections  3000;
}

http {
    lua_package_path "/usr/local/lib/lua/?.lua;;";
    ....
}
</code></pre>
<p>적용을 하면서 여러가지 이슈 사항들을 겪었습니다. 그 내용에 대해서 정리를 해보겠습니다.</p>
<h3>설치시 발생한 이슈</h3>
<ol>
<li>설치시 환경 변수 셋팅
<pre><code class="language-bash line-numbers"># 오류 내용
adding module in /usr/local/src/ngx_devel_kit-0.3.1
+ ngx_devel_kit was configured
adding module in /usr/local/src/lua-nginx-module-0.10.19
checking for LuaJIT 2.x ... not found
   ./configure: error: unsupported LuaJIT version; ngx_http_lua_module requires LuaJIT 2.x.
</code></pre>
<p>nginx를 컴파일하고 설치를 했더니 위와 같은 오류가 발생했습니다. LuaJIT이 필요하다는 내용인데요. 분명히 LuaJIT을 설치했지만 찾을 수 없는 것 같았습니다.</p>
</li>
</ol>
<ul>
<li>Resolve Ref : https://forum.openresty.us/d/6494-ngx-http-lua-module-requires-luajit-2x
<pre><code class="language-bash line-numbers"># nginx compile 시에 환경 변수 설정. 
export LUAJIT_LIB=/usr/local/lib
export LUAJIT_INC=/usr/local/include/luajit-2.0
</code></pre>
</li>
</ul>
<ol start="2">
<li>PCRE 옵션 설정
<pre><code class="language-bash line-numbers"># 오류 내용
/tmp/nginx.lJpu0R.ltrans10.ltrans.o:<artificial>:function ngx_http_lua_log_by_chunk: error: undefined reference to 'pcre_malloc'
/tmp/nginx.lJpu0R.ltrans10.ltrans.o:<artificial>:function ngx_http_lua_log_by_chunk: error: undefined reference to 'pcre_free'
/tmp/nginx.lJpu0R.ltrans10.ltrans.o:<artificial>:function ngx_http_lua_log_by_chunk: error: undefined reference to 'pcre_malloc'
/tmp/nginx.lJpu0R.ltrans10.ltrans.o:<artificial>:function ngx_http_lua_log_by_chunk: error: undefined reference to 'pcre_free'
/tmp/nginx.lJpu0R.ltrans10.ltrans.o:<artificial>:function ngx_http_lua_body_filter_by_chunk: error: undefined reference to 'pcre_malloc'
/tmp/nginx.lJpu0R.ltrans10.ltrans.o:<artificial>:function ngx_http_lua_body_filter_by_chunk: error: undefined reference to 'pcre_free'
</code></pre>
<p>pcre와 관련된 내용의 오류가 발생했습니다. Nginx Compile 과정에서 pcre를 적절하게 시스템에서 사용할 수 있도록 link를 해야된다는 것을 알았습니다. 다음의 옵션값으로 설치를 진행합니다.</p>
</li>
</ol>
<ul>
<li>Resolve Ref : https://github.com/openresty/lua-nginx-module/issues/1984
<pre><code class="language-bash line-numbers"># pcre 링크 설정
--with-ld-opt="-Wl,-rpath,/usr/local/lib -lpcre"
</code></pre>
</li>
</ul>
<ol>
<li><code>-Wl,-rpath,/usr/local/lib</code>: 실행 시간(runtime) 라이브러리 검색 경로를 <code>/usr/local/lib</code>으로 설정합니다. 이는 동적 라이브러리(.so 파일)를 로드할 때 사용됩니다.</li>
<li><code>-lpcre</code>: PCRE(Perl Compatible Regular Expressions) 라이브러리를 링크합니다. 이는 Nginx의 정규 표현식 처리 기능을 위해 필요합니다.
<ol start="3">
<li>Package Path 설정</li>
</ol>
<pre><code class="language-bash line-numbers"># 오류 내용
nginx: [error] lua_load_resty_core failed to load the resty.core module
</code></pre>
<p>nginx에서 module을 로딩할 수 없다는 내용입니다. config 설정에서 모듈을 불러 올 수 있도록 설정합니다.</p>
</li>
</ol>
<ul>
<li>Resolve Ref : https://github.com/openresty/lua-nginx-module/issues/1533
<pre><code class="language-bash line-numbers"># module 로딩 
http {
   lua_package_path "/usr/local/lib/lua/?.lua;;";
}
</code></pre>
</li>
</ul>
<h2>3. Nginx Lua script 예제</h2>
<p>처음에 lua module을 탑재하게 된 계기는 403 status code를 200으로 전환이 가능한지에서부터 시작했습니다. 개발팀의 특정 상황으로 인해서 어쩔 수 없이 403 code를 반환하는 상황이 있었습니다. 이를 200으로 전환하여 google로 하여금 seo indexing이 되도록 설정하고자 해습니다.</p>
<p>기본적인 Nginx에서는 status code를 변조하는것을 허락하지 않습니다. 이를 lua script를 통해서 변경했고 다음과 같이 config 설정을 작성했습니다.</p>
<pre><code class="language-bash line-numbers">location / {
    resolver xxx.xxx.xxx.xxx valid=600s;        
    proxy_pass https://$backend;
    proxy_next_upstream error timeout;
    proxy_redirect off;
    proxy_connect_timeout 2s;

    # response header를 변조합니다. 
    header_filter_by_lua_block {
        # .json 확장자에 대해서는 예외처리
        if ngx.var.uri:match("%.json$") then
            return
        end

        local content_type = ngx.header["Content-Type"]
        if content_type and content_type:match("text/html") then
            if ngx.status == 403 then
                # status code를 200으로 반환
                ngx.status = 200
            end
        end
    }
...
}
</code></pre>
<p>위의 내용을 통해서 적절하게 status code를 변경할 수 있었습니다. 이 외에도 다양한 활용 사례들이 있습니다. 이는 다음번 포스팅에서 작성을 해보도록 하겠습니다.</p>
<h2>4. 마치며&#8230;</h2>
<p>Nginx는 정말 웹서버 이상으로 강력한 활용 사례가 있다고 생각합니다. 이번에는 lua module을 통해서 header 제어에 대해서 확인을 했지만, 다음번에는 다양한 활용 사례에 대해서도 포스팅을 해보겠습니다.</p>
<p>또한, Nginx에는 유용한 모듈들이 많기 때문에 이러한 부분들에 대해서도 확인하고 학습하면 좋을 것 같다는 생각을 해봤습니다. 이상으로 포스팅을 마칩니다. 감사합니다.</p>
<h2>5. 참고</h2>
<p>https://www.jacobbaek.com/1369</p>
<p>https://byeong-gook.tistory.com/64</p>
<p>https://blog.naver.com/n_cloudplatform/222182688666</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/">[DevOps] Nginx Lua module 사용법</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2248</post-id>	</item>
		<item>
		<title>[DevOps] Nginx Logrotation 설정</title>
		<link>https://blog.wonizz.com/2023/08/10/linux-logrotate/</link>
					<comments>https://blog.wonizz.com/2023/08/10/linux-logrotate/#respond</comments>
		
		<dc:creator><![CDATA[워니]]></dc:creator>
		<pubDate>Thu, 10 Aug 2023 09:23:01 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=2051</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>안녕하세요? 정리하는 개발자 워니즈 입니다. 웹 서버를 운영하다보면, 로그 파일들이 무분별하게 쌓이는 문제가 있습니다. 이를 정리하기 위해서는 logrotation이라는 프로그램을 이용해야 하는데요. logrotation을 어떻게 설정하고 어떤식으로 활용하는지에 대해서 정리를 해보도록 하겠습니다. Nginx에 관한 시리즈 포스팅은 아래에서 확인이 가능합니다. [DevOps] Nginx 컴파일 설치 [DevOps] ansible nginx config 배포 구성 [DevOps] Nginx Logrotation 설정 [DevOps] Nginx GeoIP 모듈&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2023/08/10/linux-logrotate/">[DevOps] Nginx Logrotation 설정</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>logrotation</strong>이라는 프로그램을 이용해야 하는데요. logrotation을 어떻게 설정하고 어떤식으로 활용하는지에 대해서 정리를 해보도록 하겠습니다.</p>
<p>Nginx에 관한 시리즈 포스팅은 아래에서 확인이 가능합니다.</p>
<ul>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/02/09/devops-nginx-compile-installation/">[DevOps] Nginx 컴파일 설치</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/">[DevOps] ansible nginx config 배포 구성</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/08/10/linux-logrotate/">[DevOps] Nginx Logrotation 설정</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/08/17/devops-nginx-geoip-module/">[DevOps] Nginx GeoIP 모듈 적용</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/10/19/devops-nginx-log-aggregation-dashboard/">[DevOps] Nginx Log Aggregation &#038; Dashboard</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/">[DevOps] Nginx Lua module 사용법</a>
  </li>
</ul>
<h2>1. Logrotation 이란?</h2>
<p>간단하게 리눅스에서 사용할 수 있는 프로그램.</p>
<p>Logrotatefㅡㄹ 사용하면 특정 폴더에 쌓이는 로그를 날짜 별로 나누어서 관리를 할 수 있으며, 기준을 정하면 해당일 이전 로그는 삭제하여 시스템 용량을 낭비하지 않을 수 있습니다.</p>
<h3>Logrotate 구조</h3>
<ul>
<li>/etc/logrotate.conf : 로그 로테이트의 기본 설정 파일
<p>기본 설정 : log는 주 단위로 백업 -> 4주동안 보관</p>
<pre><code class="language-bash line-numbers"># see "man logrotate" for details
# rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4

# create new (empty) log files after rotating old ones
create

# use date as a suffix of the rotated file
dateext

# uncomment this if you want your log files compressed
#compress

# RPM packages drop log rotation information into this directory
include /etc/logrotate.d

# no packages own wtmp and btmp -- we'll rotate them here
/var/log/wtmp {
  monthly
  create 0664 root utmp
      minsize 1M
  rotate 1
}

/var/log/btmp {
  missingok
  monthly
  create 0600 root utmp
  rotate 1
}

# system-specific logs may be also be configured here.
</code></pre>
</li>
<li>/etc/logrotate.d/ : 로그 로테이트의 개별 설정 파일이 들어있는 폴더
<pre><code class="language-bash line-numbers">## syslog 예시
/var/log/cron
/var/log/maillog
/var/log/messages
/var/log/secure
/var/log/spooler
{
  missingok
  sharedscripts
  postrotate
      /bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true
  endscript
}

## custom 예시
## test.txt를 rotation할시에 data.json파일도 강제적으로 날짜별 copy를 수행
/home1/test/apps/devops/logs/test.txt {
  daily
    missingok
  copytruncate
  dateext
  notifempty
  postrotate
      cp -p /home1/test/apps/devops/logs/data.json /home1/test/apps/devops/logs/data.json-`date +%Y%m%d.%H%M%S`
  endscript
}
</code></pre>
</li>
<li>/etc/cron.daily/logrotate : 로그 로테이트 작업 내역 로그</p>
</li>
</ul>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.tk/wp-content/uploads/2023/08/logrotation_1.png?w=1200" alt="DevOps Nginx Logrotation 설정" /></p>
<h2>2. Logrotation 설정 방법</h2>
<p>필자는 nginx log에 대해서 rotation설정을 진행했습니다.</p>
<ul>
<li>nginx logrotation 설정</li>
</ul>
<pre><code class="language-bash line-numbers">/apps/nginx-1.20.1/logs/access_log {
        daily
        missingok
        rotate 7
        compress
        delaycompress
        notifempty
        create 640 root root
        sharedscripts
        postrotate
                if [ -f /var/run/nginx.pid ]; then
                        kill -USR1 `cat /var/run/nginx.pid`
                fi
        endscript
}
</code></pre>
<p>1️⃣ 로그 정리 대상 파일 : /apps/nginx-1.20.1/logs/access_log<br />
2️⃣ daily : daily(매일), weekly(매주), monthly(매달), yearly(매년) 순환<br />
3️⃣ missingok : 로그파일이 없을 경우에도 에러로 처리하지 않음<br />
4️⃣ rotate 7 : rotate 파일 갯 수<br />
5️⃣ compress : 순환된 로그파일 압축(gz)<br />
6️⃣ delaycompress : 최근파일 외 전부 압축<br />
7️⃣ notifempty : 로그파일이 제로인 경우 rotation하지 않음<br />
8️⃣ sharedscripts : prerotate, postrotate 스크립트를 한번만 실행<br />
9️⃣ postrotate : 로그파일 분할 후 실행할 script 지정 ( nginx 의 경우 SIGUSR1 을 받으면 로그 파일을 새로 읽으므로 새로 만들어진 로그 파일에 로그를 기록합니다. )<br />
🔟 copytruncate : 대부분의 어플리케이션들은 SIGTERM을 받으면, 로그파일을 새로 만듭니다. copytruncate를 이용하면 원본파일을 지우지 않고, truncate(파일 크기를 0으로 만든다)한다.</p>
<h2>3. Logrotation 설정 테스트</h2>
<p>로그 로테이션 설정을 진행하고나서 설정 테스트를 하기 위해서는 아래와 같이 테스트를 진행합니다.</p>
<pre><code class="language-bash line-numbers">logrotate -d -f /etc/logrotate.d/nginx
</code></pre>
<ul>
<li>-d, &#8211;debug : 디버그 모드, 실제 로그 파일을 변경하지는 않고 처리 과정만 표시합니다.</li>
</ul>
<h1>참고</h1>
<ul>
<li><a class="wp-editor-md-post-content-link" href="https://www.lesstif.com/system-admin/nginx-log-rotate-logrotate-75956229.html" target="_blank" rel="noopener">nginx log를 rotate 해서 일자별로 관리(logrotate)</a></li>
<li><a class="wp-editor-md-post-content-link" href="https://www.wp-vps.com/logrotate이용하여-nginx-로그파일-분할관리하기.html" target="_blank" rel="noopener">logrotate이용하여 nginx 로그파일 분할관리하기</a></li>
<li><a class="wp-editor-md-post-content-link" href="https://www.joinc.co.kr/w/man/12/logrotate" target="_blank" rel="noopener">logrotate를 이용한 로그 파일 관리</a></li>
<li><a class="wp-editor-md-post-content-link" href="https://sailing-blog.com/6033" target="_blank" rel="noopener">로그관리 Logrotate</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2023/08/10/linux-logrotate/">[DevOps] Nginx Logrotation 설정</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2023/08/10/linux-logrotate/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2051</post-id>	</item>
		<item>
		<title>[DevOps] 주로 사용하는 Nginx 설정</title>
		<link>https://blog.wonizz.com/2023/07/03/devops-nginx-configuration/</link>
					<comments>https://blog.wonizz.com/2023/07/03/devops-nginx-configuration/#respond</comments>
		
		<dc:creator><![CDATA[워니]]></dc:creator>
		<pubDate>Mon, 03 Jul 2023 01:34:23 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=2046</guid>

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

필자가 속한 프로젝트에서는 FE에 대한 서버를 Nginx로 사용하고 있습니다. Nginx에 index.html을 서빙하는 방식으로 이용하고 있습니다.

그러다보니 Nginx에 대한 셋팅 혹은 설정을 많이 하게 되는데 주로 사용하는 것들에 대해서 정리를 해두어서 참고하고자 합니다.

<h2>1. nginx.conf 설정</h2>

<h3>worker_process</h3>

nginx의 실행 가능한 worker 프로세스의 수를 지정해 줄 수 있습니다. nginx는 master와 worker 프로세스로 구성이 되는데요.

공식문서에 의하면, 최적값은 <strong>cpu core</strong>를 사용하라고 권고 하고 있습니다.

<pre><code class="line-numbers">worker_processes        4; # number of CPU cores
</code></pre>

<h3>worker_rlimit_nofile</h3>

worker process들에서 최대로 열린 파일들의 수를 제한 할 수 있습니다. 이 수가 클 수록 메인 프로세스를 재시작 할 필요가 없어진다고 합니다. 하지만 너무 많은 수의 파일이 열려있으면, 서버에 부하를 발생시킵니다.

<pre><code class="line-numbers">worker_rlimit_nofile    20000; # sockets, fds per worker process
</code></pre>

<h3>events 블록 &#8211; worker_connections</h3>

Proxy 서버를 통해 연결된 커넥션들을 포함한 클라이언트들의 모든 커넥션들의 숫자를 고려해야 합니다. worker_rlimit_nofile의 값을 넘어서는 안된다.

<pre><code class="line-numbers">events {
    worker_connections  3000; # total supported connection : 4 x 3000 = 12000
}
</code></pre>

<h2>2. http 블록</h2>

<h3>Include &#038; default_type</h3>

core_module에 있는 설정으로, include는 다른 파일을 가져올 수 있습니다. 아래의 mime.types와 같이 위에서 정의한 types를 파일로 빼내서, include지시어를 이용해 가져올 수 있습니다.

아래에서는 types의 default_type도 정의해 주었습니다.

<pre><code class="line-numbers">include       mime.types;
default_type  application/octet-stream;
</code></pre>

<h3>keepalive</h3>

한번 맺어 놓은 연결에 대해서는 keepalive timeout 시점까지는 연결을 지속적으로 허용해두는 설정입니다. 서버를 사용하지 않는 혹은 못하는 Connection까지 모두 keep 하고 있으므로 자원의 손실이 발생하게 됩니다.

<pre><code class="line-numbers">keepalive_timeout   30s;
keepalive_requests  128; 
</code></pre>

<h3>client_body_timeout</h3>

client의 request body를 읽을 때의 timeout을 정의합니다. 기본값은 60s로 되어 있습니다.

<pre><code class="line-numbers"># timeout for client
client_body_timeout     3s;
client_header_timeout   3s;
client_max_body_size    1m;
</code></pre>

<h3>send_timeout</h3>

client에게 response를 전송할 떄의 timeout값을 설정합니다. client가 아무것도 받지 못하면, connection이 closed 됩니다. 기본값은 60초로 되어있습니다.

<pre><code class="line-numbers">send_timeout            3s;
</code></pre>

<h2>3. Server 블록</h2>

<h3>server</h3>

server_name은 가상 서버의 이름을 정할 때 사용합니다. 아래는 80 port로 접속시 443으로 전환 시켜주는 내용입니다.

<pre><code class="line-numbers">server {
    listen 80;
    server_name test.store.com;
    rewrite ^(.*) https://test.store.com$1 permanent;
}
</code></pre>

<h3>Location 우선순위</h3>

nginx에서 가장 중요한 부분입니다. request URI에 따른 설정을 하는 곳입니다. URI에 대한 매칭은 텍스트 값을 prefix로 하여서 매칭하거나 주어진 정규식을 이용해서 매칭할 수 있습니다.

<table>
<thead>
<tr>
  <th>=</th>
  <th>패턴과 정확하게 일치 할 때 사용. URI검색시 가장 우선순위가 높습니다. $host정보에 /test.png로 정확하게 매치가 될 때 사용합니다. 하지만, 만약 &#8220;=/test&#8221;와 같이 사용할 경우, &#8220;$host/test&#8221;는 일치하여서 매칭이 되지만, &#8220;$host/test/&#8221;는 매칭되지 않아버리므로, 주의를 기울여서 사용해야 합니다.</th>
</tr>
</thead>
<tbody>
<tr>
  <td>~</td>
  <td>대소문자를 구별하여 정규표현식과 일치할 때 사용 보통은 아래의 기호를 더 많이 사용하게 됩니다.</td>
</tr>
<tr>
  <td>~*</td>
  <td>대소문자 구별하지 않고 정규표현식과 일치할 때 사용 ex) location ~* &#46;(gif&#124;jpg&#124;jpeg)$ {  return 200 &#8220;found&#8221; }</td>
</tr>
<tr>
  <td>^~</td>
  <td>지정한 패턴으로 시작할 때 사용.</td>
</tr>
<tr>
  <td></td>
  <td>아무기호도 없이 텍스트를 사용하면, prefix로 사용해서 해당 텍스트로 시작하는 URI를 찾는다.</td>
</tr>
<tr>
  <td>@name</td>
  <td>이름을 붙여서, location 블럭을 정의한다. 내부 요청에 의해서만 접근할 수 있는데요. 아래와 같이 사용될 수 있습니다.   location {   try_files $uri @mylabel;  } location @mylabel { return 404 &#8220;Not Found&#8221;}</td>
</tr>
</tbody>
</table>

<h3>Header Setting</h3>

FE에 대한 서빙을 하다보면, index.html 페이지의 배포가 자주 일어나는데, 이부분이 브라우저 혹은 중간 CDN 서버에 캐싱이 되어있으면, 사용자 측에서 변경이 반영이 안된것으로 노출이 되게 됩니다.

이러한 부분을 캐시 설정을 통해서 서버의 변경사항을 바로 보여줄 수 있도록 설정할 수 있습니다.

<pre><code class="line-numbers">        location / {
...
...
            add_header Cache-Control "no-cache, no-store, max-age=0, must-revalidate";
        }
</code></pre>

<h3>Access Control</h3>

Public open을 앞둔 서비스는 사내망에서 혹은 특정 허용된 사용자만을 노출하기 위해서 제한을 할 수 있습니다.

<pre><code class="line-numbers">location ~ ^/internal-api/v1/circuit-breaker/(turn-off|turn-on)$ {
            if ($request_method != POST ) {
                    return 405;
            }
            allow 10.XXX.XX.X/32;
            deny all;
}
</code></pre>

<h3>Rewrite</h3>

rewrite은 server, location, if블록에서 사용할 수 있습니다. 마지막 flag값으로는 last, break, redirect, permanent가 있습니다. 마지막 permanent의 값은 301코드와 함께, 영원히 redirect시키는 flag입니다.

<pre><code class="line-numbers">location /test/api {
    rewrite ^/test/api(/.*)$ $1 break; // "/test/api를 제외한 URI로 전달"
    proxy_pass https://lan3rd.line.me;
    proxy_next_upstream error timeout;
    proxy_redirect off;
    proxy_connect_timeout 2s;

    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}  
</code></pre>

<h3>Return</h3>

nginx에서 rewrite를 하는 방법으로는 지시어 rewrite와 return하는 두가지 방법이 있습니다. 되도록 return을 사용하도록 권고하고 있습니다.

<pre><code class="line-numbers">server {
    listen 80;
    server_name .test.com;
    location / {
        return 301 https://$host$request_uri;
    }
}
</code></pre>

<h3>Proxy_set_header</h3>

중계 받는 nodejs 같은 서버에 request header를 다시 재정의해서 전달할 때 사용합니다.

<pre><code class="line-numbers">        location / {
            proxy_pass http://test_upstream;
            proxy_next_upstream error timeout;
            proxy_redirect off;
            proxy_connect_timeout 2s;

            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;

            proxy_set_header X-Forwarded-Proto https;
            proxy_set_header X-Forwarded-Server $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_http_version 1.1;
            proxy_set_header Connection "";

            proxy_hide_header x-envoy-decorator-operation;
            proxy_hide_header x-envoy-upstream-service-time;

            add_header Cache-Control "no-cache, no-store, max-age=0, must-revalidate";
        }
</code></pre>

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

Nginx 는 이미 만들어진 미들웨어(중간 소프트웨어) 제품입니다. 여러가지 설정들을 통해서 필자가 운영하는 서비스들에 좀 더 안정적으로 트래픽 제어 혹은 보안적인 측면에서 효율적으로 관리를 할 수 있다는 생각을 했습니다.

설정들에 대해서 하나하나 세세히 알기 쉽지는 않겠지만, 주로 설정하는 내용들에 대해서 미리 알고 있다면 조금 더 운영함에 있어서 손 쉽게 운영할 수 있을 것이라는 생각을 해봤습니다.

다음시간에는 <strong>Nginx의 통합</strong> 시리즈에 대해서 정리를 해보겠습니다.
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2020/10/20/nginx-configuration/">[DevOps] Nginx Configuration 정리</a></li><li><a href="https://blog.wonizz.com/2021/03/03/devops-rinetd-portforward/">[DevOps] Rinetd를 활용한 portforward</a></li><li><a href="https://blog.wonizz.com/2023/08/10/linux-logrotate/">[DevOps] Nginx Logrotation 설정</a></li><li><a href="https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/">[DevOps] Nginx Lua module 사용법</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2023/07/03/devops-nginx-configuration/">[DevOps] 주로 사용하는 Nginx 설정</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2023/07/03/devops-nginx-configuration/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2046</post-id>	</item>
		<item>
		<title>[DevOps] ansible nginx config 배포 구성</title>
		<link>https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/</link>
					<comments>https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/#respond</comments>
		
		<dc:creator><![CDATA[워니]]></dc:creator>
		<pubDate>Mon, 11 Jul 2022 07:59:14 +0000</pubDate>
				<category><![CDATA[ansible]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=1936</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>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 ansible을 이용한 nginx config 파일의 배포에 대해서 정리해보도록 하겠습니다. 필자가 속한 프로젝트에서는 nginx를 Front-end의 export된 html 소스를 서빙하기 위한 용도로 사용하고 있습니다. nginx config의 설정 변경을 수행하고 배포시에는 별도의 사내 시스템을 사용하고 있었지만, 이는 scp를 통해서 직접 파일을 카피하고 전송하는 부분이였습니다. 이러한 부분을 좀더 수월하게 개선하기 위해서 필자는 ansible을 통하여&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/">[DevOps] ansible nginx config 배포 구성</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>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 <code>ansible</code>을 이용한 <code>nginx config</code> 파일의 배포에 대해서 정리해보도록 하겠습니다. 필자가 속한 프로젝트에서는 nginx를 Front-end의 export된 html 소스를 서빙하기 위한 용도로 사용하고 있습니다. nginx config의 설정 변경을 수행하고 배포시에는 <code>별도의 사내 시스템</code>을 사용하고 있었지만, 이는 scp를 통해서 직접 파일을 카피하고 전송하는 부분이였습니다.</p>
<p>이러한 부분을 좀더 수월하게 개선하기 위해서 필자는 <code>ansible</code>을 통하여 파일을 배포하고 배포된 파일이 정상인지 검증(validation)을 수행하고, 이후에 기동한 뒤 프로세스체크까지 하는 파이프라인구조로 변경을 하기로 했습니다.</p>
<p>Nginx에 관한 시리즈 포스팅은 아래에서 확인이 가능합니다.</p>
<ul>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/02/09/devops-nginx-compile-installation/">[DevOps] Nginx 컴파일 설치</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/">[DevOps] ansible nginx config 배포 구성</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/08/10/linux-logrotate/">[DevOps] Nginx Logrotation 설정</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/08/17/devops-nginx-geoip-module/">[DevOps] Nginx GeoIP 모듈 적용</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/10/19/devops-nginx-log-aggregation-dashboard/">[DevOps] Nginx Log Aggregation &#038; Dashboard</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/">[DevOps] Nginx Lua module 사용법</a>
  </li>
</ul>
<h2>1. nginx deploy with ansible</h2>
<p><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.tk/wp-content/uploads/2022/07/ansible_deploy_1.png?w=1200" alt="ansible_deploy_1" /></p>
<p>nginx의 config 파일 관리는 github에서 우선적으로 합니다. ansible은 별도 ansible server에서 설치하여 사용하며 ansible을 위한 별도의 git repository도 존재합니다. 흐름은 다음 플로우를 통해서 진행이 되며, ansible을 통해서 nginx config 파일을 배포하고 nginx를 기동합니다.</p>
<ul>
<li>ansible에서 target되는 nginx config파일을 다운로드 받습니다.</li>
<li>nginx.conf 파일을 nginx의 binary를 통해서 검증(-t)를 수행합니다.</li>
<li>Nginx.conf 파일을 기반으로 restart를 수행합니다. (nginx config 파일을 갖고 기동합니다.)</li>
<li>Nginx의 프로세스(systemctl status)를 통해서 정상 기동되었는지 체크를 합니다.</li>
<li>위의 과정을 serial하게 1대씩 진행을 합니다.</li>
</ul>
<p>위와 같은 과정을 거쳐서 타겟팅 되는 nginx를 1대씩 배포를 수행하고(Rolling Update) 배포 완료시 알람을 발송합니다.</p>
<h2>2. ansible folder 구조</h2>
<p>Ansible의 git repository 구성에 대해서 정리를 해보도록 하겠습니다.</p>
<pre><code class="language-bash line-numbers">├── group_vars
│    └── test-web-nginx-prod.yml
├── nginx_deploy.yml
├── test-web-nginx-prod
└── roles
    ├── common
    │   ├── meta
    │   │   └── main.yml
    │   └── tasks
    │       └── main.yml
    └── nginx
        ├── meta
        │    └── main.yml
        ├── tasks
        │     └── main.yml
        └── templates
            └── index.html.j2
</code></pre>
<ul>
<li>ansible inventory 작성은 배포그룹(ex. test-web-nginx-prod) 에 작성</li>
</ul>
<h3>inventory / test-web-nginx-prod</h3>
<pre><code class="language-bash line-numbers">[test-web-nginx-prod]
test1501
test1502
test1503

[webservers:children]
test-web-nginx-prod
</code></pre>
<h3>inventory / group_vars / test-web-nginx-prod.yml</h3>
<pre><code class="language-yaml line-numbers">phase: "prod"
application: "test-web-nginx"
index: true
maintenence: true
members: false
vosdomain: "test-objects.com"
vosbucket: "test-nft"
</code></pre>
<p>inventory에는 서버에 대한 정보 설정을 기입합니다. 그리고 관련하여 참조할 변수들을 <strong>group_vars</strong> 하위에 기입을 합니다.</p>
<h2>3. ssh 접속을 위한 사전설정</h2>
<p>ansible 서버에서 target 서버로 접속을 하기 위해서는 ssh 설정이 필요합니다. 별도의 비밀번호 없이 public key와 private key를 통해서 접근을 하기 위한 설정입니다.</p>
<h3>키생성</h3>
<pre><code class="language-bash line-numbers">$ ssh-keygen -t rsa
</code></pre>
<ol>
<li>키를 저장할 경로( 기본값 : $HOME/.ssh/id_rsa)</li>
<li>passphrase (추가로 사용할 암호, 기본값 없음)</li>
<li>passphrase 확인</li>
</ol>
<h3>ssh key 등록하기</h3>
<p>.pub이 공개키 인데 해당 공개키를 서버에 등록하면 다음부턴 비밀번호를 입력할 필요가 없어집니다.</p>
<pre><code class="line-numbers">$ mkdir ~/.ssh
$ touch ~/.ssh/authorized_keys
$ chmod 755 ~/.ssh/authorized_keys
</code></pre>
<p>Host의 ~/.ssh/id_rsa.pub 에 있는 모든 내용을 복사해서, <strong>접속한 서버의 .ssh 폴더 내에 있는 authorized_keys 파일을 수정해 해당 내용을 모두 붙여 넣고 저장합니다.</strong></p>
<p>이렇게 되면, ansible서버에서 target 서버로 접속이 비밀번호 없이 바로 할 수 있습니다.</p>
<h2>4. jenkins 연계</h2>
<p>Jenkins를 통해서 ansible playbook 명령어를 호출하여 target 서버에 nginx config를 배포하고 restart를 해주는 내용을 연계하려고 합니다.</p>
<p>jenkins의 파라미터로는 2가지로 선정을 했습니다. nginx가 FE의 서빙 역할을 하기 때문에 application 별로 있습니다.</p>
<p>따라서 application이라는 파라미터를 설정했고, 각 phase(alpha, beta, real) 순서로 파라미터를 설정했습니다.</p>
<ul>
<li>applicatoin</li>
<li>phase</li>
</ul>
<p>설정한 값에 맞춰서 ansible playbook 실행시, nginx-config 와 target 서버 목록을 셋팅합니다.</p>
<h3>ansible 명령어</h3>
<pre><code class="language-bash line-numbers">$ ansible-playbook -i ${WORKSPACE}/devops-nginx-deploy/inventory/${APPLICATION}-${PHASE} ${WORKSPACE}/devops-nginx-deploy/playbook/nginx_deploy.yml -u irteamsu
</code></pre>
<h3>ansible roles</h3>
<pre><code class="language-yaml line-numbers"># roles/nginx/tasks/main.yml

---
# tasks file for nginx
#- name: install nginx
#  yum: name=nginx state=installed

- name: git clone
  git:
    repo: https://test:xxxxx@github.com/dongwonlee/test-web-nginx.git
    dest: /home1/test/apps/test-web-nginx/
    update: yes
    version: master

- name: copy nginx.config
  copy:
    src: /home1/test/apps/test-web-nginx/config/{{ application }}/nginx-{{ phase }}.conf
    dest: /etc/nginx/nginx.conf
    remote_src: yes

- name: Verify Nginx config
  command: nginx -t
  changed_when: false

- name: Download Index html
  get_url:
    url: https://{{ vosdomain }}/{{ vosbucket }}-{{ phase }}/index.html
    dest: /etc/nginx/index.html
    force: true
  when: index | bool

- name: Reload nginx config
  service: name=nginx state=reloaded enabled=yes

- name: check nginx status
  command: systemctl status nginx
  register: process
  failed_when: "'running' not in process.stdout"

</code></pre>
<p>ansible yaml 파일을 보면, 기존의 수동으로 하던 작업들을 일련의 작업으로 순서화를 시킨내용입니다.</p>
<ul>
<li>git clone</li>
<li>verify nginx</li>
<li>download resource ( index.html )</li>
<li>reload nginx cofig</li>
<li>check nginx status</li>
</ul>
<h2>5. 테스트</h2>
<p>기본적으로 ansible은 병렬 수행을 하는데, serial 수행으로 옵션을 줄 수 있습니다.</p>
<h3>Playbook / nginx_deploy.yml</h3>
<pre><code class="language-yaml line-numbers">---
- hosts: webservers
  become: yes
  serial: 1
  roles:
    - nginx
</code></pre>
<p>위와 같이 <strong>serial: 1</strong>을 주게 되면, 1대씩 실행을 합니다. 아래 결과에서 보듯이 2대의 서버를 1대씩 진행하고 결과를 출력해주고 있습니다.</p>
<pre><code class="line-numbers">PLAY [webservers] **************************************************************

TASK [Gathering Facts] *********************************************************
ok: [test-web-nginx001-dev]

TASK [nginx : git clone] *******************************************************
ok: [test-web-nginx001-jp2v-dev]

TASK [copy nginx.config] *******************************************************
ok: [test-web-nginx001-dev]

TASK [nginx : Verify Nginx config] *********************************************
ok: [test-web-nginx001-dev]

TASK [nginx : Download Index html] *********************************************
changed: [test-web-nginx001-dev]

TASK [Reload nginx config] *****************************************************
changed: [test-web-nginx001-dev]

TASK [check nginx status] ******************************************************
changed: [test-web-nginx001-dev]

PLAY [webservers] **************************************************************

TASK [Gathering Facts] *********************************************************
ok: [test-web-nginx002-dev]

TASK [nginx : git clone] *******************************************************
ok: [test-web-nginx002-dev]

TASK [copy nginx.config] *******************************************************
ok: [test-web-nginx002-dev]

TASK [nginx : Verify Nginx config] *********************************************
ok: [test-web-nginx002-dev]

TASK [nginx : Download Index html] *********************************************
changed: [test-web-nginx002-dev]

TASK [Reload nginx config] *****************************************************
changed: [test-web-nginx002-dev]

TASK [check nginx status] ******************************************************
changed: [test-web-nginx002-dev]

PLAY RECAP *********************************************************************
test-web-nginx001-dev : ok=8    changed=3    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
test-web-nginx002-dev : ok=8    changed=3    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
</code></pre>
<h2>6. 마치며</h2>
<p>ansible은 여러대의 config 설정과 같이 다양한 환경에서 반복적이고 여러대의 작업에서 수행되는 작업을 할 때 굉장히 유용한것 같습니다. 본 포스팅은 사내의 시스템이 있었는데 설정도 배포도 상당히 어려움이 있어서 ansible을 통해서 간단하게 jenkins 연계를 통하여 nginx 설정 배포를 할 수 있도록 구성했습니다.</p>
<p>다음 시간에는 ansible을 실행하고 job들을 관리할 수 있는 ansible tower(AWX)에 대해서 정리해보고 적용해보는 시간을 갖도록 하겠습니다.</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/">[DevOps] ansible nginx config 배포 구성</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/07/11/devops-ansible-nginx-config-deploy/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1936</post-id>	</item>
		<item>
		<title>[DevOps] Nginx 컴파일 설치</title>
		<link>https://blog.wonizz.com/2022/02/09/devops-nginx-compile-installation/</link>
					<comments>https://blog.wonizz.com/2022/02/09/devops-nginx-compile-installation/#respond</comments>
		
		<dc:creator><![CDATA[워니]]></dc:creator>
		<pubDate>Wed, 09 Feb 2022 01:39:24 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=1871</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>안녕하세요? 정리하는 개발자 워니즈 입니다. 2022년의 첫 포스팅입니다. 그동안 업무로 인해 블로그 정리에 대해서 소홀했던 것 같습니다. 저의 블로그에 방문해주시는 모든 분들 새해복 많이 많이 받으셨으면 좋겠습니다. 🙇 1월 경에는 이것저것 설치와 구성을 많이 하는 달이였던 것 같습니다. 특히 필자는 nginx에 관심이 굉장히 많습니다. nginx는 간단한게 웹서버를 구성해줄 수 있을 뿐더러, reverse proxy 역할을 수행함으로써&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/02/09/devops-nginx-compile-installation/">[DevOps] Nginx 컴파일 설치</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>안녕하세요? 정리하는 개발자 워니즈 입니다. 2022년의 첫 포스팅입니다. 그동안 업무로 인해 블로그 정리에 대해서 소홀했던 것 같습니다. 저의 블로그에 방문해주시는 모든 분들 새해복 많이 많이 받으셨으면 좋겠습니다. 🙇</p>
<p>1월 경에는 이것저것 설치와 구성을 많이 하는 달이였던 것 같습니다. 특히 필자는 <strong>nginx</strong>에 관심이 굉장히 많습니다. nginx는 간단한게 웹서버를 구성해줄 수 있을 뿐더러, reverse proxy 역할을 수행함으로써 적절한 LB의 역할도 수행을 해줍니다.</p>
<p>Nginx에 관한 시리즈 포스팅은 아래에서 확인이 가능합니다.</p>
<ul>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/02/09/devops-nginx-compile-installation/">[DevOps] Nginx 컴파일 설치</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2022/07/11/devops-ansible-nginx-config-deploy/">[DevOps] ansible nginx config 배포 구성</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/08/10/linux-logrotate/">[DevOps] Nginx Logrotation 설정</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/08/17/devops-nginx-geoip-module/">[DevOps] Nginx GeoIP 모듈 적용</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/10/19/devops-nginx-log-aggregation-dashboard/">[DevOps] Nginx Log Aggregation &#038; Dashboard</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a>
  </li>
<li><input style="margin-right:5px" type="checkbox" class="task-list-item-checkbox" checked disabled /><a class="wp-editor-md-post-content-link" href="https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/">[DevOps] Nginx Lua module 사용법</a>
  </li>
</ul>
<h2>1. Nginx compile 설치</h2>
<p>필자는 그동안 package manager를 통해서 간편하게 nginx를 설치했었습니다. 이렇게 설치했을 경우에는 별도의 module을 설치하거나 customizing을 하기 어렵다는 단점이 있습니다. 정형화된 nginx만을 사용하게 됩니다.</p>
<h3>1. 필수 패키지 다운로드</h3>
<blockquote><p>
  nginx를 compile 방식으로 설치하기 위해서는 반드시 필요한 의존성 라이브러리들이 있습니다.
</p></blockquote>
<ul>
<li>PCRE(Perl Compatible Regular Expressions)
<p>Nginx는 Perl5에서 사용하는 정규표현식 라이브러리인 PCRE를 사용합니다. Ngix의 재작성모듈과 HTTP 코어 모듈은 PCRE 구문에 따르는 정규표현식을 사용합니다.</p>
</li>
<li>openssl
<p>https 모듈인 HttpSslModule을 사용하기 위해서는 openssl 이 필요합니다.</p>
</li>
<li>zlib
<p>zlib 라이브러리는 개발자에게 압축 알고리즘을 제공합니다. ngx_http_gzip_module 을 사용하기 위해서는 zlib 라이브러리가 있어야 합니다.</p>
</li>
</ul>
<p>필자는 위의 소스를 다음과 같은 방법으로 다운로드를 받았습니다.</p>
<pre><code class="language-bash line-numbers">#root 계정을 통해서 pkgs 폴더 생성 
$ cd /
$ mkdir pkgs 
$ cd pkgs

#필수 패키지 다운로드 
$ wget http://nginx.org/download/nginx-1.20.1.tar.gz
$ wget https://ftp.openssl.org/source/old/1.1.1/openssl-1.1.1l.tar.gz
$ wget https://free.nchc.org.tw/osdn//sfnet/p/pc/pcre/pcre/8.44/pcre-8.44.tar.gz
$ wget https://fossies.org/linux/misc/zlib-1.2.11.tar.gz

#압축 해제 
$ tar -zxvf nginx-1.20.1.tar.gz
$ tar -zxvf openssl-1.1.1l.tar.gz
$ tar -zxvf pcre-8.44.tar.gz
$ tar -zxvf zlib-1.2.11.tar.gz
</code></pre>
<p>설치는 아래의 순서대로 진행하게 됩니다.</p>
<ul>
<li>configure : 환경설정
</li>
<li>
<p>make : 설치파일을 컴파일</p>
</li>
<li>
<p>make install : 설치파일을 이용해서 설치</p>
</li>
</ul>
<h3>2. configure를 통한</h3>
<p>이제 필요한 준비는 모두 됐습니다. 아래의 순서대로 설치가 진행이 됩니다. 먼저 configure를 통해서 위에 준비한 재료들을 사용한다고 설정(configure)를 진행합니다.</p>
<pre><code class="language-bash line-numbers"># variable 설정
NGINX_VERSION=1.20.1
PCRE_VERSION=8.44
OPENSSL_VERSION=1.1.1l
ZLIB_VERSION=1.2.11
NGINX_PATH=/home1/irteam/apps/nginx-${NGINX_VERSION}

# 필요 패키지 설치
$ yum install gcc-c++ pcre-devel zlib-devel make wget openssl-devel which libxml2-devel unzip libxslt-devel gd-devel perl-ExtUtils-Embed GeoIP-devel git gperftools-devel libcurl-devel file -y

# nginx 경로 생성
$ mkdir -p /pkgs /home1/irteam/apps

# configure
./configure --prefix=${NGINX_PATH} \
    --user=irteamsu --group=irteamsu \
    --with-http_ssl_module \
    --with-http_stub_status_module \
    --with-http_realip_module \
    --with-http_v2_module \
    --with-pcre=/pkgs/pcre-${PCRE_VERSION} \
    --with-openssl=/pkgs/openssl-${OPENSSL_VERSION} \
    --with-zlib=/pkgs/zlib-${ZLIB_VERSION} 
</code></pre>
<p>위의 설정은 금방 진행이 됩니다.</p>
<ul>
<li>&#8211;with-(zlib | pcre | openssl) : NGINX가 의존하고 있는 라이브러리들의 소스 경로</li>
<li>&#8211;with-(http_ssl_module | debug) : NGINX를 설치할 때 ssl, debug 모듈을 활성화한다. 이 모듈들은 NGINX가 제공하는 내부 모듈이지만 기본적으로는 설치가 되지 않는 옵션사항이다.</li>
<li>&#8211;prefix : NGINX가 설치될 기본 디렉토리를 의미한다. 이 디렉토리 하위에 NGINX의 실행, 로깅, 설정 파일들이 설치된다. 각각의 항목을 바꿀 수도 있다. 메뉴얼을 참고하자.</li>
<li>&#8211;user, &#8211;gourp : irteam 사용자의 권한으로 NGXIN를 실행시킨다. Irteam 사용자가 없다면 만들어야 한다. 사용자의 리스트는 아래의 명령을 통해서 알 수 있다. irteam가 아니라 자기 자신의 계정을 사용해도 된다.</li>
</ul>
<h3>3. make &#038; make install</h3>
<p>이제는 소스코드의 compile을 진행합니다. 이부분은 다소 시간이 소요되는 부분입니다.</p>
<pre><code class="language-bash line-numbers">$ make
</code></pre>
<p>아래와 같이 설정한 directory에서 정상적으로 빠져나왔다는 문구가 출력이 되면, 컴파일이 정상적으로 된 것입니다.</p>
<pre><code class="line-numbers">sed -e "s|%%PREFIX%%|/home1/irteam/apps/nginx-1.20.1|" \
        -e "s|%%PID_PATH%%|/home1/irteam/apps/nginx-1.20.1/logs/nginx.pid|" \
        -e "s|%%CONF_PATH%%|/home1/irteam/apps/nginx-1.20.1/conf/nginx.conf|" \
        -e "s|%%ERROR_LOG_PATH%%|/home1/irteam/apps/nginx-1.20.1/logs/error.log|" \
        < man/nginx.8 > objs/nginx.8
make[1]: Leaving directory `/pkgs/nginx-1.20.1'
</code></pre>
<p>정상적으로 compile된 내용물을 설치(디렉토리를 옮김)하는 과정입니다.</p>
<pre><code class="language-bash line-numbers">$ make install
</code></pre>
<p>아래와 같이 정상적으로 지정한 폴더에 내용물을 옮기는 과정이 출력됩니다.</p>
<pre><code class="language-bash line-numbers">make -f objs/Makefile install
make[1]: Entering directory `/pkgs/nginx-1.20.1'
test -d '/home1/irteam/apps/nginx-1.20.1' || mkdir -p '/home1/irteam/apps/nginx-1.20.1'
test -d '/home1/irteam/apps/nginx-1.20.1/sbin' \
        || mkdir -p '/home1/irteam/apps/nginx-1.20.1/sbin'
test ! -f '/home1/irteam/apps/nginx-1.20.1/sbin/nginx' \
        || mv '/home1/irteam/apps/nginx-1.20.1/sbin/nginx' \
                '/home1/irteam/apps/nginx-1.20.1/sbin/nginx.old'
cp objs/nginx '/home1/irteam/apps/nginx-1.20.1/sbin/nginx'
test -d '/home1/irteam/apps/nginx-1.20.1/conf' \
        || mkdir -p '/home1/irteam/apps/nginx-1.20.1/conf'
cp conf/koi-win '/home1/irteam/apps/nginx-1.20.1/conf'
cp conf/koi-utf '/home1/irteam/apps/nginx-1.20.1/conf'
cp conf/win-utf '/home1/irteam/apps/nginx-1.20.1/conf'
test -f '/home1/irteam/apps/nginx-1.20.1/conf/mime.types' \
        || cp conf/mime.types '/home1/irteam/apps/nginx-1.20.1/conf'
cp conf/mime.types '/home1/irteam/apps/nginx-1.20.1/conf/mime.types.default'
test -f '/home1/irteam/apps/nginx-1.20.1/conf/fastcgi_params' \
        || cp conf/fastcgi_params '/home1/irteam/apps/nginx-1.20.1/conf'
cp conf/fastcgi_params \
        '/home1/irteam/apps/nginx-1.20.1/conf/fastcgi_params.default'
test -f '/home1/irteam/apps/nginx-1.20.1/conf/fastcgi.conf' \
        || cp conf/fastcgi.conf '/home1/irteam/apps/nginx-1.20.1/conf'
cp conf/fastcgi.conf '/home1/irteam/apps/nginx-1.20.1/conf/fastcgi.conf.default'
test -f '/home1/irteam/apps/nginx-1.20.1/conf/uwsgi_params' \
        || cp conf/uwsgi_params '/home1/irteam/apps/nginx-1.20.1/conf'
cp conf/uwsgi_params \
        '/home1/irteam/apps/nginx-1.20.1/conf/uwsgi_params.default'
test -f '/home1/irteam/apps/nginx-1.20.1/conf/scgi_params' \
        || cp conf/scgi_params '/home1/irteam/apps/nginx-1.20.1/conf'
cp conf/scgi_params \
        '/home1/irteam/apps/nginx-1.20.1/conf/scgi_params.default'
test -f '/home1/irteam/apps/nginx-1.20.1/conf/nginx.conf' \
        || cp conf/nginx.conf '/home1/irteam/apps/nginx-1.20.1/conf/nginx.conf'
cp conf/nginx.conf '/home1/irteam/apps/nginx-1.20.1/conf/nginx.conf.default'
test -d '/home1/irteam/apps/nginx-1.20.1/logs' \
        || mkdir -p '/home1/irteam/apps/nginx-1.20.1/logs'
test -d '/home1/irteam/apps/nginx-1.20.1/logs' \
        || mkdir -p '/home1/irteam/apps/nginx-1.20.1/logs'
test -d '/home1/irteam/apps/nginx-1.20.1/html' \
        || cp -R html '/home1/irteam/apps/nginx-1.20.1'
test -d '/home1/irteam/apps/nginx-1.20.1/logs' \
        || mkdir -p '/home1/irteam/apps/nginx-1.20.1/logs'
make[1]: Leaving directory `/pkgs/nginx-1.20.1'    
</code></pre>
<h2>2. 기본 설정</h2>
<h3>1. /usr/bin</h3>
<p>global 하게 nginx binary를 실행할 수 있도록 <strong>/usr/bin/</strong>경로로 nginx binary를 copy해줍니다.</p>
<pre><code class="language-bash line-numbers">$ cp /home1/irteam/apps/nginx-1.20.1/sbin/nginx /usr/bin
</code></pre>
<p>먼저 설치한 경로로 이동을 해봅니다.</p>
<h3>2. systemd 설정</h3>
<p>daemon 형태로 명령어를 사용하기 위해서 systemd에 등록을 해줍니다.</p>
<pre><code class="language-bash line-numbers">$ vi /etc/systemd/system/nginx.service

[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/bin/nginx -t
ExecStart=/usr/bin/nginx
ExecReload=/usr/bin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
</code></pre>
<h3>3. symbolic link 설정</h3>
<p>이부분은 필자만의 custom 사용인데, package manager를 사용하여 설치하게 되면 /etc/nginx 경로에 설치가 됩니다. 필자는 이경로로에서 config 제어를 하기 위해서 symbolic link를 걸어두기로 했습니다.</p>
<pre><code class="language-bash line-numbers">$ ln -s /etc/nginx/nginx.conf /home1/irteam/apps/nginx-1.20.1/conf/nginx.conf
</code></pre>
<h2>3. 정상 설치 확인</h2>
<p>먼저 nginx의 설정이 정상적인지를 체크합니다.</p>
<pre><code class="language-bash line-numbers">$ nginx -t
nginx: the configuration file /home1/irteam/apps/nginx-1.20.1/conf/nginx.conf syntax is ok
nginx: configuration file /home1/irteam/apps/nginx-1.20.1/conf/nginx.conf test is successful
</code></pre>
<p>nginx의 daemon 상태를 확인합니다.</p>
<pre><code class="language-bash line-numbers">$ systemctl status nginx
   Loaded: loaded (/etc/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
</code></pre>
<p>nginx의 daemon을 기동합니다</p>
<pre><code class="language-bash line-numbers">$ systemctl start nginx
$ systemctl status nginx
● nginx.service - The NGINX HTTP and reverse proxy server
   Loaded: loaded (/etc/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: active (running) since Wed 2022-02-09 10:26:30 JST; 1s ago
  Process: 149360 ExecStart=/usr/bin/nginx (code=exited, status=0/SUCCESS)
  Process: 149359 ExecStartPre=/usr/bin/nginx -t (code=exited, status=0/SUCCESS)
 Main PID: 149363 (nginx)
   CGroup: /system.slice/nginx.service
           ├─149363 nginx: master process /usr/bin/nginx
           └─149364 nginx: worker process

Feb 09 10:26:30 ansible001-lnk8s-temp-jp2v-prod nginx[149359]: nginx: the configura...
Feb 09 10:26:30 ansible001-lnk8s-temp-jp2v-prod nginx[149359]: nginx: configuration...
Hint: Some lines were ellipsized, use -l to show in full.
</code></pre>
<h2>4. Module 추가</h2>
<p>서두에 정리했다시피, nginx를 위의 과정을 통해서 compile하는 이유는 module을 설치할 수 있다는 장점이 있습니다. 모듈에 대한 리스트는 아래의 페이지에서 확인할 수 있습니다.</p>
<p><a class="wp-editor-md-post-content-link" href="https://www.nginx.com/resources/wiki/modules/index.html" target="_blank" rel="noopener">NGINX 3rd Party Modules</a></p>
<p>필요한 모듈을 설치 과정에서 pkgs 폴더에 다운로드를 받습니다. 그렇게 된 상태에서 <strong>configure</strong>과정에서 add-module을 통해서 모듈을 참조하도록 해줍니다. 위의 설치 과정과 다른 부분은 마지막줄이 다릅니다.</p>
<pre><code class="language-bash line-numbers">./configure --prefix=${NGINX_PATH} \
    --user=irteamsu --group=irteamsu \
    --with-http_ssl_module \
    --with-http_stub_status_module \
    --with-http_realip_module \
    --with-http_v2_module \
    --with-pcre=/pkgs/pcre-${PCRE_VERSION} \
    --with-openssl=/pkgs/openssl-${OPENSSL_VERSION} \
    --with-zlib=/pkgs/zlib-${ZLIB_VERSION} \
    --add-module=/pkgs/sample_module-${SAMPLE_VERSION}-x64
</code></pre>
<p>이러한 과정을 통해서 필요한 외부의 모듈을 탑재할 수 있습니다.</p>
<h2>5. 마치며&#8230;</h2>
<p>이번시간에는 nginx의 compile을 통해서 설치하는 과정에 대해서 정리를 해보았습니다. 그동안 패키지 매니저에 너무 익숙해져서 왜 이렇게 복잡한 과정을 걸쳐서 설치를 하는지 이해를 못했었습니다. 하지만, 이러한 과정에는 모듈의 설정이 연관이 있다는 것을 알게 됐습니다.</p>
<p>DevOps 입장에서 이러한 과정들을 하나로 엮어서 자동화 했으면 하는 생각이 들었습니다. 우선 다음시간에는 ansible을 통해서 nginx의 config 설정을 업데이트 하는 내용에 대해서 정리를 해보려고 합니다. 그리고 이후에는 nginx의 설치 과정에 대해서도 ansible을 통해서 손쉽게 구성이 가능하도록 해보려 합니다.</p>
<h2>6. 참조</h2>
<p><a class="wp-editor-md-post-content-link" href="https://opentutorials.org/module/384/4511" target="_blank" rel="noopener">NGINX 컴파일</a></p>
<p><a class="wp-editor-md-post-content-link" href="https://saegeullee.github.io/server/nginx" target="_blank" rel="noopener">Nginx 서버 설치와 환경 설정</a></p>
<p><a class="wp-editor-md-post-content-link" href="https://victorydntmd.tistory.com/234" target="_blank" rel="noopener">[Web Server] Nginx 1.6.2 컴파일 설치</a></p>
<p><a class="wp-editor-md-post-content-link" href="https://emunhi.com/view/201812/23153413395?menuNo=10019" target="_blank" rel="noopener">Nginx를 CnetOS 7에 소스 컴파일 설치</a></p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/02/09/devops-nginx-compile-installation/">[DevOps] Nginx 컴파일 설치</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/09/devops-nginx-compile-installation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1871</post-id>	</item>
		<item>
		<title>[DevOps] Rinetd를 활용한 portforward</title>
		<link>https://blog.wonizz.com/2021/03/03/devops-rinetd-portforward/</link>
					<comments>https://blog.wonizz.com/2021/03/03/devops-rinetd-portforward/#respond</comments>
		
		<dc:creator><![CDATA[워니]]></dc:creator>
		<pubDate>Wed, 03 Mar 2021 08:36:40 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Tech]]></category>
		<category><![CDATA[DevOps]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1738</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>안녕하세요? 정리하는 개발자 워니즈 입니다. 이번시간에는 Public subnet에있는 Deploy tool을 통해서 Private Subnet에 존재하는 서버들에 대해서 배포를 수행하기 위한 고민을 했던 포스팅 입니다. 필자가 소속된 프로젝트에서는 운영 환경에서 2개 이상의 AWS Region에서 서비스를 하고 있습니다. Deploy 같은 경우 하나의 Tool(Rundeck)에서 수행되어야 하는 것을 목표로 했었습니다. 이번 포스팅에서 소개할 내용은 rinetd라는 포트포워딩 툴입니다. 1. 구성 상황&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2021/03/03/devops-rinetd-portforward/">[DevOps] Rinetd를 활용한 portforward</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>
안녕하세요? 정리하는 개발자 워니즈 입니다. 이번시간에는 Public subnet에있는 Deploy tool을 통해서 Private Subnet에 존재하는 서버들에 대해서 배포를 수행하기 위한 고민을 했던 포스팅 입니다.

필자가 소속된 프로젝트에서는 운영 환경에서 2개 이상의 AWS Region에서 서비스를 하고 있습니다. Deploy 같은 경우 하나의 Tool(Rundeck)에서 수행되어야 하는 것을 목표로 했었습니다.

이번 포스팅에서 소개할 내용은 <strong>rinetd</strong>라는 포트포워딩 툴입니다.

<h2>1. 구성 상황</h2>

서두에 기록을 해두었지만, 2개 이상의 Region에서 운영되는 서비스인데다가, 한개의 region의 public영역에서 다른 region의 private영역으로 연결을 시도할 때가 당연히 문제가 되었습니다. 그렇다고, 각 region별로 deploy tool을 둘수도 없는 상황이기에 약간의 꼼수(?)를 부리기 위해서 알아보다보니, rinetd를 알게 되었고, 한개의 region의 public에서 다른 region의 public으로 붙은다음에 거기서 포트포워딩으로 패킷을 전달해주는 방식을 채택하기로 했습니다.

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

<h2>2. rinetd란 무엇인가요?</h2>

TCP 연결을 한 IP 주소 및 포트에서 다른 IP로 리다이렉션을 수행하게끔 해주는 툴입니다. 설정 파일을 통해서 from에서 to로 명시적으로 기록을 합니다.

설정 파일을 통해서 수행되지만, nonblocking I/O를 이용하여 단일 프로세스로 수행되기 떄문에 프로세스 수행상에 문제를 발생시키지 않는다고 되어있습니다.

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

<h2> </h2>

<h2>3. rinetd 설치 방법</h2>

<pre><code class="line-numbers"># /etc/yum.repos.d/nux-misc.repo 내 추가 
[nux-misc]
name=Nux Misc
baseurl=http://li.nux.ro/download/nux/misc/el7/x86_64/
enabled=0
gpgcheck=1
gpgkey=http://li.nux.ro/download/nux/RPM-GPG-KEY-nux.ro

# rinetd 설치
yum --enablerepo=nux-misc install rinetd
</code></pre>

설치는 상당히 심플 합니다. yum을 통해서 설치를 진행하면 되고, 포트포워딩을 수행할 서버에서 설치를 진행하면 됩니다.

<h2>3. rinetd 설정 방법</h2>

<pre><code class="line-numbers"># rinetd 설정 파일 수정
vi /etc/rinetd.conf
</code></pre>

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

실제 설정파일에는 가이드도 친절하게 젂혀 있습니다. 
예를들어, 10.10.10.2(rinetd가 설치된 서버) 80 포트로 접속을 수행했을때, 192.168.0.2:80 으로 보내라는 설정은 다음과 같습니다.

<pre><code class="line-numbers">0.0.0.0 80 192.168.0.2 80   
</code></pre>

IP기반으로 ACL에 대한 설정도 가능합니다.

<pre><code class="line-numbers"># 172.16.32.0/24 대역 ALLOW
allow 172.16.32.*

# 192.168.32.12 아이피 DENY
deny 192.168.32.12
</code></pre>

로그에 대한 기록도 수행해 줍니다.

<pre><code class="line-numbers"># log 경로 셋팅
logfile /var/log/rinetd.log
</code></pre>

설정을 모두 마친후, rinetd를 재시작하게 되면 적용이 됩니다.

<pre><code class="line-numbers">[root@testuser ec2-user]# service rinetd restart
Restarting rinetd (via systemctl):                         [  OK  ]
</code></pre>

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

그럼 서두에 기록했던, 한개의 region public subnet의 인스턴스에서 다른 region의 public subnet의 인스턴스로 접속을 수행합니다.

ap regsion public A ec2 ->  eu region public B ec2 ->portforward -> eu region private C ec2

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

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

이번 시간에는 rinetd를 활용한 포트포워딩 프로그램에 대해서 정리해보는 시간을 갖었습니다. 네트워크 쪽은 공부를 하면 할수록 정말 어려운 분야 인 것 같습니다. VPC 설계부터 subnet 그리고 route table, NAT의 개념에 대해서도 다시금 정리를 해두어야 할것 같다는 생각을 해보았습니다.
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2019/02/26/devops-assign/">DevOps 사전 과제</a></li><li><a href="https://blog.wonizz.com/2019/07/31/docker-dockerfile/">[Docker] Dockerfile 의 이해</a></li><li><a href="https://blog.wonizz.com/2019/10/07/elk-log-anlysis/">[DevOps] ELK를 활용한 로그 분석</a></li><li><a href="https://blog.wonizz.com/2019/08/13/docker-compose/">[Docker] Compose 구성과 사용법</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2021/03/03/devops-rinetd-portforward/">[DevOps] Rinetd를 활용한 portforward</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2021/03/03/devops-rinetd-portforward/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1738</post-id>	</item>
		<item>
		<title>[DevOps] Apache rewrite rule 정리</title>
		<link>https://blog.wonizz.com/2020/11/03/devops-apache-rewrite-rule/</link>
					<comments>https://blog.wonizz.com/2020/11/03/devops-apache-rewrite-rule/#respond</comments>
		
		<dc:creator><![CDATA[워니]]></dc:creator>
		<pubDate>Tue, 03 Nov 2020 05:50:26 +0000</pubDate>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[Linux]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1548</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>필자가 속한 프로젝트에서는 Apache를 웹서버로 사용하고 있습니다.  그러다보니, apache에 들어가있는 configuration에 대해서 알아야 되는데요. 그중에서도 rewrite rule이 있습니다. </p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/11/03/devops-apache-rewrite-rule/">[DevOps] Apache rewrite rule 정리</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>
안녕하세요 정리하는 개발자 워니즈입니다. 이번시간에는 아파치 config 중에 rewrite 룰에 대해서 정리를 해보려고 합니다. 필자가 속한 프로젝트에서는 <strong>Apache를 웹서버로 사용하고 있습니다.</strong> 그러다보니, apache에 들어가있는 configuration에 대해서 알아야 되는데요. 그중에서도 rewrite rule이 있습니다.

Apache의 rewrite Module은 아파치 모듈주의 한종류로 서버 Request를 정해진 Rule에 의해서 다른 URL or File로 보내는 모듈입니다.

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

<h2>1. Rewrite 모듈 지시자</h2>

<ul>
<li>RewriteEngine</li>
</ul>

Rewriting 엔진을 사용할지 여부를 설정합니다. 기본설정은 Off로 되어 있으며 RewriteEngine On으로 설정하면 Rewriting 엔진이 활성화 됩니다.

<ul>
<li>RewirteLog File-Path</li>
</ul>

RewriteLog 지시자는 Rewrite 엔진의 로그를 그록할 파일을 지정합니다.
RewriteLog 파일을 항상 남기기 보다 잘못된 Rewrite 규칙들을 디버킹할 때 사용하기를 권장합니다. 아파치와 마찬가지로 RewriteLog 파일도 방문자 수가 많은 사이트에서는 많은 로그파일이 쌓이기 때문에 해당 파티션의 여유공간이 많이 없는 시스템에서는 장래를 유발 할수도 있으므로 로그를 잘 관리 해야 합니다.

<ul>
<li>RewriteLogLevel Level</li>
</ul>

RewriteLogLevel 지시자는 RewriteLog 지시자로 설정한 로그파일에 기록할 로그들에 대해 얼마나 자세한 내용을 로그로 남길것인가에 대해 설정하는 지시자입니다.
기록할 로그 Level 은 0 ~ 9까지 사용할 수 있으며 0은 로그를 기록하지 않겠다는 의미입니다.

<h2>2. Rewrite Flag</h2>

RewriteRule 문법중 마지막에 패턴이 일치할 경우 어떤 동작을 취할지 지정하는 부분이며, 이를 플래그라고도 합니다. 지정할 수 있는 플래그중 자주 사용되는 것들은 다음과 같은 항목이 있습니다. 플래그는 전체 단어를 써도 되지만 축약어로 써도 됩니다.

필자의 프로젝트에 적용된 것을 위주로 정리를 해보겠습니다.

<ul>
<li>Last :  L</li>
</ul>

Last 플래그는 더이상 mod_rewrite 룰 처리를 하지 않겠다는 의미이다. 프로그래밍 언어에서 break 와 비슷한 용도로 사용되며 여러 개의 <em>RewriteRule</em>  룰을 연결해서 사용하는 경우 더 이상의 처리를 하지 않아도 될 때 유용하게 사용할 수 있다.

<ul>
<li>Nocase : NC</li>
</ul>

Nocase 는 패턴 매칭할 경우 대소문자 구분을 하지 않겠다는 의미이다.

<ul>
<li>Noescape: NE

기본적으로 &#038; 및 ?와 같은 특수 문자는 16진수 등가로 변환된다. [NE] 플래그를 사용하면 그런 일이 발생하지 않는다.</p></li>
</ul>

RewriteRule &#8220;^/anchor/(.+)&#8221; &#8220;/bigpage.html#$1&#8221; [NE,R]
위의 예는 /anchor/xyz를 /bigpage로 리디렉션한다.html#xyz. [NE]를 생략하면 #가 16진수 등가 %23로 변환되어 404 Not Found 오류 상태가 된다.

<ul>
<li>Redirect:R</li>
</ul>

리다이렉트 플래그는 규칙에 일치할 경우 HTTP 302 Redirect 응답을 클라이언트에게 전송한다. 만약 <em>HTTP 301 Moved Permanently</em> 응답을 전송해야 한다면 R=301 로 적어주면 된다.

<ul>
<li>Passthru:PT</li>
</ul>

RewriteRule 의 target_url 이 http 나 https 로 시작하지 않으면 mod_rewrite 는 target_url 을 로컬 파일의 경로로 인식한다. / 로 시작할 경우 절대 경로로 / 가 아닐 경우 상대 경로로 처리하게 된다. 파일 경로로 처리할 경우 스크립트 파일의 경우 파일의 내용이 그대로 노출될 우려가 있다.

<ul>
<li>qsappend: QSA</li>
</ul>

mod_rewrite 는 기본적으로 클라이언트가 GET 으로 전송한 변수를 무시한다. 이 변수 값은 QUERY_STRING 이라는 변수명에 저장된다. QSA(Query String Append) 플래그를 사용하면 QUERY_STRING 을 무시하지 않고 유지시키므로 URL 전환시에도 문제가 없다.

<h2>3. RewriteCond</h2>

앞에서 <em>RewriteRule</em> 에 대한 설명을 보고 만약 조건문이 필요할 경우는 어떻게 해야 할지 의문이 생긴 독자들도 있을 것이다. <em>RewriteCond</em> 는 그런 독자들의 의문을 해소해 줄 지시자이다. 여러 가지 상황별로 조건을 확인하고 그 조건이 맞을 경우 처리를 하게 할 수 있다. <em>RewriteCond</em>는 다음과 같은 문법을 갖는다.

<em>RewriteCond TestString Pattern [Flags]</em>

<strong>TestString</strong> 에는 다음과 같은 값등을 사용할 수 있다.

<ul>
<li><strong>직전 RewriteRule 에서 일치한 캡처값</strong> &#8211; RewriteCond 앞에 RewriteRule 을 사용했고 정규 표현식에서 그룹으로 지정된 값이 있을 경우 TestString 에 사용할 수 있다. 사용할 경우 $N (N 은 0 에서 9사이 값) 형식으로 사용한다.

</li>
<li>

<strong>직전 RewriteCond 에서 일치한 캡처값</strong> &#8211; RewriteCond 앞에 RewriteCond를 사용했고 정규 표현식에서 그룹으로 지정된 값이 일치했을 경우 %N(N 은 0 에서 9) 형식으로 사용할 수 있다.

</li>
<li>

<strong>서버 변수</strong> &#8211; 웹서버가 갖고 있는 변수값을 사용할 수 있다. 서버의 변수를 사용할 경우 %{변수명} 형식으로 사용한다. 제일 많이 사용하는 변수들은 %{HTTP_HOST}, %{QUERY_STRING} 등이다.

</li>
</ul>

<table>
<thead>
<tr>
  <th align="left">변수명</th>
  <th align="left">설명</th>
</tr>
</thead>
<tbody>
<tr>
  <td align="left">HTTP 요청 변수</td>
  <td align="left"></td>
</tr>
<tr>
  <td align="left">HTTP_HOST</td>
  <td align="left">URL 에서 호스트 이름 부분이며 클라이언트가 보낸 HTTP 헤더중 Host: 헤더에 있는 값이 된다. 가상 호스트 기반 rewrite 규칙을 설정할 경우에 많이 사용된다.</td>
</tr>
<tr>
  <td align="left">HTTP_REFERER</td>
  <td align="left">사용자가 현재 요청시 어떤 링크를 통해 들어왔는지 알수 있는 변수이다.</td>
</tr>
<tr>
  <td align="left">REQUEST_METHOD</td>
  <td align="left">HTTP 요청 메소드로 보통 GET 또는 POST 가 된다.</td>
</tr>
<tr>
  <td align="left">QUERY_STRING</td>
  <td align="left">GET 방식으로 URL 을 호출했을 때 넘긴 파라미터가 설정된다. 예로 <em>&#8220;http://www.example.com/article/view.jsp?one=two&#038;three=four&#8221; 로 호출했을 경우</em>, QUERY_STRING 은 &#8220;one=two&#038;three=four&#8221; 가 된다.</td>
</tr>
<tr>
  <td align="left">REQUEST_URI</td>
  <td align="left">클라이언트가 요청한 리소스로 보통 URL 에서 호스트 이름과 파라미터를 제외한 부분이 된다. 위 QUERY_STRING 예제에서 REQUEST_URI는 &#8220;<em>article/view.jsp&#8221;</em> 가 된다.</td>
</tr>
<tr>
  <td align="left">클라이언트 변수</td>
  <td align="left"></td>
</tr>
<tr>
  <td align="left">HTTP_USER_AGENT</td>
  <td align="left">사용자 브라우저 정보가 설정</td>
</tr>
<tr>
  <td align="left">HTTP_ACCEPT</td>
  <td align="left">브라우저가 처리할 수 있는 컨텐츠의 목록</td>
</tr>
<tr>
  <td align="left">REMOTE_ADDR</td>
  <td align="left">요청 클라이언트가 사용하는 IP</td>
</tr>
<tr>
  <td align="left">REMOTE_USER</td>
  <td align="left">로그인이 필요한 리소스에 접근할 경우 사용자명</td>
</tr>
<tr>
  <td align="left">서버 내부 변수</td>
  <td align="left"></td>
</tr>
<tr>
  <td align="left">DOCUMENT_ROOT</td>
  <td align="left">현재 가상 호스트에 설정한 DocumentRoot 의 경로를 얻을 수 있다.</td>
</tr>
<tr>
  <td align="left">REQUEST_FILENAME</td>
  <td align="left">클라이언트가 요청한 파일이나 스크립트가 현재 서버에 위치하는 절대 경로를 의미한다. 현재 가상호스트의 DocumentRoot 가 &#8220;/var/www/vhost1&#8221; 이고 클라이언트가 /book.php 를 요청했을 경우 REQUEST_FILENAME 은 <em>/var/www/vhost1/book.php</em> 가 된다.</td>
</tr>
<tr>
  <td align="left">SERVER_NAME</td>
  <td align="left">The canonical name of the current virtual host.</td>
</tr>
<tr>
  <td align="left">SERVER_ADDR</td>
  <td align="left">The IP address of the current virtual host.</td>
</tr>
<tr>
  <td align="left">SERVER_PORT</td>
  <td align="left">The port number from which the current request is being served.</td>
</tr>
<tr>
  <td align="left">HTTPS</td>
  <td align="left">SSL 이나 TLS 를 사용할 경우 on 으로 설정되고 HTTP 일 경우 off 이다.</td>
</tr>
</tbody>
</table>

<strong>Pattern</strong> 에는 정규식으로 일치시킬 문자열의 패턴을 기술하면 된다.

마지막 플래그는 다음과 같은 값을 사용할 수 있다.

<ul>
<li><strong>NoCase:NC</strong> – RewriteRule 과 마찬가지로 대소 문자를 구분하지 않을 경우 사용한다.</li>
<li><strong>ORNext:OR</strong> – OR 플래그는 여러 개의 RewriteCond 를 사용할 경우 논리적인 OR 조건이 필요할 때 사용할 수 있다.(여러 개의 RewriteCond 가 있을 때 기본적으로 AND 로 처리한다.)</li>
</ul>

<h2>4. 실제 사용 사례</h2>

필자의 프로젝트에서 사용하는 RewriteRule에 대해서 정리를 해보도록 하겠습니다.

<pre><code class="line-numbers">    # 1단계 URL 을 그냥 통과 시킬 리스트 적용
    RewriteCond %{REQUEST_URI} ^/etc/designs(.*) [NC,OR]
    RewriteCond %{REQUEST_URI} ^/etc.clientlibs(.*) [NC,OR]
    RewriteCond %{REQUEST_URI} ^/apps/samsung/login(.*) [NC,OR]
    RewriteCond %{REQUEST_URI} ^/bin(.*) [NC,OR]
    RewriteCond %{REQUEST_URI} ^/aemapi(.*) [NC,OR]
    RewriteCond %{REQUEST_URI} ^/sysapi(.*) [NC,OR]
    RewriteCond %{REQUEST_URI} ^/libs/granite/csrf/token [NC,OR]
    RewriteCond %{REQUEST_URI} ^/samsung(.*) [NC,OR]
    RewriteCond %{REQUEST_URI} ^/content/dam(.*) [NC]
    RewriteRule ^(.*)$ $1 [PT]
</code></pre>

위의 예제는 재작성 조건에 대해서 여러개를 연결 시켜 놓은 것입니다. 개발코드로 치면 조건문에서 or조건으로 여러개의 체크 조건을 갖고 있습니다.

<ol>
<li>대소문자를 가리지 않는다. [NC]</li>
<li>조건체크를 or조건으로 한다. [OR]</li>
<li>최종 나온 path에 대해서 그대로 통과 시킨다. [PT]</li>
</ol>

<pre><code class="line-numbers"># 2단계 /content/samsung 이 붙어 있을 경우 제거
RewriteCond %{REQUEST_URI} ^/content/samsung/(.*)$ [NC]
RewriteRule ^/content/samsung/(.*)$ /$1 [R=302,NE,QSA,L]
</code></pre>

위의 조건은 url 요청이 특정 문자열(/content/samsung)을 붙이고 들어올때, 그부분을 제거하는 내용입니다.

<ol>
<li>/content/samsung을 떼어주되, 특수문자를 그대로 둡니다.[NE]</li>
<li>query string에 대해서 그대로 append 해줍니다.[QSA]</li>
<li>302 redirectino 처리를 하고 break를 수행합니다.[R=302, L]</li>
</ol>

<pre><code class="line-numbers"># 3단계 /가 없거나 확장자가 없을때 / 붙여줌
RewriteCond %{REQUEST_URI} !.*\..*$
RewriteCond %{REQUEST_URI} !.*/$
RewriteRule ^(.*)$ $1/ [R=302,NE,QSA]

# handle requests to pages ending with .html
# 4단계 .html 로 끝날경우 / 를 붙여줌
RewriteCond %{REQUEST_URI} .*.html$
RewriteRule ^(.*).html$ $1/ [R=302,NE,QSA]
</code></pre>

3단계와 4단계는 유사합니다. 모든 request에 대해서 끝에 슬래시를 추가해주는 내용입니다.

<ol>
<li>확장자가 없거나 (!.<em>&#46;.</em>$), 슬래시가 없거나 (!.*/$)의 조건을 찾음.</li>
<li>.html로 끝나는 경우(.*.html$)</li>
<li>특수문자 처리, query string append, Redirection 처리[R=302,NE,QSA]</li>
</ol>

<pre><code class="line-numbers"># 5단계 앞의 작업이 끝났을경우 인터널로 호출할때 /content/samsung 을 붙여줌  
# 앞에서 빼고 뒤에서 붙이는 이유는 사전 URL 작업을 진행하고 내부로 호출하기 위해서임
RewriteCond %{REQUEST_URI} ^/(.*)$ [NC]
RewriteRule ^/(.*)$ /content/samsung/$1 [NE,QSA]

# 6단계 내부적으로 호출할때 html 을 붙여줌
RewriteCond %{REQUEST_URI} .*/$
RewriteCond %{REQUEST_URI} !^/$
RewriteRule ^(.*)/$ $1.html [PT,NE,L,QSA]
</code></pre>

5단계와 6단계를 거치면서 내부의 internal server(was)로 페이지를 요청하기 위해서 다시 /content/samsung과 확장자(.html)을 붙여줍니다.

<h2>5. apache debug 방법</h2>

아파치 rewriterule을 셋팅하면서 항상 어려웠던 부분이  rewrite rule에 대한 디버깅이였습니다. 서칭을 좀 하다보니, online으로 rewrite rule을 테스팅 해볼 수 있는 사이트가 있었습니다.

<a class="wp-editor-md-post-content-link" href="https://htaccess.madewithlove.be/" target="_blank" rel="noopener">online rewrite test tool</a>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/apache_2.png?w=1200&#038;ssl=1" alt="DevOps Apache rewrite rule 정리 설명 이미지 1" />

아래에 rewrite rule에 대해서 읿력을 하고, 위에 request 되는 url에 대해서 입력을 하면, 아래에 debugging된 내용이 노출이 됩니다. 이것을 통해서 개략적인 rewrite rule에 대해서 확인을 해 볼 수 있습니다.

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

이번시간에는 apache rewrite rule에 대해서 정리를 해 보았습니다. apache의 지극히 일부의 모듈에 대해서 정리를 한것이고, 지난 포스팅과 더불어 nginx, apache의 설정들에 대한 정리는 지속적으로 해볼 예정입니다.

nginx-aapche-was로 이어지는 트래픽 흐름의 중간에 어디 부분에서 오류를 일으키고, 어떤 부분을 고쳐야 되는지 확인하기 위해서 각각의 미들웨어 + 어플리케이션 로그를 확인할줄도 알아야된다는 것을 느꼇습니다.
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2020/10/20/nginx-configuration/">[DevOps] Nginx Configuration 정리</a></li><li><a href="https://blog.wonizz.com/2021/03/03/devops-rinetd-portforward/">[DevOps] Rinetd를 활용한 portforward</a></li><li><a href="https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/">[DevOps] Nginx Lua module 사용법</a></li><li><a href="https://blog.wonizz.com/2023/08/10/linux-logrotate/">[DevOps] Nginx Logrotation 설정</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/11/03/devops-apache-rewrite-rule/">[DevOps] Apache rewrite rule 정리</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/11/03/devops-apache-rewrite-rule/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1548</post-id>	</item>
		<item>
		<title>[DevOps] Nginx Configuration 정리</title>
		<link>https://blog.wonizz.com/2020/10/20/nginx-configuration/</link>
					<comments>https://blog.wonizz.com/2020/10/20/nginx-configuration/#comments</comments>
		
		<dc:creator><![CDATA[워니]]></dc:creator>
		<pubDate>Tue, 20 Oct 2020 07:36:12 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1540</guid>

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

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

<h2>1. nginx의 동작 방식</h2>

nginx 의 가장 큰 특징은 <strong>비동기 Event Driven</strong>에 의한 Non Blocking 처리를 한다는 것입니다. apache 서버에 비해 메모리소모량이 젂어지면서 동시 처리수를 급격하게 늘릴 수 있습니다. 요청이 아무리 많아도 Process 또는 Thread 생성 비용이 존재하지 않습니다.

Single Thread 기반으로 <strong>Master / Worker</strong> 프로세스로 구동되면서 context switching을 하지 않기 떄문에 CPU 사용률을 감소 시킬 수 있습니다 .

먼저 apache의 동작 방식을 정리해보겠습니다.

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

<ul>
<li>Apache는 병렬 처리 동작방식은 기본적으로 Apache Process 기반 방식으로 클라이언트 요청들을 처리 합니다. 요청에 따라 프로세스를 생성하는 Multi Process Module-prefork 방식과 worker 방식이 있습니다.</li>
<li>요청에 따라 Process가 늘어나고 한개의 요청 처리중 다른 처리를 위한 Context switching으로 인해 부하가 걸림.</li>
</ul>

다음은 nginx의 동작방식에 대해서 정리하겠습니다.

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

<ul>
<li>Event Driven 방식으로 클라이언트 요청 병렬처리를 진행합니다. 기본적으로 싱글 프로세스 기반으로 이벤트를 받는 reactor와 이벤트를 각 worker로 전달하는 handler로 구성되어 있습니다.</li>
<li>process를 prefork하는 과정이 없이 요청온 request에 대한 행동에 대해서만 각 worker로 넘기고 계속해서 요청을 받기 떄문에 처리가 빠릅니다.</li>
<li>비동기 처리로 인한 메모리 사용이 효율적이다.</li>
</ul>

<h2>2. nginx configuration 정리</h2>

<a class="wp-editor-md-post-content-link" href="http://nginx.org/en/docs/" target="_blank" rel="noopener">nginx 공식 document</a>

<ul>
<li>최상단 모듈 (Core)</li>
</ul>

<pre><code class="line-numbers">user root;                              // 워커 프로세스의 권한을 지정한다. 
worker_processes 1;                     // auto도 무방하지만, 코어 수 만큼 할당하는 것이 보통입니다. 
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;                 // nginx의 마스터 프로세스 ID 정보가 저장됩니다. 
events {
    worker_connections 1024;            // 하나의 프로세스가 처리 할 수 있는 커넥션 수입니다. 
}
</code></pre>

<ul>
<li>http 블락</li>
</ul>

<pre><code class="line-numbers">http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main '[NGINX-ACCESS-LOG] [$time_local] $remote_addr to: $upstream_addr: $status: upstream $upstream_status $request upstream_response_time $upstream_response_time msec $request_time referer: [$http_referer] xff: [$proxy_add_x_forwarded_for] args: [$args] body: $request_body user-agent: [$http_user_agent]';

    sendfile on;                       // 응답을 보낼 때 바로 kernel file buffer를 사용하도록 하여, user-space의 buffuer 메모리를 사용하지 않아 보다 빠른 성능을 보장한다고 합니다.

    keepalive_timeout 65;              // 접속시 커넥션을 몇 초동안 유지할지에 대한 설정값.

    map_hash_bucket_size 10240;        // map 파일을 담을 버킷 사이즈 
    variables_hash_max_size 1024;
    variables_hash_bucket_size 128;
    server_tokens off;                 // NGINX의 버전을 숨길것인가에 대한 옵션이다. 보안상 주석을 제거하여 설정하는 것이 좋다.

    upstream disp_http {
        zone disp80 64k;
        server 127.0.0.1:8080;
    }

    map $uri $rd_mapping {
        include /etc/nginx/maps/*.map;
    }

    map $uri$is_args$args $rd_query_mapping {
        include /etc/nginx/maps_query/*.map;
    }
}

</code></pre>

<ul>
<li>server 블락</li>
</ul>

하나의 server 블락은 하나의 가상 호스트를 구성합니다. 또한 한 개 이상의 location 블락을 삽입할 수 있습니다.

<pre><code class="line-numbers"> server {
        listen 80;                                  //nginx의 가상호스트 포트
        access_log /var/log/nginx/access.log main;  
        error_log /var/log/nginx/error.log warn;

        root /efs/live/html;

        proxy_set_header Proxy "";                 //proxy 서버에 특정 헤더를 전달(proxy 헤더 제거)
        large_client_header_buffers 8 512k;        //대규모 클라이언트 요청 헤더를 읽을 때 사용 

        proxy_buffer_size 64k;                     //백엔드 서버 응답의 첫 부분을 읽기 위한 버퍼 크기를 설정하며, 여기에는 주로 간단한 헤더 데이터가 포함됩니다.
        proxy_buffers 4 64k;                       //백엔드 서버로부터의 응답 데이터를 읽는 데 사용할 버퍼의 수와 크기를 설정합니다.

        if ( $request_method !~ ^(GET|POST|OPTIONS)$ ) {
            return 405;
        }

        location / {

            if ($rd_mapping) {
                rewrite ^(.*)$ https://$http_host$rd_mapping permanent;
            }
            if ($rd_query_mapping) {
                rewrite ^(.*)$ https://$http_host$rd_query_mapping? permanent;
            }

            proxy_pass http://disp_http;

            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_intercept_errors on;

            error_page 403 404 405 500 501 503 @error_page;
        }


        location /etc/designs/smg/global/fonts/ {
            proxy_pass http://disp_http;
            add_header 'Access-Control-Allow-Origin' *;

            proxy_buffering on;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

    include /etc/nginx/locations/p4_redirection.location;
    include /etc/nginx/locations/error_page.location;
    include /etc/nginx/locations/static_files.location;
    }

</code></pre>

<ul>
<li>location 블락</li>
</ul>

<pre><code class="line-numbers">location / {

           //map파일을 통하는 처리를 위하여 다음과 같이 분기 
            if ($rd_mapping) {
                rewrite ^(.*)$ https://$http_host$rd_mapping permanent;
            }
            if ($rd_query_mapping) {
                rewrite ^(.*)$ https://$http_host$rd_query_mapping? permanent;
            }

            proxy_pass http://disp_http;

            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_intercept_errors on;

            error_page 403 404 405 500 501 503 @error_page;
        }
</code></pre>

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

이번시간에는 nginx의 설정에 대해서 간단히 정리를 해보았습니다. 이번 포스팅은 모든 지시어들을 다 정리하지는 않고,필자가 프로젝트에서 사용하는 지시어들 위주로 정리를 해보았습니다. 주로 reverse proxy 서버의 역할을 수행하면서 backend의 서버로 연결을 짓는 역할을 하고 있습니다.

또한 maps config를 통해서 redirection에 대한 처리와 error에 대한 처리도 같이 하고 있습니다. 이번 포스팅은 미완성으로 남겨두도록 하겠습니다. 앞으로 nginx에 대해 습득되는 지식에 대해서는 포스팅 업데이트를 하도록 하겠습니다. 다음시간에는 대비되는 웹서버인 apache에 대해서도 정리를 해보도록 하겠습니다.

<h2>4. 참고</h2>

<a class="wp-editor-md-post-content-link" href="https://taes-k.github.io/2019/03/08/server-nginx-event-driven/" target="_blank" rel="noopener">Nginx와 Apache의 구동방식 비교</a>

<a class="wp-editor-md-post-content-link" href="https://12bme.tistory.com/366" target="_blank" rel="noopener">엔진엑스 기본 환경 설정</a>
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2020/11/03/devops-apache-rewrite-rule/">[DevOps] Apache rewrite rule 정리</a></li><li><a href="https://blog.wonizz.com/2021/03/03/devops-rinetd-portforward/">[DevOps] Rinetd를 활용한 portforward</a></li><li><a href="https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/">[DevOps] Nginx Lua module 사용법</a></li><li><a href="https://blog.wonizz.com/2023/08/10/linux-logrotate/">[DevOps] Nginx Logrotation 설정</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/10/20/nginx-configuration/">[DevOps] Nginx Configuration 정리</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/10/20/nginx-configuration/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1540</post-id>	</item>
		<item>
		<title>[Linux] Load Average와 시스템 부하</title>
		<link>https://blog.wonizz.com/2020/09/14/linux-cpu-load-average/</link>
					<comments>https://blog.wonizz.com/2020/09/14/linux-cpu-load-average/#respond</comments>
		
		<dc:creator><![CDATA[워니]]></dc:creator>
		<pubDate>Mon, 14 Sep 2020 06:54:57 +0000</pubDate>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[Linux]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1453</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>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 리눅스의 Load Average에 대해서 정리하는 시간을 갖도록 하겠습니다. 필자의 아는 지인분이 저에게 물어본적이 있습니다. 지인 : TOP 명령어를 치고 나오는 Load Average가 뭘 의미하는지 알아요? 필자 : 로드 평균.... 로드가 걸린다....모르겠습니다. 사실 정의는 간단합니다. 이전에 정리해놓은 포스팅에서 R, D상태에 있는 job들의 갯수라고 보시면 됩니다. 즉, 현재 진행중인 job이거나 아니면 D상태로&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/09/14/linux-cpu-load-average/">[Linux] Load Average와 시스템 부하</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>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 리눅스의 Load Average에 대해서 정리하는 시간을 갖도록 하겠습니다.

필자의 아는 지인분이 저에게 물어본적이 있습니다.

<pre><code class="line-numbers">지인 : TOP 명령어를 치고 나오는 Load Average가 뭘 의미하는지 알아요?
필자 : 로드 평균.... 로드가 걸린다....모르겠습니다. 
</code></pre>

사실 정의는 간단합니다. 이전에 정리해놓은 포스팅에서 R, D상태에 있는 job들의 갯수라고 보시면 됩니다. 즉, 현재 진행중인 job이거나 아니면 D상태로 I/O와 같은 요청을 하고 잠시 대기 상태에 빠져있는 job들이 갯수 입니다.

<blockquote>
  얼마나 많은 프로세스가 실행 중 혹은 실행 대기중이냐를 의미하는 수치입니다. Load Average가 높다면 많은 수의 프로세스가 실행 중이거나 I/O 등을 처리하기 위한 대기 상태에 있다는 것이며, 낮다면 적은 수의 프로세스가 실행 중이거나 대기 중이라는 의미입니다.
</blockquote>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/09/Load_Avg_1.png?w=1200&#038;ssl=1" alt="Linux Load Average와 시스템 부하" />

위에 보시는 그림에서 각각 Load Average는 2에 가까운 수치가 나올 것입니다.

하지만, Core의 갯수에 따라 그 의미가 달라집니다. 왼쪽 그림은 Run Queu에 두 개의 프로세스가 있으며 이 경우 한 번에 하나만 실행되기 때문에 나머지 하나의 프로세스는 대기 상태에 있을 수 밖에 없습니다.

오른쪽 그림은 Run Queue에 두 개의 프로세스가 있지만 서로 다른 CPU에 있기 때문에 A와 B는 동시에 실행 될 수 있습니다. 현재 시스템에서 처리 가능한 만큼의 프로세스가 있다는 것입니다.

<h2>1. CPU Bound vs I/O Bound</h2>

앞선 Load Average의 개념에 대해서 정리를 했습니다. 서버에서 부하가 걸리는 원인은 크게 2가지를 꼽습니다.

<ul>
<li>CPU 부하</li>
<li>I/O 부하</li>
</ul>

<strong>CPU 부하가 높은 경우</strong>는 서버에서 실행되고 있는 프로그램 자체의 연산량이 많은 경우나 프로그램에 오류등이 발생하는 경우 입니다. 이러한 경우는 대게 Source Code 레벨에서 수정이 가능합니다. 오류 제거, 알고리즘의 시간, 공간 복잡도를 개선하여 대응 할 수 있습니다.

<strong>I/O 부하가 높은 경우</strong>는 서버에서 실행되고 있는 프로그램의 I/O가 많거나, DB나 하드디스크 등의 저장장치로의 접근이 많아 스왑이 발생하는 경우가 대부분입니다. 저장장치나 하드디스크로의 입출력이 빈번하게 발생하는 경우, 메모리 증설하는 방법으로 대응할 수 있습니다.

메모리 증설로 해결할 수 없는 경우 데이터 자체를 분산 (샤딩이나 파티셔닝) 하거나 캐시서버등을 도입하는 방안을 고려해 볼 수 있습니다.

부하를 일으키는 프로세스는 크게 두가지 종류로 나눌 수 있습니다.

<ul>
<li>nr_running</li>
<li>nu_uninterruptible</li>
</ul>

두 종류의 부하 프로세스는 같은 Load Average를 보여준다고 해도 사실 일으키고 있는 부하는 전혀 다른 부하이다.

<h2>2. vmstat으로 부하의 정체 확인하기</h2>

Load Average 값은 시스템에 부하가 있다는 것을 알려주지만 구체적으로 어떤 부하인지는 알 수 없습니다. 어떤 부하가 일어나는지에 대한 정보는 vmstat을 통해서 확인 할 수 있습니다.

<pre><code class="line-numbers">procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 1  0      0 293156 134388 21696656    0    0    30    76    0    1  3  2 94  0  0
</code></pre>

<pre><code class="line-numbers">r: The number of processes waiting for run time.
b: The number of processes in uninterruptible sleep.
</code></pre>

r은 실행되기를 기다리거나 현재 실행되고 있는 프로세스의 갯수를, b는 I/O를 위해 대기열에 있는 프로세스의 갯수를 말합니다. 즉 각각이 nr_running, nr_uninterruptible을 의미한다고 볼 수 있습니다.

<h2>3. Load Average가 보고하는 부하의 정체</h2>

시스템 부하의 원인이 대부분의 경우 CPU나 I/O에 있음을 나타내고 있습니다. Load Average로 시스템에 과부하가 걸리고 있다는 사실을 알게된 후에는, 한단계 더 나아가 CPU와 I/O중 어떤 부분에서 부하가 걸리는지를 조사해야 합니다.

CPU는 사용자 모드와 시스템 모드로 나뉘어집니다.

사용자 모드는 사용자 프로그램이 동작할 떄의 CPU 모드이며 시스템 모드는 커널이 동작할 때의 CPU 모드 입니다.

<pre><code class="line-numbers">15시 20분 01초     CPU     %user     %nice   %system   %iowait    %steal     %idle
15시 30분 01초     all      0.62      0.00      0.10      0.00      0.00     99.28
15시 40분 01초     all      0.75      0.00      0.14      0.00      0.00     99.11
15시 50분 01초     all      0.63      0.00      0.11      0.00      0.00     99.26
16시 00분 01초     all      0.64      0.00      0.13      0.00      0.00     99.23
16시 10분 01초     all      0.65      0.00      0.15      0.00      0.00     99.20
16시 20분 01초     all      0.63      0.00      0.11      0.00      0.00     99.26
16시 30분 01초     all      0.66      0.00      0.11      0.00      0.00     99.23
16시 40분 01초     all      0.65      0.00      0.12      0.00      0.00     99.23
16시 50분 01초     all      0.65      0.00      0.13      0.00      0.00     99.22
17시 00분 01초     all      0.64      0.00      0.11      0.00      0.00     99.25
17시 10분 01초     all      0.66      0.00      0.14      0.00      0.00     99.20
17시 20분 01초     all      0.69      0.00      0.19      0.00      0.00     99.12
17시 30분 01초     all      0.66      0.00      0.13      0.00      0.00     99.20
17시 40분 01초     all      0.65      0.00      0.14      0.00      0.00     99.21
17시 50분 01초     all      0.65      0.00      0.13      0.00      0.00     99.21
</code></pre>

<strong>sar</strong>명령어를 사용하면 부하를 시킨 경과 별로 확인할 수 있어 매우 편리합니다. 위의 결과에서 <strong>%user</strong>는 사용자 모드에서의 CPU 사용률을 나타내며 <strong>%system</strong>은 시스템 모드에서의 CPU 사용률을 나타냅니다.

<strong>%iowait</strong> 이 높은 상태이면 I/O가 시스템 부하의 원인이 될 수 있으며, 이때에는 I/O 관련하여 더 자세한 지표인 메모리 사용률이나 프로세스별 스왑 발생 상황등을 더 자세히 살펴본 후 적절히 대응할 수 있습니다.

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

사실 위의 내용을 정리하면서 2가지의 측정을 사용하였습니다. vmstat과 sar 입니다. 어쩃든 결론을 내리자면 부하의 원인에 대해서 어떠한 명령어가 됐든 확인을 해보고 판단을 내리자는 것을 배웠습니다. 크게 2가지 (cpu bound, i/o bound)에 대해서 분석을 수행 한 후, 원인을 일으키는 것이 어떤것인지를 접근하면 훨씬 편해지는것 같습니다.

다음 이시간에는 메모리의 대한 내용을 정리하고자 합니다. 많은 기대 부탁드립니다.
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2020/08/03/linux-command-top/">[Linux] top을 통해 살펴보는 프로세스 정보들</a></li><li><a href="https://blog.wonizz.com/2019/04/01/linux-apache-tomcat-connect/">[Linux] Apache HTTP 서버와 Tomcat 서버의 연동</a></li><li><a href="https://blog.wonizz.com/2019/04/01/linux-tomcat-server-config/">[Linux] 아파치 Tomcat Server.xml 설정</a></li><li><a href="https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/">[DevOps] Nginx Lua module 사용법</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/09/14/linux-cpu-load-average/">[Linux] Load Average와 시스템 부하</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/14/linux-cpu-load-average/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1453</post-id>	</item>
		<item>
		<title>[Linux] top을 통해 살펴보는 프로세스 정보들</title>
		<link>https://blog.wonizz.com/2020/08/03/linux-command-top/</link>
					<comments>https://blog.wonizz.com/2020/08/03/linux-command-top/#respond</comments>
		
		<dc:creator><![CDATA[워니]]></dc:creator>
		<pubDate>Mon, 03 Aug 2020 01:35:52 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1416</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>안녕하세요? 정리하는 개발자 워니즈 입니다. 이번시간부터 이어지는 포스팅들은 리눅스의 기본정리를 해보려고 합니다. 그동안 시스템 엔지니어 + DevOps 업무를 진행해 왔었습니다. 그런데 시스템적으로 확인해야될 부분에서는 아직은 기초가 부족하다고 생각이 많이 들었습니다. 그래서 DevOps와 SE를 위한 리눅스 커널이야기 라는 책을 읽고 해당 내용을 정리해보기로 했습니다. 이번포스팅부터는 개인적인 공부를 정리해둔 거라고 보시면 됩니다. 필자는 절대 저자와 아무런 관련이&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/08/03/linux-command-top/">[Linux] top을 통해 살펴보는 프로세스 정보들</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>
안녕하세요? 정리하는 개발자 워니즈 입니다. 이번시간부터 이어지는 포스팅들은 리눅스의 기본정리를 해보려고 합니다. 그동안 시스템 엔지니어 + DevOps 업무를 진행해 왔었습니다. 그런데 시스템적으로 확인해야될 부분에서는 아직은 기초가 부족하다고 생각이 많이 들었습니다.

그래서 <strong>DevOps와 SE를 위한 리눅스 커널이야기</strong> 라는 책을 읽고 해당 내용을 정리해보기로 했습니다. 이번포스팅부터는 개인적인 공부를 정리해둔 거라고 보시면 됩니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/08/top_1.png?w=1200&#038;ssl=1" alt="Linux top을 통해 살펴보는 프로세스 정보들 설명 이미지 1" />

<strong>필자는 절대 저자와 아무런 관련이 없음을 밝힙니다.</strong>

필자는 사실 공부하는 것(?)을 좋아합니다. 그냥 지식을 습득하는 것을 좋아하는 것 같습니다. 그러다보니 이러저러한 책들을, 특히나 IT 서적들을 많이 둘러보는데 이번에 위의 책을 알게 되었습니다. 리눅스의 커널단부터 시스템적인 요소를 하나하나씩 짚어보게끔 되어있습니다.

그래서 기왕 책 읽는거 정리하면서 보자는 마음으로 포스팅을 진행하게 되었습니다.

<h2>1. 시스템의 상태 살피기</h2>

top 명령은 시스템의 상태를 전반적으로 가장 빠르게 파악 할 수 있는 명령어 중 하나이다.

<strong>옵션없이 top 명령을 입력하면 3초의 간격으로 refresh 하면서 정보를 보여줍니다. 순간의 top 정보를 확인하기 위해서는 -b 옵션을 사용합니다.</strong>

필자가 처음 TA(Technical Architecture) 업무를 배우게 되면서 알게된 명령어 입니다. top명령어를 치면 다음과 같은 내용들이 보이는데, 처음에는 무슨 내용을 봐야하는지 몰랐습니다 .

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/08/top_2_1.png?w=1200&#038;ssl=1" alt="Linux top을 통해 살펴보는 프로세스 정보들 설명 이미지 2" />

<ul>
<li>up 200 days</li>
</ul>

현재 서버의 시간과 서버가 얼마나 구동되었는지 구동 시간이 나와 있습니다.

<ul>
<li>load average : 1.81, 1.44, 1.26</li>
</ul>

Load Average는 현재 시스템이 얼마나 많은 일을 하고 있는지를 보여주는 데이터로, 높으면 서버가 많은 일을 하고 있다고 볼 수 있습니다.

<ul>
<li>2 running, 353 sleeping</li>
</ul>

시스템에서 구동 중인 프로세스의 개를 나타냅니다.

<ul>
<li>VIRT, RES, SHR</li>
</ul>

프로세스가 사용하는 메모리의 양이 얼마인지를 확인할 수 있는 정보로, 이를 통해 프로세스에 메모리 누수가 있는지를 확인할 수 있어 중요한 정보중 하나입니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/08/top_3.png?w=1200&#038;ssl=1" alt="Linux top을 통해 살펴보는 프로세스 정보들 설명 이미지 3" />

<h2>2. VIRT, RES, SHR은 무엇인가요?</h2>

VIRT는 간단하게 프로세스에 할당된 가상 메모리 전체의 크기라고 보면 됩니다. 이것이 높다고해서 문제가 될 소지는 없습니다. RES는 그중 실제로 메모리에 올려서 사용하고 있는 물리 메모리의 크기, 그리고 SHR은 다른 프로세스와 공유하고 있는 메모리의 크기를 말합니다.

실제 사용하고 있는 메모리는 RES 영역이기 때문에 점유율이 높은 프로세스를 찾기 위해서는 RES 영역이 높은 프로세스를 찾아야 한다.

<h2>3. Memory Commit의 개념</h2>

VIRT는 프로세스가 커널로부터 사용을 하려고 예약받은 메모리라고 할 수 있습니다. malloc() 과 같은 시스템콜로 자신이 필요로 하는 메모리의 영역을 할당해 줄 것을 요청합니다. 이에 커널은 가용한 공간이 있따면 성공 메시지와 함께 해당 프로세스가 사용할 수 있도록 가상의 메모리 주소를 전달해 줍니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/08/top_4.png?w=1200&#038;ssl=1" alt="Linux top을 통해 살펴보는 프로세스 정보들 설명 이미지 4" />

그 후 프로세스가 할당받은 메모리 영역에 실제로 쓰기 작업을 하면 Page fault가 발생하며, 그제서야 커널은 실제 물리 메모리에 프로세스의 가상 메모리 공간을 매핑한다. 이것은 Page Table이라고 불리는 커널의 전역 변수로 관리된다. 그리고 이렇게 물리 메모리에 바인딩된 영역이 RES로 계산된다.

프로세스는 자신만의 작업 공간이 필요하고 그 공간은 메모리에 존재한다. 프로세스가 커널에 필요한 만큼의 메모리를 요청하면 커널은 프로세스에 사용 가능한 메모리 영역을 주고 실제로 할당은 하지 않지만 해당 영역을 프로세스에 주었따는 것을 저장합니다. 이 일련의 과정을 <strong>Memory Commit</strong>이라고 부릅니다.

<h2>4. 프로세스 상태 보기</h2>

<pre><code class="line-numbers">프로세스의 상태는 SHR 옆에 있는 S 항목으로 볼 수 있다. 어떤 항목들이 있을지 man 페이지 설명은 아래와 같다.
  S  --  Process Status
                The status of the task which can be one of:
                    'D' = uninterruptible sleep
                    'R' = running
                    'S' = sleeping
                    'T' = traced or stopped
                    'Z' = zombie
</code></pre>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/08/top_5.png?w=1200&#038;ssl=1" alt="Linux top을 통해 살펴보는 프로세스 정보들 설명 이미지 5" />

<ul>
<li><strong>D: uninterruptible sleep</strong></li>
</ul>

디스크 혹은 네트워크 I/O를 대기하고 있는 프로세스를 의미한다. 이 상태의 프로세스들은 대기하는 동안 Run Queue에서 빠져나와 Wait Queue에 들어가게 된다.

D 상태의 프로세스가 많으면 특정 요청이 끝나기를 기다리고 있는 프로세스가 많다는 뜻이고, 이 프로세스들은 요청이 끝나면 R 상태로 다시 돌아가야 하기 떄문에 시스템의 부하를 계산하는데 포함됩니다.

<ul>
<li><strong>R: running</strong></li>
</ul>

실행 중인 프로세스를 의미합니다. 실제로 CPU 자원을 소모하고 있는 프로세스 입니다.

<ul>
<li><strong>S: sleeping</strong></li>
</ul>

D 상태와의 가장 큰 차이점은 요청한 리소스를 즉시 사용할 수 있는지 여부입니다. 시스템 콜이나, 콘솔 입력을 기다리는 프로세스들은 Interruptible sleep 상태가 됩니다. S 상태의 프로세스가 많은 것은 시스템에 큰 영향을 끼치지 않습니다.

<ul>
<li><strong>Z: zombie</strong></li>
</ul>

포 프로세스가 죽은 자식 프로세스를 의미합니다. 좀비 프로세스가 실제로 시스템에 지대한 영향을 끼치는 것은 아니지만, PID가 정리가 되지 않고 쌓이면 새로운 프로세스에 할당할 PID가 모자르게 되고, 이는 결국 더이상 PID를 할당하지 못하여 고갈을 일으 킬 수 있습니다.

<h2>5. 프로세스 우선 순위</h2>

top을 통해 볼 수 있는 항목 중 PR과 NI 값을 살펴 봅니다. PR과 NI는 커널이 프로세스를 스케쥴링할 떄 사용하는 우선순위를 나타내는 값입니다. 프로세스 스케쥴링이 진행되는 구조는 다음과 같습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/08/top_6.png?w=1200&#038;ssl=1" alt="Linux top을 통해 살펴보는 프로세스 정보들 설명 이미지 6" />

스케줄러는 유휴 상태에 있던 프로세스가 깨어나거나 특정 프로세스가 스케줄링을 양보하는 등의 경우에 현재 Run Queu 에 있는 프로세스들 중 가장 우선순위가 높은 프로세스를 꺼내서 디스패처에 넘겨줍니다.

디스패처는 현재 실행중인 프로세스의 정보를 다른 곳에 저장한 후 넘겨 받은 프로세스의 정보를 가지고 다시 연산을 하도록 요청합니다.

<h2> </h2>
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2020/09/14/linux-cpu-load-average/">[Linux] Load Average와 시스템 부하</a></li><li><a href="https://blog.wonizz.com/2019/07/22/nodejs-pm2/">[Node.JS] 프로세스 관리도구 PM2 사용법</a></li><li><a href="https://blog.wonizz.com/2019/04/01/linux-apache-tomcat-connect/">[Linux] Apache HTTP 서버와 Tomcat 서버의 연동</a></li><li><a href="https://blog.wonizz.com/2019/04/01/linux-tomcat-server-config/">[Linux] 아파치 Tomcat Server.xml 설정</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/08/03/linux-command-top/">[Linux] top을 통해 살펴보는 프로세스 정보들</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/03/linux-command-top/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1416</post-id>	</item>
	</channel>
</rss>
