728x90

TCP 프록시 부하 분산은 인터넷에서 들어오는 TCP 트래픽을 Google Cloud VPC 네트워크의 가상 머신(VM) 인스턴스로 배포하는 역방향 프록시 부하 분산기입니다. TCP 프록시 부하 분산을 사용하면 TCP 연결을 통해 들어오는 트래픽이 부하 분산 레이어에서 종료된 후 TCP 또는 SSL을 통해 사용 가능한 가장 가까운 백엔드로 전달됩니다.

TCP 프록시 부하 분산을 사용하면 전 세계 모든 사용자의 단일 IP 주소를 사용할 수 있습니다. TCP 프록시 부하 분산기는 자동으로 트래픽을 사용자와 가장 가까운 백엔드로 라우팅합니다.

프리미엄 등급에서 TCP 프록시 부하 분산을 전역 부하 분산 서비스로 구성할 수 있습니다. 표준 등급을 사용하면 TCP 프록시 부하 분산기가 리전별 부하 분산을 처리합니다. 자세한 내용은 네트워크 서비스 등급의 부하 분산기 동작을 참조하세요.

이 예시에서 서울 및 보스턴에 있는 사용자의 트래픽 연결은 부하 분산 레이어에서 종료됩니다. 이러한 연결은 1a  2a로 표시되어 있습니다. 부하 분산기에서 선택한 백엔드 인스턴스로 별도의 연결이 설정됩니다. 이러한 연결은 1b  2b로 표시되어 있습니다.

TCP 종료를 사용하는 Cloud Load Balancing(확대하려면 클릭)

TCP 프록시 부하 분산은 SMTP(Simple Mail Transfer Protocol)의 포트 25와 같이 잘 알려진 특정 포트의 TCP 트래픽용입니다. 자세한 내용은 포트 사양을 참조하세요. 동일한 포트에서 암호화되는 클라이언트 트래픽의 경우 SSL 프록시 부하 분산을 사용합니다.

Google Cloud 부하 분산기의 차이점에 대한 자세한 내용은 다음 문서를 참조하세요.

장점

다음은 TCP 프록시 부하 분산기의 몇 가지 이점입니다.

  • IPv6 종료. TCP 프록시 부하 분산은 클라이언트 트래픽의 IPv4 주소 및 IPv6 주소를 모두 지원합니다. 클라이언트 IPv6 요청은 부하 분산 레이어에서 종료된 후 IPv4를 통해 백엔드로 프록시 처리됩니다.
  • 지능형 라우팅. 부하 분산기는 용량이 있는 백엔드 위치로 요청을 라우팅할 수 있습니다. 반대로 L3/L4 부하 분산기는 용량에 관계없이 리전 백엔드로 라우팅해야 합니다. 더 스마트한 라우팅을 사용하면 x*N이 아니라 N+1 또는 N+2에서 프로비저닝할 수 있습니다.
  • 보안 패치 적용. TCP 스택에 취약점이 발생하면 Cloud Load Balancing은 백엔드가 안전하게 유지되도록 자동으로 부하 분산기에 패치를 적용합니다.
  • 가장 많이 사용되는 TCP 포트 지원: 25, 43, 110, 143, 195, 443, 465, 587, 700, 993, 995, 1883, 3389, 5222, 5432, 5671, 5672, 5900, 5901, 6379, 8085, 8099, 9092, 9200, 9300.

참고: TCP 프록시 부하 분산은 TCP 포트 80 또는 8080을 지원하지 않습니다. HTTP 트래픽의 경우 외부 HTTP(S) 부하 분산을 사용합니다.

네트워크 서비스 등급의 부하 분산기 동작

TCP 프록시 부하 분산을 프리미엄 등급의 전역 부하 분산 서비스와 표준 등급의 리전 서비스로 구성할 수 있습니다.

프리미엄 등급

백엔드 서비스 하나만 가질 수 있으며 백엔드 서비스는 여러 리전에서 백엔드를 가질 수 있습니다. 전역 부하 분산의 경우 백엔드를 여러 리전에 배포하면 부하 분산기에서 자동으로 트래픽을 사용자와 가장 가까운 리전에 전달합니다. 트래픽 집중 리전의 경우 부하 분산기가 자동으로 새 연결을 사용 가능한 용량이 있는 다른 리전에 전달합니다. 기존 사용자 연결은 현재 리전에 계속 유지됩니다.

트래픽은 다음과 같이 백엔드에 할당됩니다.

  1. 클라이언트가 요청을 전송하면 부하 분산 서비스는 소스 IP 주소에서 요청의 대략적인 출처를 확인합니다.
  2. 부하 분산 서비스는 백엔드 서비스가 소유한 백엔드의 위치, 백엔드의 전체 용량, 현재 총 사용량을 확인합니다.
  3. 사용자에게 가장 가까운 백엔드 인스턴스에 이용 가능한 용량이 있으면 요청은 가장 가까운 백엔드 집합으로 전달됩니다.
  4. 한 리전에 수신되는 요청은 해당 리전의 이용 가능한 모든 백엔드 인스턴스에 균등하게 분산됩니다. 하지만 부하가 아주 적은 경우에는 분산이 균등하지 않게 나타날 수 있습니다.
  5. 지정한 리전에 이용 가능한 용량이 있는 정상 백엔드 인스턴스가 없는 경우 부하 분산기는 이용 가능한 용량이 있는 가장 가까운 다음 리전으로 요청을 전송합니다.

표준 등급

표준 등급에서 TCP 프록시 부하 분산은 리전 서비스입니다. 백엔드는 모두 부하 분산기의 외부 IP 주소 및 전달 규칙에서 사용하는 리전에 있어야 합니다.

아키텍처

TCP 프록시 부하 분산기의 구성요소는 다음과 같습니다.

전달 규칙 및 IP 주소

전달 규칙은 IP 주소, 포트, 프로토콜별로 트래픽을 대상 프록시와 백엔드 서비스로 구성된 부하 분산 구성으로 라우팅합니다.

각 전달 규칙은 애플리케이션의 DNS 레코드에 사용할 수 있는 단일 IP 주소를 제공합니다. DNS 기반 부하 분산은 필요 없습니다. 사용할 수 있는 고정 IP 주소를 예약하거나 Cloud Load Balancing에서 IP 주소를 하나 할당하도록 할 수 있습니다. 고정 IP 주소를 예약하는 것이 좋습니다. 그렇지 않으면 전달 규칙을 삭제하고 새 규칙을 만들 때마다 DNS 레코드를 새로 할당된 임시 IP 주소로 업데이트해야 합니다.

TCP 프록시 부하 분산기의 정의에 사용되는 외부 전달 규칙은 전달 규칙 포트 사양에 나와 있는 포트 중 하나를 정확하게 참조할 수 있습니다.

대상 프록시

TCP 프록시 부하 분산은 클라이언트에서 TCP 연결을 종료하고 백엔드에 새 연결을 만듭니다. 기본적으로 원래 클라이언트 IP 주소와 포트 정보는 유지되지 않습니다. 이 정보를 유지하려면 PROXY 프로토콜을 사용하면 됩니다. 대상 프록시는 들어오는 요청을 직접 백엔드 서비스로 라우팅합니다.

백엔드 서비스

백엔드 서비스는 들어오는 트래픽을 연결된 백엔드 1개 이상에 전달합니다. 각 백엔드는 인스턴스 그룹 또는 네트워크 엔드포인트 그룹과 백엔드의 제공 용량에 대한 정보로 구성됩니다. 백엔드 제공 용량은 CPU 또는 초당 요청 수(RPS)를 기반으로 합니다.

TCP 프록시 부하 분산기마다 하나의 백엔드 서비스 리소스가 있습니다. 백엔드 서비스 변경사항은 즉시 적용되지 않습니다. 변경사항이 Google 프런트엔드(GFE)에 적용되는 데 몇 분 정도 걸릴 수 있습니다.

각 백엔드 서비스는 사용 가능한 백엔드에 수행할 상태 확인을 지정합니다.

사용자에 대한 중단이 최소화되도록 백엔드 서비스에서 연결 드레이닝을 사용 설정할 수 있습니다. 이러한 중단은 백엔드가 종료되거나 수동으로 삭제되거나 자동 확장 처리 과정에서 삭제될 때 발생할 수 있습니다. 연결 드레이닝을 사용하여 서비스 중단을 최소화하기에 대해 자세히 알아보려면 연결 드레이닝 사용 설정을 참조하세요.

백엔드와의 통신에 사용되는 프로토콜

TCP 프록시 부하 분산기에 백엔드 서비스를 구성할 때 백엔드 서비스가 백엔드와 통신하는 데 사용할 프로토콜을 설정합니다. SSL 또는 TCP를 선택할 수 있습니다. 부하 분산기는 사용자가 지정한 프로토콜만 사용하고 다른 프로토콜과의 연결 협상을 시도하지 않습니다.

방화벽 규칙

백엔드 인스턴스는 부하 분산기 GFE/상태 확인 범위에서의 연결을 허용해야 합니다. 즉, 130.211.0.0/22  35.191.0.0/16의 트래픽이 백엔드 인스턴스 또는 엔드포인트에 도달하도록 허용하는 방화벽 규칙을 만들어야합니다. 이러한 IP 주소 범위는 상태 확인 패킷과 백엔드로 전송되는 모든 부하 분산 패킷의 소스로 사용됩니다.

이 방화벽 규칙에 대해 구성하는 포트는 백엔드 인스턴스 또는 엔드포인트에 대한 트래픽을 허용해야 합니다.

  • 각 전달 규칙에서 사용하는 포트를 허용해야 합니다.
  • 각 백엔드 서비스에 구성된 각 상태 확인에 사용하는 포트를 허용해야 합니다.

방화벽 규칙은 Google 프런트엔드(GFE) 프록시가 아닌 VM 인스턴스 수준에서 구현됩니다. Google Cloud 방화벽 규칙을 사용하여 트래픽이 부하 분산기에 도달하는 것을 막을 수 없습니다.

상태 확인 프로브와 130.211.0.0/22  35.191.0.0/16의 트래픽을 허용해야 하는 이유에 대한 자세한 내용은 프로브 IP 범위 및 방화벽 규칙을 참조하세요.

소스 IP 주소

각 백엔드 가상 머신(VM) 인스턴스 또는 컨테이너에서 확인되는 패킷의 소스 IP 주소는 다음 범위의 IP 주소입니다.

  • 35.191.0.0/16
  • 130.211.0.0/22

실제 부하 분산 트래픽의 소스 IP 주소는 상태 확인 프로브 IP 범위와 같습니다.

백엔드에서 확인되는 트래픽의 소스 IP 주소는 부하 분산기의 Google Cloud 외부 IP 주소가 아닙니다. 다시 말해 HTTP, SSL 또는 TCP 세션이 두 개 있습니다.

  • 원래 클라이언트에서 부하 분산기(GFE)로 이동하는 세션 1:
    • 원본 IP 주소: 원래 클라이언트 또는 클라이언트가 NAT 뒤에 있는 경우 외부 IP 주소입니다.
    • 대상 IP 주소: 부하 분산기의 IP 주소입니다.
  • 부하 분산기(GFE)에서 백엔드 VM 또는 컨테이너로 이동하는 세션 2:
    • 소스 IP 주소: IP 주소는 35.191.0.0/16 또는 130.211.0.0/22 범위 중 하나입니다.
    • 실제 소스 주소는 예측할 수 없습니다.
    • 대상 IP 주소: Virtual Private Cloud(VPC) 네트워크의 백엔드 VM 또는 컨테이너의 내부 IP 주소입니다.

중요: 35.191.0.0/16 또는 130.211.0.0/22에 있는 IP 주소 중 어떤 IP 주소를 차단해도 상태 확인은 계속 진행될 수 있습니다. 여러 프로버가 동시에 사용됩니다. 다수가 통과하면 몇몇 실패한 프로버가 무시될 수 있습니다. 그러나 실제 부하 분산 트래픽을 차단할 수 있습니다.

열린 포트

TCP 프록시 부하 분산기는 역방향 프록시 부하 분산기입니다. 부하 분산기는 수신 연결을 종료한 후 부하 분산기에서 백엔드로 새 연결을 엽니다. 역방향 프록시 기능은 Google 프런트엔드(GFE)에서 제공합니다.

GFE에는 다른 Google Cloud 부하 분산기와 다른 Google 서비스를 지원하는 열린 포트가 여러 개 있습니다. 부하 분산기의 외부 IP 주소에 대해 보안 또는 포트 검사를 실행하면 추가 포트가 열려 있는 것처럼 보입니다.

이는 TCP 프록시 부하 분산기에 영향을 주지 않습니다. TCP 프록시 부하 분산기에서 사용하는 외부 전달 규칙마다 전달 규칙 포트 사양에 나와 있는 포트 중 하나를 정확하게 참조할 수 있습니다. 다른 TCP 대상 포트를 사용하는 트래픽은 부하 분산기의 백엔드로 전달되지 않습니다. 승인되지 않은 포트에 대한 TCP 세션을 열어서 추가 포트에 대한 트래픽이 처리되지 않는지 확인할 수 있습니다. 요청을 처리하는 GFE가 TCP 재설정(RST) 패킷으로 연결을 닫습니다.

트래픽 분산

TCP 프록시 부하 분산기가 트래픽을 백엔드로 배포하는 방식은 분산 모드와 백엔드를 선택하기 위해 선택한 해싱 메서드(세션 어피니티)에 따라 다릅니다.

분산 모드

백엔드 서비스에 백엔드를 추가할 때 부하 분산 모드를 설정합니다.

TCP 프록시 부하 분산의 경우 분산 모드는 CONNECTION 또는 UTILIZATION일 수 있습니다.

부하 분산 모드가 CONNECTION이면 백엔드에서 처리할 수 있는 동시 연결 수에 따라 부하가 분산됩니다. 매개변수 maxConnections(리전 관리형 인스턴스 그룹 제외), maxConnectionsPerInstance, maxConnectionsPerEndpoint 중 하나를 정확하게 지정해야 합니다.

부하 분산 모드가 UTILIZATION이면 인스턴스 그룹의 인스턴스 사용률에 따라 부하가 분산됩니다.

부하 분산기 유형과 지원되는 부하 분산 모드 비교에 대한 자세한 내용은 부하 분산 방법을 참조하세요.

세션 어피니티

세션 어피니티는 백엔드가 정상이고 용량이 있는 한 동일한 클라이언트의 모든 요청을 동일한 백엔드로 전송합니다.

TCP 프록시 부하 분산은 동일한 클라이언트 IP 주소의 모든 요청을 동일한 백엔드에 전달하는 클라이언트 IP 어피니티를 제공합니다.

장애 조치

백엔드가 비정상이 되면 트래픽은 자동으로 동일한 리전에 있는 정상 백엔드로 리디렉션됩니다. 한 리전 내 모든 백엔드가 비정상이면 트래픽이 다른 리전의 정상 백엔드로 분산됩니다(프리미엄 등급만 해당). 모든 백엔드가 비정상이면 부하 분산기가 트래픽을 삭제합니다.

다음 단계

 

 

https://cloud.google.com/load-balancing/docs/tcp

 

TCP 프록시 부하 분산 개요  |  Google Cloud

TCP 프록시 부하 분산은 인터넷에서 들어오는 TCP 트래픽을 Google Cloud VPC 네트워크의 가상 머신(VM) 인스턴스로 배포하는 역방향 프록시 부하 분산기입니다. TCP 프록시 부하 분산을 사용하면 TCP 연

cloud.google.com

 

728x90

 

Nginx 에서 HTTP 프로토콜에 대하여 HTTPS로 redirect 설정하는 것과 다른 포트로 포트포워딩(Port Forwarding) 하는 설정 내용을 정리합니다.


테스트 환경

 

 

Nginx를 설치 및 HTTPS 설정된 환경에서 진행을 하고 위 링크의 포스트가 선행되어야 하겠습니다.


Nginx HTTP redirect to HTTPS

HTTP redirect는 HTTP(비암호화 프로토콜)로 접속했을 때 자동적으로 HTTPS 프로토콜로 서비스되도록 리다이렉트 처리를 하는 것입니다.

일반적으로 사이트 접속 시 jackerlab.com 이렇게 도메인을 치고 사이트 접속을 하면 https://jackerlab.com과 같은 형태의 HTTP 프로토콜로 접속이 됩니다.

사이트를 항상 HTTPS로 서비스하기 위하여 HTTPS로 리다이렉트 처리하여 HTTPS로 접속을 전환/유도하는 것입니다.

Redirect 설정은 /etc/nginx/nginx.conf 파일에서 설정하고 Nginx 서비스를 구동하면 되고 HTTPS(443) 설정이 사전에 되어 있어야 합니다.

[root@jackerlab ~]# vim /etc/nginx/nginx.conf ... (앞부분 생략) server { listen 80 default_server; listen [::]:80 default_server; #server_name _; server_name apps.jackerlab.com; root /usr/share/nginx/html; charset utf-8; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } return 301 https://$host$request_uri; # HTTP to HTTPS redirect } ... (뒷부분 생략 - 뒷부분의 HTTPS 설정이 되어 있어야 함) [root@jackerlab ~]#

위 설정은 마지막 부분에 1줄 추가가 된 상태고 301 HTTP 응답 코드에 의하여 https://도메인으로 redirect 처리 해주는 설정입니다.


Nginx 포트 포워딩 설정

웹 어플리케이션을 작성했을 때 HTTPS 통신을 하기 위하여 포트 포워딩을 사용할 수 있겠습니다.

예를 들어 React, Django 등의 웹서버가 별도로 구동되어 있을 경우, HTTPS인 443 포트에 React(3000), Django(8000) 매핑을 하여 HTTPS 프로토콜로 웹 서비스를 제공할 수 있겠습니다.

이번 테스트에서는 React(3000) 가 구동되었다고 가정하고 포트포워딩 설정을 해보겠습니다.

Redirect 설정과 연계되어 있고 최종적으로는 아래와 같은 구조가 되겠습니다.

최종적으로 사이트를 접속하면 HTTPS 암호화 통신 환경에서 React(3000) 어플리케이션에 접속이 되는 것입니다.

/etc/nginx/nginx.conf 파일에서 설정하고 Nginx 서비스를 구동하면 되고 HTTPS(443) 설정 및 React(3000) 서비스 구동이 사전에 되어 있어야 합니다.

[root@jackerlab nginx]# cat nginx.conf ... (앞부분 생략 - HTTP(80) 설정 부분) # Settings for a TLS enabled server. server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name localhost; # server_name apps.jackerlab.com; root /usr/share/nginx/html; ssl_certificate /etc/letsencrypt/live/apps.jackerlab.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/apps.jackerlab.com/privkey.pem; ssl_session_cache shared:SSL:1m; ssl_session_timeout 10m; ssl_ciphers PROFILE=SYSTEM; ssl_prefer_server_ciphers on; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { proxy_pass http://localhost:3000; # 포트 포워딩 설정 } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } } ... (뒷부분 생략) [root@jackerlab nginx]#

위 설정은 중간 location 부분에 1줄 추가가 된 상태고 HTTPS(443) 접속 시, 프록시 기능으로 3000 포트로 포워딩을 하겠다는 설정입니다.

최종적으로 설정 된 결과는 아래와 같고 HTTPS(443) 과 인증서 적용(자물쇠)이 정상적으로 된 후, React(3000) 웹 서비스로 정상 접속된 것을 확인할 수 있습니다.

 

 

 

 

https://jackerlab.com/nginx-redirect-port-forwarding/

 

[Nginx] Nginx HTTP redirect 및 포트포워딩(Port Forwarding) 설정⋆ JackerLab

Nginx 에서 HTTP 프로토콜에 대하여 HTTPS로 redirect 설정하는 것과 다른 포트로 포트포워딩(Port Forwarding) 하는 설정 내용을 정리합니다.

jackerlab.com

 

 

 

 

728x90

Ever wondered how more than one application is deployed to the same machine, and how traffic is routed to the corresponding applications? Keep reading to find out.

Introduction

Goals

By the end of the article, you’ll understand

  • What a Reverse Proxy is?
  • What NGINX is?
  • How does NGINX help in managing multiple applications?
  • How to leverage NGINX as a Reverse Proxy?

Reverse Proxy

According to Wikipedia, a reverse proxy is a type of proxy server that retrieves resources on behalf of a client from one or more servers. These resources are then returned to the client, appearing as if they originated from the server itself.

Refer to this article to better understand what Reverse Proxies are.

NGINX

We will be using NGINX as a Reverse Proxy. According to Wikipedia,
NGINX is a web server that can be used as a reverse proxy, load balancer, mail proxy, and HTTP cache. The software was created by Igor Sysoev and was publicly released in 2004. Nginx is a free and open-source software, released under the terms of the 2-clause BSD license. A large fraction of web servers use NGINX, often as a load balancer.

Some other examples Reverse Proxies available are:

Reverse Proxy Example

This is an example of an architecture, where two apps are running in the background, but the clients have no idea about them. The clients only know about NGINX which acts as a reverse proxy that sends the request to the appropriate application.

Now that you have a broader idea of what we are about to build, let’s jump right in!

Aim

  • Deploy two applications and have them managed by NGINX.

Setup & Pre-Requisites:

  • For this example, we have two sample Express Applications. One can have any kind of application running on different ports.

NOTE: Do not run your application on Port 80 or 443. We will explaining later why this must not be done.
Refer the official ExpressJS documentation for help getting started.

  • We have installed NGINX on our local machine, but the same could be done on any Virtual Machine where the applications are expected to be deployed.

Here is the documentation on how to install NGINX on your machine.

Step 1: Start two apps running in different ports

As we’ve mentioned earlier, we’ve got two Node.js Apps running on two different ports as shown below.

Server app running on Port 3000

Client app running on Port 3001

Now that we have our apps up and running, we don’t want our users to use these applications by typing their PORTS explicitly, so we need to map it with something that is more human-readable.

In this example, we will be using subdomains to distinguish between them. Again one is free to use whichever element is suitable as per requirements.

Another example could be a particular route like domain/client and domain/server. The only condition for the distinguishing element is to follow a valid URL regular expression. To learn about Regex you can click here.

Step 2: Add DNS records

This is the part where one would add the DNS records in their DNS management dashboard. If you are running Nginx locally, you can skip this step.

The general DNS Configurations would be something like:

  • Server app mapped to the server.domain
  • Client app mapped to the client.domain

My Localhost Config, in this case, would be:

  • Server mapped to server.localhost
  • Client mapped to client.localhost

There are two standard protocols HTTP and HTTPS. The default port for HTTP is 80 and HTTPS is 443. The reason we must not run our applications on these ports is because our NGINX server is running on these two ports. All the requests the client makes would either be redirected to port 80 or 443 from where it would be redirected internally to the corresponding application.

Step 3 - Configure NGINX at 80 for HTTP and 443 for HTTPS

Now that we have our apps running and our DNS records ready. We can start configuring our NGINX Reverse Proxy to make it all work.

By default, the configuration file is named nginx.conf and placed in the directory /usr/local/nginx/conf, /etc/nginx, or /usr/local/etc/nginx for Linux and Debian Based systems.

On Windows, the file is placed inside the installation folder, nginx/conf/nginx.conf.

Add these configurations inside the HTTP block.

Step 3.1 - HTTP

server { listen 80; server_name server.domain; location / { proxy_pass "http://localhost:3000" ; } } server { listen 80; server_name client.domain; location / { proxy_pass "http://localhost:3001" ; } }

Step 3.2 - HTTPS

server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name server.domain; location / { proxy_pass "http://localhost:3000/"; } ssl_certificate <location of SSL certificate>; ssl_certificate_key <location of SSL certificate Key>; } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name client.domain; location / { proxy_pass "http://localhost:3001/"; } ssl_certificate <location of SSL certificate>; ssl_certificate_key <location of SSL certificate Key>; }

NOTE: These are the minimum configurations required to successfully implement NGINX for reverse proxying. Feel free to explore other config parameters as well.

Make sure to change the domain name to your domain. For a SSL Certificate and Key, you can obtain them from your SSL provider.

If you don’t have one, use this free service LetsEncrypt.

Follow their documentation to get free SSL instantly!

Step 4 - Save and Restart

After editing, save your changes. Use the sudo nginx -t command to test your changes before actually reloading NGINX. It is good practice do this to make sure your server won’t crash, if there were any errors in your config file.

Once you get a message that the test is successful, you can go ahead and restart NGINX.

Use this command sudo nginx -s reload to restart NGINX.

Open the browser and enter the URLs to find your applications running on the corresponding URLs configured.

For the example above, the URLs are:

  • client.localhost
  • server.localhost

Important Note

Using NGINX secures your server because it routes the traffic internally. Instead of having to open up all of your ports, in this case 3000 and 3001, to the internet, just 80 and 443 will do the trick.

This is because all traffic passes through the secure NGINX server (like a gateway) and is redirected to the correct application. Using a reverse proxy like NGINX is more secure that opening up several ports for every application you deploy because of the increased risk a hacker will use an open port for malicious activity.

Conclusion

Here is the end result:

Congratulations! You did it! 🎉

In large systems, the system is highly dependent on the micro-services architecture where each service would be served by an application. In that case, managing multiple apps would be an essential skill to know.

The microservices architecture is discussed here in detail.

Hope this article helped you to manage those independently deployed applications as a whole with the help of NGINX as a reverse proxy.

Thanks for reading!

References


Peer Review Contributions by: Louise Findlay


About the author

Harish Ramesh Babu

Harish Ramesh Babu is a final year CS Undergrad at the National Institute of Technology, Rourkela, India. He gets really excited about new tech and the cool things you can build with it. Mostly you’ll find him working on web apps either for the campus or an opensource project with the

 

 

 

https://www.section.io/engineering-education/nginx-reverse-proxy/

728x90

기본적으로 웹서버 구조는

와 같습니다.

nginx 와 php 를 사용하는 경우

와 같이 됩니다.

FastCGI는 웹 서버와 프로그램이 상호작용(데이터를 주고 받기 위한) 인터페이스 개발을 위한 프로토콜입니다.

FastCGI는 CGI(Common Gateway Interface)를 개선한 인터페이스입니다.

PHP 는 FastCgi 구현채인 php-fpm 을 사용해서 nginx 와 통신합니다.

php-fpm 설정 ( 기본경로 : /etc/php-fpm.d/www.conf )

listen = 127.0.0.1:9000

9000 번 포트로 tcp/ip socket 통신을 하는걸 알 수 있습니다.

nginx 설정 에서 php-fpm 과 통신할 수 있도록 설정 해봅시다.

nginx 설정 ( 기본경로 : /etc/nginx/nginx.conf )

server { location ~ \.(php)$ { fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; } location ~ \.(gif|jpg|png)$ { root /data/images; } }

만일 nginx 와 php-fpm 이 물리적으로 동일한 서버에 있다면 unix socket 을 사용해서 속도를 향상 시킬 수 있습니다.

(주의 : unix socket 은 프로세스간 통신 이기 때문에 물리적으로 다른 서버에 있다면 사용 할 수 없습니다.)

다음과 같이 설정을 바꿉니다.

php-fpm 설정

listen = /var/run/php7-fpm.sock

nginx 설정

fastcgi_pass unix:/var/run/php7-fpm.sock;

설정 후

설정한 경로에 파일이 생김을 알 수 있습니다. (리눅스는 소켓을 파일 취급 합니다.)

nginx 와 php-fpm 소켓통신의 경우 접근이 잦기 때문에 /dev/shm 경로 아래에 넣어주면 약간의 속도 향상 효과를 얻을 수 있습니다.

/dev/shm 은 실제로 메모리를 점유하는건 아니지만 사용하는 만큼 램을 사용하는데

결국

php-fpm 설정

listen = /dev/shm/php7-fpm.sock

nginx 설정

fastcgi_pass unix:/dev/shm/php7-fpm.sock;

으로 수정하면 됩니다.

아주 간단하게 벤치마킹을 해봅시다.

server 코드

<?php echo "test"; echo PHP_EOL;

client 코드

<?php $message = 'test'; $header = array(); $url = "서버 주소"; $start = microtime(true); for($i=0; $i<100; $i++) { $curlSession = curl_init(); curl_setopt($curlSession, CURLOPT_URL, $url); curl_setopt($curlSession, CURLOPT_HTTPHEADER, $header); curl_setopt($curlSession, CURLOPT_POST, TRUE); curl_setopt($curlSession, CURLOPT_POSTFIELDS, $message); curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE); $curlResult = curl_exec($curlSession); curl_close($curlSession); } $end = microtime(true); print_r($end - $start);

5회 돌려본 결과

 1회2회3회4회5회

tcp/ip socket 2.2519 2.5132 2.3198 2.4347 2.4336
unix socket 2.4471 2.3182 2.1452 2.1803 1.9307



참고 사이트

+

1)

팀 동료가 tcp/ip socket 을 unix socket 으로 수정후 테스트 케이스 1000개 정도의 속도가 1분정도 감소 하는 효과가 있었다고 말 해줬습니다.

2)

또다른 팀 동료는 tcp/ip socket 대신 unix socket 사용하는 이유는 tcp/ip socket 은 close 시에 프로세스가 time wait 가 걸려서 바로 반환 하지 않기 때문에 소켓 개수 제한에 금방 걸릴수 있어서 unix socket 으로 대체 한다고 말해 줬다.

관련 내용은 다시 찾아봐야 할 거 같습니다.

+ Recent posts