πŸ”§ DevOps

Nginx

Engine X

A high-performance web server and reverse proxy. Widely used for serving static files, load balancing, and as an API Gateway.

πŸ“– Detailed Explanation

Nginx (pronounced "Engine X") is open-source software used as a high-performance HTTP server, reverse proxy, load balancer, and mail proxy. With its event-driven asynchronous architecture, it handles concurrent connections efficiently and can process more requests with less memory than Apache, which has made it a standard of modern web infrastructure.

The main uses of Nginx are static file serving, reverse proxy, load balancing, and SSL termination. It quickly serves static files (HTML, CSS, JS, images) and proxies dynamic requests to backend application servers (Node.js, Python, Java, etc.). It also acts as a load balancer that distributes traffic among multiple backend servers.

As a reverse proxy, Nginx sits between clients and backends and handles common functions such as SSL certificate management, request compression, caching, and adding security headers. Backend servers can focus solely on business logic, while Nginx takes care of web-layer concerns.

In a Kubernetes environment, the Nginx Ingress Controller routes external traffic to services inside the cluster. Domain-based routing, path-based routing, TLS termination, rate limiting, and more are managed declaratively as Kubernetes resources.

πŸ’» Code Example

# /etc/nginx/nginx.conf - ν”„λ‘œλ•μ…˜ μ„€μ • 예제
user nginx;
worker_processes auto;  # CPU μ½”μ–΄ μˆ˜μ— 맞게 μžλ™ μ„€μ •
error_log /var/log/nginx/error.log warn;

events {
    worker_connections 4096;  # λ™μ‹œ μ—°κ²° 수
    use epoll;  # Linux μ΅œμ ν™”
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # 둜그 포맷 (JSON)
    log_format json_combined escape=json '{"time":"$time_iso8601",'
        '"remote_addr":"$remote_addr","method":"$request_method",'
        '"uri":"$uri","status":$status,"body_bytes_sent":$body_bytes_sent,'
        '"request_time":$request_time,"upstream_time":"$upstream_response_time"}';

    access_log /var/log/nginx/access.log json_combined;

    # μ„±λŠ₯ μ΅œμ ν™”
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    gzip on;
    gzip_types text/plain application/json application/javascript text/css;

    # Upstream λ°±μ—”λ“œ μ •μ˜
    upstream api_backend {
        least_conn;  # μ—°κ²° 수 기반 λ‘œλ“œλ°ΈλŸ°μ‹±
        server api-1:8080 weight=3;
        server api-2:8080 weight=2;
        server api-3:8080 backup;
        keepalive 32;  # μ—°κ²° μž¬μ‚¬μš©
    }

    server {
        listen 80;
        server_name example.com;
        return 301 https://$server_name$request_uri;  # HTTPS λ¦¬λ‹€μ΄λ ‰νŠΈ
    }

    server {
        listen 443 ssl http2;
        server_name example.com;

        ssl_certificate /etc/nginx/ssl/cert.pem;
        ssl_certificate_key /etc/nginx/ssl/key.pem;
        ssl_protocols TLSv1.2 TLSv1.3;

        # 정적 파일
        location /static/ {
            alias /var/www/static/;
            expires 1y;
            add_header Cache-Control "public, immutable";
        }

        # API ν”„λ‘μ‹œ
        location /api/ {
            proxy_pass http://api_backend;
            proxy_http_version 1.1;
            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;

            # νƒ€μž„μ•„μ›ƒ
            proxy_connect_timeout 5s;
            proxy_read_timeout 60s;
        }
    }
}
# Kubernetes Ingress μ„€μ • 예제
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: api-ingress
  annotations:
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-body-size: "10m"
    nginx.ingress.kubernetes.io/rate-limit: "100"
    nginx.ingress.kubernetes.io/rate-limit-window: "1m"
spec:
  ingressClassName: nginx
  tls:
    - hosts: [api.example.com]
      secretName: api-tls
  rules:
    - host: api.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: api-service
                port:
                  number: 80

πŸ—£οΈ How It's Said in Practice

DevOps: "Let's put Nginx in front of the API server to handle SSL termination and rate limiting. Handling it directly in the application is a burden."

Junior: "Then how do we renew certificates in Nginx?"

Senior: "If you integrate cert-manager with Let's Encrypt, they're renewed automatically. On Kubernetes, you just add an annotation to the Ingress."

Interviewer: "Do you have experience setting up high availability with Nginx?"

Candidate: "Yes, I used Nginx as a reverse proxy and load-balanced across 3 API servers. I configured health_check on the upstream so that failed servers were automatically excluded, and I reused connections with keepalive to reduce latency. I terminated SSL at Nginx and used HTTP between Nginx and the backend, which simplified certificate management."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

Reviewer: "Watch out for the trailing slash in proxy_pass. With `location /api/` and `proxy_pass http://backend;`, /api/ is included, but with `proxy_pass http://backend/;`, /api/ is removed."

Author: "Ah, so that's why requests were arriving at the backend with /api/ still attached. I'll add the trailing slash."

⚠️ Cautions

πŸ“š Learn More