티스토리 뷰

Programming/Web

NGINX 기본 캐시 설정

혤혤혤 2017. 2. 7. 11:51

원문:https://www.nginx.com/blog/nginx-caching-guide/

필요한 부분만 번역했습니다.

The Basics (기본)

A web cache sits in between a client and an “origin server”, and saves copies of all the content it sees. If a client requests content that the cache has stored, it returns the content directly without contacting the origin server. This improves performance as the web cache is closer to the client, and more efficiently uses the application servers because they don’t have to do the work of generating pages from scratch each time.

웹캐시는 본 서버와 클라이언트 사이에 위치한다. 그리고 모든 컨텐츠의 사본을 저장한다. 클라이언트가 캐시에 저장된 컨텐츠를 요구할 경우 그것은 본 서버와의 연결 없이 바로 반환 된다. 매번 페이지를 그리는 작업을 하지 않기때문에 훨씬더 효율적으로 사용된다. 

There are potentially multiple caches between the web browser and the application server: the client’s browser cache, intermediary caches, content delivery networks (CDNs), and the load balancer or reverse proxy sitting in front of the application servers. Caching, even at the reverse proxy/load balancer level, can greatly improve performance.

잠재적으로 앱서버와 웹브라우저 사이에는 복수의 캐시가 있다. : 클라이언트의 브라우저 캐시, 중계 캐시들, 컨텐트 전송 네트워크(CDNS), 그리고 로드 발랜서 또는 앱서버 앞단의 리버스 프록시 씨팅. 로드 발랜서와 리버스 프록시의 단계에서 캐시를 하는 것은 수행능력을 눈에띄게 향상시킬 수 있다. 

NGINX is commonly deployed as a reverse proxy or load balancer in an application stack and has a full set of caching features. The next section discusses how to configure basic caching with NGINX.

NGINX는 일반적으로 앱 스택에서 리버스 프록시 또는 로드 밸런서로 배포된다. 그리고 캐시 요소의 전체 집합을 갖고 있다. 다음 세션은 NGINX에서 기본 캐시를 설정하는 방법에 대해서 논의 한다. 

How to Setup and Configure Basic Caching

Only two directives are needed to enable basic caching: proxy_cache_path and proxy_cache. The proxy_cache_path directive sets the path and configuration of the cache, and the proxy_cache directive activates it.

기본 캐시를 위해서는 2개의 지시자가 필요하다. proxy_cache_path 와 proxy_cache 이다. proxy_cache_path 지시자는 경로와 캐시의 형상을 설정하고 proxy_cache 지시자는 그것을 활성화 시킨다. 

proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g
                 inactive=60m use_temp_path=off;

server { ... location / { proxy_cache my_cache; proxy_pass http://my_upstream; } }

The parameters to the proxy_cache_path directive define the following settings:

proxy_cache_path 지시자는 다음과 같은 설정 인자를 갖는다. 

  • The local disk directory for the cache is called /path/to/cache/
  • 캐시가 호출되면 불리는 로컬 디스크 폴더 
  • levels sets up a two‑level directory hierarchy under /path/to/cache/. Having a large number of files in a single directory can slow down file access, so we recommend a two‑level directory hierarchy for most deployments. If the levels parameter is not included, NGINX puts all files in the same directory.
  • levels은 2단계 디렉토리 계층을 /path/to/cache/ 하위에 설정한다. 하나의 디렉토리에 너무 많은 파일을 갖고 있을 경우 파일에 접근하는데 많은 시간이 소요된다. 2단계 디렉토리 계층을 권장한다. 만약 이 levels 파라미터가 포함되지 않았을 경우 NGINX는 모든 파일을 한 디렉토리에 저장한다. 
  • keys_zone sets up a shared memory zone for storing the cache keys and metadata such as usage timers. Having a copy of the keys in memory enables NGINX to quickly determine if a request is a HIT or a MISS without having to go to disk, greatly speeding up the check. A 1‑MB zone can store data for about 8,000 keys, so the 10‑MB zone configured in the example can store data for about 80,000 keys.
  • keys_zone 은 캐시의 키들을 저장하기 위해 공유되는 메모리 영역과 사용 타이머와 같은 메타데이터를 설정한다. 메모리에 이 키들의 사본을 갖고 있는 것은 NGINX를 더 빠르게 요청이 HIT인지 MISS인지를 결정할 수 있도록 도와준다. 
  • max_size sets the upper limit of the size of the cache (to 10 gigabytes in this example). It is optional; not specifying a value allows the cache to grow to use all available disk space. When the cache size reaches the limit, a process called the cache manager removes the files that were least recently used to bring the cache size back under the limit.
  • max_size는 최대 캐시사이즈의 제한을 정한다. (여기서는 10GB). 옵션값이다. 특정값을 정하지 않으면 캐시가 사용 가능한 모든 공간을 사용할 수 있도록 허락 한다. 캐시 크기가 최대 사용용량에 도달하면 캐시 매니저가 최근에 사용하지 않은 파일을 지우는 프로세스를 진행한다. 
  • inactive specifies how long an item can remain in the cache without being accessed. In this example, a file that has not been requested for 60 minutes is automatically deleted from the cache by the cache manager process, regardless of whether or not it has expired. The default value is 10 minutes (10m).Inactive content differs from expired content. NGINX does not automatically delete content that has expired as defined by a cache control header (Cache‑Control:max‑age=120 for example). Expired (stale) content is deleted only when it has not been accessed for the time specified by inactive. When expired content is accessed, NGINX refreshes it from the origin server and resets the inactive timer.
  • inactive 는얼마나 오래 하나의 아이템이 캐시에 접근되지 않는 상태로 남아 있을 수 있는지 설정한다. 여기에서는 하나의 파일은 요청이 60분 동안 없을 경우 캐시 매니저에 의해서 자동적으로 삭제된다. 이때 유효기간은 무시된다. NGINX 는 캐시 컨트롤에 유효기간이 정의된 컨텐츠를 자동적으로 삭제 하지 않는다. (예에서는  Cache‑Control:max‑age=120 ) 유효기간이 지난 컨텐츠는 inactive에 의해서 정의된 시간만큼 접근이 없었을때 삭제된다. 만약 유효기간이 지난 컨텐츠에 접근이 되면, NGINX는 이것을 본 서버로부터 새로고침하고 inactive 타이머를 재설정 한다. 
  • NGINX first writes files that are destined for the cache to a temporary storage area, and the use_temp_path=off directive instructs NGINX to write them to the same directories where they will be cached. We recommend that you set this parameter to off to avoid unnecessary copying of data between file systems. use_temp_path was introduced in NGINX version 1.7.10 and NGINX Plus R6.
  • NGINX 는 캐시를 위한 임시 저장소 영역에 파일을 처음 작성한다.그리고 use_temp_path=off 지시자는 NGINX가 그들이 캐시된 곳과 같은 디렉토리에 쓰도록 지시한다. 우리는 이 인자를 off로 설정해 불필요 한 데이터의 사본이 생기는 것을 방지하는 것을 권장한다. use_temp_path는 NGINX 1.7.10과 NGINX PLUS R6에서 처음 소개 되었다. 

And finally, the proxy_cache directive activates caching of all content that matches the URL of the parent location block (in the example, /). You can also include the proxy_cache directive in a server block; it applies to all location blocks for the server that don’t have their own proxy_cache directive.

그리고 마지막으로 proxy_cache는 해당 부모 Location 블록에 URL과 매치되는 모든 컨텐츠의 캐시를 활성화 하는 지시자 이다. (예에서는 /). 당신은 또한 proxy_cache를 Server 블록에 포함할 수 있다. 이것은 해당 서버 안의 자기 Location블록 안에 proxy_cache 지시자를 갖고 있지 않은 모든 Location 블록에 적용된다. 


Delivering Cached Content When the Origin is Down

 (원본이 다운되었을때 캐시된 컨텐츠를 전달)

A powerful feature of NGINX content caching is that NGINX can be configured to deliver stale content from its cache when it can’t get fresh content from the origin servers. This can happen if all the origin servers for a cached resource are down or temporarily busy. Rather than relay the error to the client, NGINX delivers the stale version of the file from its cache. This provides an extra level of fault tolerance for the servers that NGINX is proxying, and ensures uptime in the case of server failures or traffic spikes. To enable this functionality, include the proxy_cache_use_stale directive:

NGINX의 컨텐츠 캐이의 강력한 요소는 NGINX가 새로운 컨텐츠를 본 서버로부터 가져오지 못할때 오래된 컨텐츠를 캐시로 부터 가져와서 전달 할 수 있다는 것이다. 이것은 캐시를 위한 본 서버가 다운되거나 임시적으로 너무 바빠서 새로운 컨텐츠를 본 서버에서 가져오지 못할때 발생한다. 클라이언트에게 에러를 전달 하는 것보다 NGINX는 캐시된 오래된 버전의 파일을 전달 한다. 이것은 NGINX가 프록시 하는 서버에 대해서 추가적인 단계에서 결함을 보완하고 서버 오류와 트래픽 급증에 대해서 서버의 가동시간을 보장합니다. 기능적으로 활성화 하기 위해서는 다음 proxy_cache_use_stale 지시자를 사용한다. 

location / {
    ...
    proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
}

With this sample configuration, if NGINX receives an errortimeout, or any of the specified 5xx errors from the origin server and it has a stale version of the requested file in its cache, it delivers the stale file instead of relaying the error to the client.

위의 예 설정에서는, 만약 NGINX가 에러를 받거나 타임아웃, 또는 다른 5XX 에러들을 본 서버로부터 받을 경우 그것의 캐시로 부터 요청된 파일의 오래된 버전을 서비스 한다. 클라이언트에게 에러를 전송하지 않고 오래된 버전의 파일을 전송한다. 



참고: https://www.joinc.co.kr/w/man/12/nginx/static

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함