캐시의 개념와 Nginx 프록시 캐시
웹 서비스의 트래픽이 증가하면 백엔드 서버의 부하를 줄이고 응답 속도를 높이기 위해 캐싱 메커니즘이 필수적으로 사용됩니다. 캐시는 주로 서버 측 캐시, 프록시 캐시, 클라이언트 브라우저 캐시로 구분됩니다. Nginx는 프록시 레벨에서 백엔드의 응답 콘텐츠를 저장하여 동일한 요청이 들어올 경우 백엔드까지 전달하지 않고 캐시된 데이터를 직접 반환하는 기능을 제공합니다.
주요 캐시 지시어(Directives)
Nginx에서 프록시 캐시를 구성하기 위해 사용되는 핵심 지시어들은 다음과 같습니다.
proxy_cache: 캐시 영역의 활성화 여부를 설정합니다. (Context: http, server, location)proxy_cache_path: 캐시 파일이 저장될 경로와 메모리 할당 크기 등을 정의합니다. (Context: http)proxy_cache_valid: HTTP 응답 코드별 캐시 유지 시간을 지정합니다. (Context: http, server, location)proxy_cache_key: 캐시를 식별하고 구분하기 위한 고유 키(Key) 문자열 조합을 설정합니다. (Context: http, server, location)
캐시 경로 및 만료 시간 설정
proxy_cache_path를 통해 캐시 저장 경로, 디렉토리 계층 구조, 공유 메모리 크기, 최대 디스크 사용량 등을 제어할 수 있습니다. proxy_cache_valid는 상태 코드에 따라 캐시 만료 주기를 다르게 설정할 때 유용합니다.
http {
proxy_cache_path /data/nginx/cache_dir levels=1:2 keys_zone=my_cache_zone:10m max_size=5g inactive=30m use_temp_path=off;
}
server {
location / {
proxy_cache my_cache_zone;
proxy_cache_valid 200 302 1h;
proxy_cache_valid 404 2m;
proxy_cache_valid any 5m;
}
}
캐시 키 구성
기본적으로 $scheme$proxy_host$request_uri 조합이 사용되지만, 요청의 특성에 맞게 키를 세분화할 수 있습니다. 파라미터가 중요한 동적 요청의 경우 쿼리 스트링까지 포함하여 키를 생성해야 정확한 캐싱이 가능합니다.
proxy_cache_key "$host$request_uri";
프록시 캐시 구성 실습
이 실습에서는 프론트엔드 프록시 서버(192.168.10.10)와 백엔드 웹 서버(192.168.10.20) 두 대를 가정합니다.
백엔드 웹 서버 설정 (192.168.10.20)
여러 포트에서 정적 파일을 서빙하도록 Nginx를 설정합니다.
mkdir -p /var/www/app1 /var/www/app2
echo "App1 Page" > /var/www/app1/index.html
echo "App2 Page" > /var/www/app2/index.html
server {
listen 8001;
root /var/www/app1;
index index.html;
}
server {
listen 8002;
root /var/www/app2;
index index.html;
}
프론트엔드 프록시 서버 설정 (192.168.10.10)
백엔드 서버로 요청을 전달하며, 응답을 캐싱하는 설정을 추가합니다. 캐시 적중 여부를 확인하기 위해 응답 헤더에 X-Cache-Status를 추가합니다.
upstream backend_nodes {
server 192.168.10.20:8001;
server 192.168.10.20:8002;
}
proxy_cache_path /data/nginx/cache_dir levels=1:2 keys_zone=my_cache_zone:10m max_size=5g inactive=30m use_temp_path=off;
server {
listen 80;
server_name proxy.example.com;
location / {
proxy_pass http://backend_nodes;
proxy_cache my_cache_zone;
proxy_cache_valid 200 302 1h;
proxy_cache_valid any 5m;
proxy_cache_key $host$uri$is_args$args;
add_header X-Cache-Status $upstream_cache_status;
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
}
}
클라이언트에서 curl -I http://proxy.example.com/index.html로 요청을 보내면 첫 번째 요청 시 X-Cache-Status: MISS가 반환되며, 두 번째 요청부터는 X-Cache-Status: HIT가 반환되어 캐싱이 정상적으로 동작함을 확인할 수 있습니다.
캐시 데이터 삭제 방법
캐시된 데이터를 강제로 삭제해야 하는 경우 다음 두 가지 방법을 사용할 수 있습니다.
1. 파일 시스템 직접 삭제
가장 단순한 방법으로 캐시 디렉토리의 파일을 직접 삭제합니다.
rm -rf /data/nginx/cache_dir/*
2. ngx_cache_purge 모듈 활용
특정 URL의 캐시만 선별적으로 삭제하려면 서드파티 모듈인 ngx_cache_purge를 컴파일하여 설치해야 합니다.
wget http://nginx.org/download/nginx-1.22.0.tar.gz
tar xzf nginx-1.22.0.tar.gz
wget https://github.com/FRiCKLE/ngx_cache_purge/archive/2.3.tar.gz
tar xzf 2.3.tar.gz
cd nginx-1.22.0
./configure --prefix=/opt/nginx --add-module=../ngx_cache_purge-2.3
make && make install
설치 후 Nginx 설정 파일에 캐시 삭제를 위한 location 블록을 추가합니다.
location ~ /purge(/.*) {
allow 127.0.0.1;
allow 192.168.10.0/24;
deny all;
proxy_cache_purge my_cache_zone $host$1$is_args$args;
}
설정 적용 후 브라우저나 curl을 통해 /purge/캐시대상경로로 요청을 보내면 해당 캐시가 삭제됩니다.
특정 경로 캐싱 제외
로그인, 회원가입, 관리자 페이지 등 동적인 처리가 필요하거나 캐싱되면 안 되는 특정 URI는 proxy_no_cache 지시어를 사용하여 캐싱 대상에서 제외할 수 있습니다.
server {
listen 80;
server_name proxy.example.com;
if ($request_uri ~ ^/(login|register|admin)) {
set $skip_cache 1;
}
location / {
proxy_pass http://backend_nodes;
proxy_cache my_cache_zone;
proxy_cache_valid 200 302 1h;
proxy_cache_valid any 5m;
proxy_cache_key $host$uri$is_args$args;
proxy_no_cache $skip_cache;
proxy_no_cache $http_authorization;
add_header X-Cache-Status $upstream_cache_status;
}
}
캐시 적중률 로깅
액세스 로그에 $upstream_cache_status 변수를 추가하여 어떤 요청이 캐시에서 처리되었는지(HIT/MISS) 추적할 수 있습니다.
log_format cache_stats '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'Cache-Status: "$upstream_cache_status"';
server {
listen 80;
server_name proxy.example.com;
access_log /var/log/nginx/proxy_access.log cache_stats;
location / {
proxy_cache my_cache_zone;
# 기타 캐시 설정...
}
}