Nginx 기초
Nginx의 설정 컨텍스트, server/location/upstream 구조, reverse proxy와 운영 점검 포인트를 정리한다.
Nginx가 담당하는 구간
Client
-> Nginx
-> WAS / Application
Nginx는 Web Server이면서 Reverse Proxy로 자주 쓰인다. 정적 파일을 응답하고, TLS를 종료하고, URI나 Host 기준으로 뒤쪽 서버에 요청을 넘긴다.
핵심 역할
Nginx는 이벤트 기반 구조로 동작하는 Web Server이며, 운영에서는 앞단 Reverse Proxy와 로드밸런서로 많이 사용된다.
설정 구조
Nginx 설정은 context 단위로 읽는다.
| Context | 역할 |
|---|---|
main | 전역 설정. worker_processes, 로그 기본값 등 |
events | connection 처리 방식 |
http | HTTP 전체 설정 |
server | 도메인과 포트 단위 가상 서버 |
location | URI 경로별 처리 |
upstream | 뒤쪽 서버 그룹 |
server는 “어떤 도메인과 포트로 들어왔는가”를 결정하고, location은 “어떤 경로를 어떻게 처리할
것인가”를 결정한다.
주요 파일
| 항목 | 경로 예시 |
|---|---|
| 메인 설정 | /etc/nginx/nginx.conf |
| 추가 설정 | /etc/nginx/conf.d/*.conf |
| 사이트 설정 | /etc/nginx/sites-available/, /etc/nginx/sites-enabled/ |
| 접근 로그 | /var/log/nginx/access.log |
| 에러 로그 | /var/log/nginx/error.log |
설정을 찾을 때는 nginx.conf에서 include를 먼저 확인한다. 실제 서비스 설정은 conf.d나
sites-enabled 아래에 분리되어 있는 경우가 많다.
정적 파일 예시
server {
listen 80;
server_name example.com;
root /var/www/example;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
root는 요청 URI를 파일 시스템 경로에 붙인다. /images/a.png 요청이면
/var/www/example/images/a.png를 찾는다.
Reverse Proxy 예시
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Tomcat이 8080에서 동작하고 Nginx가 80을 받는 구조다. 이때 WAS는 직접 클라이언트를 보는 것이
아니라 Nginx가 넘겨준 요청을 본다.
upstream 예시
upstream tomcat_backend {
server 127.0.0.1:8080 max_fails=3 fail_timeout=10s;
server 127.0.0.1:8081 max_fails=3 fail_timeout=10s;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://tomcat_backend;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
upstream은 여러 backend를 하나의 이름으로 묶는다. 세션을 서버 메모리에만 저장하는 애플리케이션이면
로드밸런싱과 세션 유지 방식을 함께 봐야 한다.
점검 명령
nginx -t
nginx -T
nginx -s reload
systemctl status nginx
systemctl reload nginx
ss -lntp | grep nginx
tail -f /var/log/nginx/error.log
nginx -t는 문법 검사, nginx -T는 include까지 합쳐진 전체 설정 출력이다. 설정 파일이 여러 곳에
흩어져 있을 때는 nginx -T가 특히 유용하다.
장애에서 먼저 볼 것
| 증상 | 확인 지점 |
|---|---|
| 404 | server_name, location, root, try_files |
| 502 | proxy_pass 대상, backend 포트, Tomcat 상태 |
| 504 | proxy_read_timeout, backend 응답 지연 |
| redirect loop | X-Forwarded-Proto, 애플리케이션 HTTPS 인식 |
| 실제 IP 누락 | X-Forwarded-For, X-Real-IP, 앞단 LB/WAF 헤더 |
관련 문서
관련 블로그 기록
- NGINX 부하분산 (HTTP / TCP) — Nginx upstream과 부하분산을 다룬 사례
- LB·WAF 뒤에서 클라이언트 실제 IP 살리기 — 프록시 헤더를 추적한 사례
공식 문서
닫기 전 질문
- 요청은 어느
serverblock에 매칭되는가? - 요청 URI는 어느
location에 매칭되는가? - Nginx가 직접 응답하는가,
proxy_pass로 넘기는가? - WAS가 알아야 할 원래 Host, IP, Scheme 정보가 전달되는가?