[NginX 웹서버] 환경 구성 방법 | 모니터링 | 기본 명령어 | 설정 예시 | 장단점 | NginX Apache 차이점 등 총정리

NginX 란?
대표적으로 사용되는 웹서버로 Apache, NginX가 있다. 엔진엑스는 경량화된 웹 서버로, 웹 서버뿐만 아니라 리버스 프록시 서버, 로드 밸런서, 캐시 서버 등 다양한 용도로 사용된다. Apache의 C10K(1만개의 클라이언트 문제) 문제점 해결을 위해 만들어진 Event-Driven 구조의 웹 서버 소프트웨어이다. 즉, 프로그램의 흐름이 이벤트에 의해 결정되는 방식으로 Apache보다 Nginx를 사용하는 이유 Nginx가 트래픽이 많은 웹 사이트에 더 적합하기 때문이다.
NginX 장점
- 한 개 또는 고정된 프로세스만 생성하고, 여러 개의 Connection을 모두 Event-Handler를 통해 비동기 방식으로 처리한다.
- 적은 양의 스레드만 사용되기 때문에 Context Swiching 비용이 적고, CPU 소모가 적다.
- Apache와 달리 동시 접속자 수가 많아져도 추가적인 생성 비용이 들지 않는다.
- CPU와 관계없이 모든 I/O들을 전부 Event Listener로 미루기 때문에 흐름이 끊기지 않고 응답이 빠르게 진행되어 1개의 프로세스로 더 빠른 작업이 가능하다.
이 덕분에 메모리를 적게 사용한다.
NginX 단점
- 동적 컨텐츠를 기본적으로 처리할 수 없습니다.
외부 프로세서로 전달하고 렌더링 된 컨텐츠를 다시 전송할 때 까지 기다려야 합니다. (프로세스 속도 저하) - Apache에 비해 다양한 모듈이 없습니다.
주요 명령어
1. Nginx 서비스 관리
# Nginx 시작
sudo systemctl start nginx
# Nginx 중지
sudo systemctl stop nginx
# Nginx 재시작
sudo systemctl restart nginx
# Nginx 설정 리로드 (서비스 중단 없이 설정만 새로고침)
sudo systemctl reload nginx
# Nginx 상태 확인
sudo systemctl status nginx
# 부팅 시 자동 시작 설정
sudo systemctl enable nginx
2. Nginx 프로세스 관리
# Nginx 프로세스 확인
ps -ef | grep nginx
# Nginx 강제 종료
sudo pkill nginx
3. 설정 관련 명령어
# Nginx 설정 테스트 (구문 오류 확인)
sudo nginx -t
# Nginx 설정 파일 위치 확인
sudo nginx -T | grep include
# Nginx 버전 확인
nginx -v
nginx -V # 상세 정보 (모듈 포함)
4. 로그 확인
# 액세스 로그 실시간 확인
sudo tail -f /var/log/nginx/access.log
# 에러 로그 확인
sudo tail -f /var/log/nginx/error.log
Nginx 기본 디렉토리 구조
- 설정 파일:
/etc/nginx/
- 메인 설정:
/etc/nginx/nginx.conf
- 사이트 설정:
/etc/nginx/sites-available/
,/etc/nginx/sites-enabled/
- 메인 설정:
- 로그 파일:
/var/log/nginx/
access.log
: 접근 로그error.log
: 에러 로그
- 웹 루트 디렉토리:
/usr/share/nginx/html/
(기본값, 설정에 따라 다를 수 있음)
기본적인 Nginx 설정 예제
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html index.htm;
}
location /api {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
}
Nginx 심화 가이드: 설정, 최적화, 문제 해결
1. 주요 구성 블록
# 전역 설정 (메인 워커 프로세스 관련)
user www-data;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# 이벤트 모델 설정
events {
worker_connections 1024;
use epoll; # Linux에서 고성능을 위한 설정
multi_accept on;
}
# HTTP 모듈 설정
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 로그 포맷 정의
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
# 성능 최적화 설정
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip 압축 설정
gzip on;
gzip_types text/plain text/css application/json application/javascript;
# 가상 호스트 설정 포함
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
2. 고급 위치(Location) 블록 매칭
location = /exact/match {
# 정확한 매칭 (우선순위 최상)
}
location ^~ /static/ {
# 접두사 기반 매칭 (정규식보다 우선)
}
location ~* \.(jpg|jpeg|png)$ {
# 대소문자 구분 없는 정규식
}
location ~ \.php$ {
# 대소문자 구분 정규식
}
location / {
# 일반적인 접두사 매칭 (가장 낮은 우선순위)
}
3. 리버스 프록시 고급 설정
upstream backend {
least_conn; # 로드 밸런싱 알고리즘
server backend1.example.com weight=5;
server backend2.example.com;
server backup.example.com backup;
keepalive 32; # 백엔드 연결 풀링
}
server {
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
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_buffers 16 32k;
proxy_buffer_size 64k;
proxy_read_timeout 90;
# 캐시 제어
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
}
}
4. 보안 강화 설정
# HTTPS 강제 적용
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# 보안 헤더
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options SAMEORIGIN;
add_header X-XSS-Protection "1; mode=block";
# SSL 설정
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_stapling on;
}
NginX 성능 최적화 기법
1.정적 파일 캐싱
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 1y;
add_header Cache-Control "public, no-transform";
access_log off;
}
2.워커 프로세스 튜닝
worker_processes auto; # CPU 코어 수에 맞춤
worker_rlimit_nofile 100000; # 열 수 있는 파일 디스크립터 수 증가
3. 커널 파라미터 조정
# 파일 디스크립터 제한 증가
echo "fs.file-max = 100000" >> /etc/sysctl.conf
sysctl -p
모니터링 및 문제 해결
1.상태 페이지
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
2.로그 분석 도구
# 상위 접근 IP 확인
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -n 20
# 응답 시간 분석
awk '{print $NF}' /var/log/nginx/access.log | sort -n | uniq -c
3.디버깅 모드
sudo nginx -t
sudo tail -f /var/log/nginx/error.log
sudo strace -p $(cat /var/run/nginx.pid)
NginX 흔한 문제와 해결 방법
1. 502 Bad Gateway: 백엔드 서비스 다운 또는 연결 시간 초과
proxy_read_timeout
값 증가 확인- 백엔드 서비스 상태 점검
2. 413 Request Entity Too Large
client_max_body_size 20M; # 업로드 크기 제한 증가
3. Too many open files
worker_rlimit_nofile 100000;
events {
worker_connections 50000;
}
Nginx는 이러한 고급 설정들을 통해 초당 수만 건의 요청을 처리할 수 있는 고성능 웹 서버로 운영될 수 있다. 서비스의 특성에 맞게 설정을 튜닝하는 것이 중요하다.
NginX와 Apache 차이점
Apache | NginX |
---|---|
요청 당 스레드 또는 프로세스가 처리하는 구조 | 비동기 이벤트 기반으로 요청 |
CPU/메모리 자원 낭비 심함 | CPU/메모리 자원 사용률 낮음 |
NginX보다 모듈이 다양 | Apache에 비해 다양한 모듈이 없음 |
PHP 모듈 등 직접 적재 가능 | 많은 접속자들 대응 가능 |
안정성, 확장성, 호환성 우세 | 성능 우세 |
동적 컨텐츠 단독 처리 가능 | 동적 컨텐츠 단독 처리 불가능 |
Apache와 NginX는 모두 강력하고 유연한 웹서버입니다. 어떤 웹서버가 더 좋다 라는 결론은 없습니다. 어떤 것을 사용할 지는 요구사항과 우선순위에 따라 크게 좌우됩니다.