Nginx는 고성능의 오픈 소스 웹 서버 소프트웨어로 많은 웹 서버와 리버스 프록시로 널리 사용된다.
apache 웹서버의 경우 요청마다 새로운 쓰레드를 생성하여 요청을 처리하기 때문에 요청이 많을수록 자원이 많이 소요된다.
반면 Nginx의 주요 특징 중 하나는 비동기 이벤트 기반 아키텍처로, 많은 동시 접속 요청을 효율적으로 처리하여 웹 사이트나 애플리케이션의 응답 속도와 성능을 향상 시킨다.
nginx는 설정파일을 읽고 유효성을 검사하는 master process와 요청을 처리하는 work process로 구성된다. nginx는 event-driven모델을 사용하는데, worker process 사이에 요청을 효율적으로 분배하기 위해 OS에 의존적인 매커니즘을 사용한다. worker process의 개수는 설정 파일에 정의되고, 정의된 프로세스 개수와 사용가능한 CPU 코어 숫자에 맞게 자동으로 조정된다.
nginx는 nginx.conf라는 설정 파일에 설정된 값을 통해 작동한다.
nginx.conf는 기본적으로 /etc/nginx/nginx.conf에 위치하고 해당 위치에 없으면 /usr/local/nginx/conf/nginx.conf 또는 /usr/local/etx/nginx/nginx.conf 경로에 위치한다
nginx는 reverse proxy로도 활용할 수 있다. 클라이언트와 서버 사이에서 중개자 역할을 하여 요청들을 설정에 따라 알맞은 내부 서버로 접근할 수 있도로 곧와주는 서버이다. 이를 통해서 내부 서버의 외부 노출을 방지하고, SSL 사용등을 통한 보안과 요청을 분산시키는 로드 밸런싱의 역할을 할 수 있다.
아래는 80포트로 들어오는 요청을 127.0.1:8001 서버로 전달하도록 설정되어 있다. 만약에 listen 으로 포트 설정이 되어있지 않으면 기본값인 80으로 설정된다.
http {
server {
listen 80;
location / {
proxy_pass http://127.0.0.1:8001;
}
}
}
server {
listen 80;
server_name example.com;
# HTTP → HTTPS 리다이렉트
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
# SSL 인증서 경로 (Let's Encrypt 예시)
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# Frontend
location / {
proxy_pass http://frontend:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
# Backend API
location /api {
proxy_pass http://backend:10001;
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;
}
}
volume을 통해 외부의 nginx.conf를 컨테이너 내부와 공유한다. /etx/nginx/nginx.conf에 외부에서 설정한 nginx.conf를 공유하여 해당 설정으로 웹서버가 실행되도록 한다.
version: '3'
services:
nginx:
image: nginx:latest
ports:
- 80:80
- 443:443
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- /etc/letsencrypt:/etc/letsencrypt
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com
자체 서명 시:
openssl req -x509 -newkey rsa:4096 -keyout privkey.pem -out fullchain.pem -days 365 -nodes
그리고 nginx에서 해당 경로를 사용