prosource

Node.js + Nginx - 이제 어떻게 됩니까?

probook 2023. 5. 28. 20:54
반응형

Node.js + Nginx - 이제 어떻게 됩니까?

서버에 Node.js와 Nginx를 설정했습니다.이제 사용하고 싶지만, 시작하기 전에 두 가지 질문이 있습니다.

  1. 그들이 어떻게 협력해야 할까요?요청 사항을 어떻게 처리해야 합니까?
  2. Node.js 서버에는 두 가지 개념이 있으며, 다음 중 더 나은 개념이 있습니다.

    필요한 각 웹 사이트에 대해 별도의 HTTP 서버를 만듭니다.그런 다음 프로그램 시작 시 모든 자바스크립트 코드를 로드하여 코드가 한 번 해석되도록 합니다.

    모든 Node.js 요청을 처리하는 단일 Node.js 서버를 만듭니다.이렇게 하면 요청된 파일을 읽고 내용을 평가할 수 있습니다.따라서 파일은 각 요청에 따라 해석되지만 서버 논리는 훨씬 단순합니다.

Node.js를 올바르게 사용하는 방법이 명확하지 않습니다.

Nginx는 프런트 엔드 서버로 작동하며, 이 경우 요청을 node.js 서버로 프록시합니다.따라서 노드에 대한 Nginx 구성 파일을 설정해야 합니다.

Ubuntu 박스에서 수행한 작업은 다음과 같습니다.

yourdomain.example/etc/nginx/sites-available/:

vim /etc/nginx/sites-available/yourdomain.example

그 안에는 다음과 같은 것이 있어야 합니다.

# the IP(s) on which your node server is running. I chose port 3000.
upstream app_yourdomain {
    server 127.0.0.1:3000;
    keepalive 8;
}

# the nginx server instance
server {
    listen 80;
    listen [::]:80;
    server_name yourdomain.example www.yourdomain.example;
    access_log /var/log/nginx/yourdomain.example.log;

    # pass the request to the node.js server with the correct headers
    # and much more can be added, see nginx config options
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass http://app_yourdomain/;
      proxy_redirect off;
    }
 }

웹 을 처리하도록 Nginx(>= 1.3.13)에 합니다.location /섹션:

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

이 설정을 수행한 후에는 위의 구성 파일에 정의된 사이트를 활성화해야 합니다.

cd /etc/nginx/sites-enabled/
ln -s /etc/nginx/sites-available/yourdomain.example yourdomain.example

을 다음위서만에 ./var/www/yourdomain/app.js 위치에서 합니다.localhost:3000

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

구문 오류 테스트:

nginx -t

Nginx 다시 시작:

sudo /etc/init.d/nginx restart

마지막으로 노드 서버를 시작합니다.

cd /var/www/yourdomain/ && node app.js

은 "Hello World"에서 " World볼 수 입니다.yourdomain.example

노드 서버 시작과 관련된 마지막 참고 사항: 노드 데몬에 대해 일종의 모니터링 시스템을 사용해야 합니다.시작모니터링 기능이 있는 노드에 대한 멋진 튜토리얼이 있습니다.

Nginx를 사용하여 여러 도메인을 설정하여 여러 node.js 프로세스로 전달할 수도 있습니다.

예를 들어 다음을 수행할 수 있습니다.

  • domain1.example 중인로 -> Node.js로 이동합니다.http://127.0.0.1:4000
  • domain2.example 중인로 -> Node.js로 이동합니다.http://127.0.0.1:5000

이러한 포트(4000 및 5000)는 앱 코드의 앱 요청을 수신하는 데 사용해야 합니다.

/etc/nginx/domain-enabled/domain1

server {
    listen 80;
    listen [::]:80;
    server_name domain1.example;
    access_log /var/log/nginx/domain1.access.log;
    location / {
        proxy_pass    http://127.0.0.1:4000/;
    }
}

/etc/nginx/sites-enabled/domain2에서

server {
    listen 80;
    listen [::]:80;
    server_name domain2.example;
    access_log /var/log/nginx/domain2.access.log;
    location / {
        proxy_pass    http://127.0.0.1:5000/;
    }
}

하나의 서버 구성에서 앱에 대해 다른 URL을 가질 수도 있습니다.

  • yourdomain.example/app1/* 중인로 -> Node.js로 이동합니다.http://127.0.0.1:3000
  • yourdomain.example/app2/* 중인로 -> Node.js로 이동합니다.http://127.0.0.1:4000

/etc/nginx/sites-enabled/yourdomain에서:

server {
    listen 80;
    listen [::]:80;
    server_name yourdomain.example;

    location ^~ /app1/{
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass    http://127.0.0.1:3000/;
    }

    location ^~ /app2/{
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass    http://127.0.0.1:4000/;
    }
}

Nginx 다시 시작:

sudo service nginx restart

응용 프로그램을 시작하는 중입니다.

노드 app1.js

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello from app1!\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

노드 app2.js

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello from app2!\n');
}).listen(4000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:4000/');

Nginx를 통해 독립 Node Express 응용 프로그램을 프록시합니다.

따라서 새로운 애플리케이션을 쉽게 마운트할 수 있으며 다른 위치에 있는 동일한 서버에서 다른 작업을 실행할 수도 있습니다.

다음은 Nginx 구성 예를 사용한 설정에 대한 자세한 내용입니다.

Nginx를 사용하여 하위 폴더에 있는 하나의 웹 서버에 여러 노드 응용 프로그램 배포

로컬 호스트에서 인터넷으로 응용 프로그램을 이동해야 하는 경우 노드의 상황이 까다로워집니다.

노드 배포에 대한 일반적인 접근 방식은 없습니다.

구글은 이 주제에 대한 수많은 기사를 찾을 수 있지만, 저는 제가 필요로 하는 설정에 적합한 솔루션을 찾는 데 어려움을 겪고 있었습니다.

기본적으로 웹 서버가 있으며 애플리케이션 코드에 대한 구성 종속성 없이 노드 애플리케이션을 하위 폴더(예: http://myhost/demo/pet-project/)에 마운트하기를 원합니다.

동시에 블로그와 같은 다른 것들이 같은 웹 서버에서 실행되기를 원합니다.

간단하죠?분명히 아닙니다.

웹 노드의 많은 예에서 응용 프로그램은 포트 80에서 실행되거나 Nginx에 의해 루트에 프록시됩니다.

두 가지 접근 방식 모두 특정 사용 사례에 대해 유효하지만, 저의 단순하면서도 약간 이국적인 기준을 충족하지 못합니다.

이것이 제가 직접 Nginx 구성을 만든 이유이며, 여기 발췌문이 있습니다.

upstream pet_project {
  server localhost:3000;
}

server {
  listen 80;
  listen [::]:80;
  server_name frontend;

  location /demo/pet-project {
    alias /opt/demo/pet-project/public/;
    try_files $uri $uri/ @pet-project;
  }

  location @pet-project {
    rewrite /demo/pet-project(.*) $1 break;

    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $proxy_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_pass http://pet_project;
    proxy_redirect http://pet_project/ /demo/pet-project/;
  }
}

이 예에서 포트 3000에서 실행 중인 Pet Project Node 응용 프로그램을 http://myhost/demo/pet-project에 마운트합니다.

먼저 Nginx는 요청한 리소스가 /opt/demo/pet-project/public/에서 사용할 수 있는 정적 파일인지 여부를 확인하고 그대로 사용하면 매우 효율적이므로 Connect static middleware와 같은 중복 계층이 필요하지 않습니다.

그런 다음 다른 모든 요청을 덮어쓰고 Pet Project Node 응용 프로그램에 프록시를 사용하므로 Node 응용 프로그램이 실제로 마운트된 위치를 알 필요가 없으므로 구성만으로 어디든 이동할 수 있습니다.

위치 헤더를 제대로 처리하려면 proxy_redirect가 필요합니다.노드 응용 프로그램에서 res.redirect()사용하는 경우 이는 매우 중요합니다.

서로 다른 포트에서 실행되는 여러 노드 응용프로그램에 대해 이 설정을 쉽게 복제하고 다른 용도로 위치 핸들러를 추가할 수 있습니다.

보낸 사람: http://skovalyov.blogspot.dk/2012/07/deploy-multiple-node-applications-on.html

Nginx 구성의 Node.js입니다.

$ sudo nano /etc/nginx/sites-available/subdomain.your-domain.example

다음 구성을 추가하여 Nginx가 프록시 역할을 하여 서버에서 포트 3000 트래픽으로 리디렉션되도록 합니다.subdomain.your_domain.example

upstream subdomain.your-domain.example {
  server 127.0.0.1:3000;
}
server {
  listen 80;
  listen [::]:80;
  server_name subdomain.your-domain.example;
  access_log /var/log/nginx/subdomain.your-domain.access.log;
  error_log /var/log/nginx/subdomain.your-domain.error.log debug;
  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://subdomain.your-domain.example;
    proxy_redirect off;
  }
}

Github에서 복제할 수 있는 vagrant-node-nginx-boilerplate 저장소를 만들었습니다.

은 node.js에 있습니다./var/www/nodeapp이라

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(4570, '127.0.0.1');

console.log('Node Server running at 127.0.0.1:4570/');

at "nginx"/etc/nginx/sites-available/이라

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/nodeapp;
        index index.html index.htm;

        server_name localhost;

        location / {
          proxy_pass http://127.0.0.1:4570;
          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;
        }
}

질문에 대한 답변 2:

는 옵션 을옵사니다합용션▁option다▁use니를 사용할 것입니다.b옵션 'a 로드합니다(php를 , 입니다).옵션 'a'를 사용하면 모든 클라이언트가 서버에 많은 메모리를 소비하여 필요한 모든 파일을 로드합니다(비록 제가 php를 좋아하지만, 이것은 그것의 문제 중 하나입니다).옵션 'b'를 사용하면 라이브러리(재사용 가능한 코드)를 로드하고 모든 클라이언트 요청 간에 공유할 수 있습니다.

그러나 코어가 여러 개인 경우 node.js를 모두 사용하도록 조정해야 합니다.

Nginx는 프로젝트 관리자처럼 작동하는 역방향 프록시 서버 역할을 할 수 있습니다.요청을 받으면 이를 분석하여 요청을 업스트림(프로젝트 구성원)으로 전달하거나 자체 처리합니다.Nginx는 구성 방식에 따라 두 가지 방법으로 요청을 처리할 수 있습니다.

  • 부탁을 들어주다

  • 요청을 다른 서버로 전달

     server{
      server_name mydomain.example sub.mydomain.example;
    
      location /{
       proxy_pass http://127.0.0.1:8000;
       proxy_set_header Host $host;
       proxy_pass_request_headers on;
      }
    
      location /static/{
        alias /my/static/files/path;
      }
    }
    

요청 서버

이 "URL"일 때mydomain.example/static/myjs.js▁the다▁returns를 반환합니다.myjs.js줄을 지어 들어가다/my/static/files/path폴더를 누릅니다.정적 파일을 제공하도록 Nginx를 구성하면 요청 자체가 처리됩니다.

요청을 다른 서버로 전달

이 "URL"인 mydomain.example/dothis을 Nginx 요다전달다로 합니다.http://127.0.0.1:8000로컬 호스트 8000 포트에서 실행 중인 서비스가 요청을 수신하고 Nginx에 응답을 반환하고 Nginx는 클라이언트에 응답을 반환합니다.

포트 8000에서 node.js 서버를 실행하면 Nginx가 요청을 node.js로 전달합니다.node.js 로직을 작성하고 요청을 처리합니다.이것이 바로 Nginx 서버 뒤에서 nodejs 서버를 실행하는 것입니다.

만약 당신이 nodejs 이외의 다른 서비스를 실행하고 싶다면, 장고, 플라스크, PHP와 같은 다른 서비스를 다른 포트에서 실행하고 Nginx에서 구성하기만 하면 됩니다.

node.js를 사용하여 nginx에서 제공하는 디렉터리에 정적 파일을 생성할 수도 있습니다.물론 사이트의 일부 동적 부분은 노드로, 일부는 nginx(정적)로 처리할 수 있습니다.

nginx에서 일부를 제공하면 성능이 향상됩니다.

Nginx가 역방향 프록시 역할을 하여 Nodejs 앱을 쉽게 설정할 수 있습니다.다음 구성에서는 NodeJS 응용 프로그램이 127.0.0.1:8080에서 실행되고 있다고 가정합니다.

  server{
     server_name domain.example sub.domain.example; # multiple domains

     location /{
      proxy_pass http://127.0.0.1:8080;
      proxy_set_header Host $host;
      proxy_pass_request_headers on;
     }

     location /static/{
       alias /absolute/path/to/static/files; # nginx will handle js/css
     }
   }

위의 설정에서 당신의 Nodejs 앱은,

  • 얻다HTTP_HOST응답을 제공하기 위해 도메인별 논리를 적용할 수 있는 헤더입니다.'

  • 애플리케이션은 상황 처리/소켓 또는 리소스 재사용 등을 위해 pm2 또는 슈퍼바이저와 같은 프로세스 관리자가 관리해야 합니다.

  • Sentry 또는 Rollbar와 같은 생산 오류를 가져오기 위한 오류 보고 서비스

참고: 도메인별 요청 경로를 처리하기 위한 로직을 설정하고 expressjs 응용 프로그램을 위한 미들웨어를 만들 수 있습니다.

Nginx 및 Nodejs를 사용하는 가장 좋고 간단한 설정은 proxy_protocol을 사용하도록 설정한 HTTP 및 TCP 로드 밸런서로 Nginx를 사용하는 것입니다.이러한 맥락에서 Nginx는 들어오는 요청을 nodejs로 프록시 처리할 수 있으며 프록시 서버 자체가 아닌 백엔드 Nginx 서버로의 SSL 연결도 종료할 수 있습니다. (SSL-PassThrough)

모든 웹 앱이 보안 환경을 사용하고 있기 때문에 비SSL 예제를 제공하는 것은 의미가 없다고 생각합니다.

/etc/nginx/nginx.conf의 프록시 서버에 대한 구성 예

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
    worker_connections  1024;
}
http {
  upstream webserver-http {
    server 192.168.1.4; #use a host port instead if using docker
    server 192.168.1.5; #use a host port instead if using docker
  }
  upstream nodejs-http {
    server 192.168.1.4:8080; #nodejs listening port
    server 192.168.1.5:8080; #nodejs listening port
  }
  server {
    server_name example.com;
    location / {
      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_set_header Host $http_host;
      proxy_set_header X-Forwarded-Host $server_name;
      proxy_set_header Connection "";
      add_header       X-Upstream $upstream_addr;
      proxy_redirect     off;
      proxy_connect_timeout  300;
      proxy_http_version 1.1;
      proxy_buffers 16 16k;
      proxy_buffer_size 16k;
      proxy_cache_background_update on;
      proxy_pass http://webserver-http$request_uri;
    }
  }
  server {
    server_name node.example.com;
    location / {
      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_set_header Host $http_host;
      proxy_set_header X-Forwarded-Host $server_name;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "Upgrade";
      add_header       X-Upstream $upstream_addr;
      proxy_redirect     off;
      proxy_connect_timeout  300;
      proxy_http_version 1.1;
      proxy_buffers 16 16k;
      proxy_buffer_size 16k;
      proxy_cache_background_update on;
      proxy_pass http://nodejs-http$request_uri;
    }
  }
}
stream {
  upstream webserver-https {
    server 192.168.1.4:443; #use a host port instead if using docker
    server 192.168.1.5:443; #use a host port instead if using docker
  }

  server {
    proxy_protocol on;
    tcp_nodelay on;
    listen 443;
    proxy_pass webserver-https;
  }
  log_format proxy 'Protocol: $protocol - $status $bytes_sent $bytes_received $session_time';
  access_log  /var/log/nginx/access.log proxy;
  error_log /var/log/nginx/error.log debug;
}

이제 백엔드 웹 서버를 처리하겠습니다./etc/nginx/nginx.conf:

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
load_module /etc/nginx/modules/ngx_http_geoip2_module.so; # GeoIP2
events {
    worker_connections  1024;
}
http {
    variables_hash_bucket_size 64;
    variables_hash_max_size 2048;
    server_tokens off;
    sendfile    on;
    tcp_nopush  on;
    tcp_nodelay on;
    autoindex off;
    keepalive_timeout  30;
    types_hash_bucket_size 256;
    client_max_body_size 100m;
    server_names_hash_bucket_size 256;
    include         mime.types;
    default_type    application/octet-stream;
    index  index.php index.html index.htm;
    # GeoIP2
    log_format  main    'Proxy Protocol Address: [$proxy_protocol_addr] '
                        '"$request" $remote_addr - $remote_user [$time_local] "$request" '
                        '$status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" "$http_x_forwarded_for"';

    # GeoIP2
    log_format  main_geo    'Original Client Address: [$realip_remote_addr]- Proxy Protocol Address: [$proxy_protocol_addr] '
                            'Proxy Protocol Server Address:$proxy_protocol_server_addr - '
                            '"$request" $remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '$geoip2_data_country_iso $geoip2_data_country_name';

    access_log  /var/log/nginx/access.log  main_geo; # GeoIP2
#===================== GEOIP2 =====================#
    geoip2 /usr/share/geoip/GeoLite2-Country.mmdb {
        $geoip2_metadata_country_build  metadata build_epoch;
        $geoip2_data_country_geonameid  country geoname_id;
        $geoip2_data_country_iso        country iso_code;
        $geoip2_data_country_name       country names en;
        $geoip2_data_country_is_eu      country is_in_european_union;
    }
    #geoip2 /usr/share/geoip/GeoLite2-City.mmdb {
    #   $geoip2_data_city_name city names en;
    #   $geoip2_data_city_geonameid city geoname_id;
    #   $geoip2_data_continent_code continent code;
    #   $geoip2_data_continent_geonameid continent geoname_id;
    #   $geoip2_data_continent_name continent names en;
    #   $geoip2_data_location_accuracyradius location accuracy_radius;
    #   $geoip2_data_location_latitude location latitude;
    #   $geoip2_data_location_longitude location longitude;
    #   $geoip2_data_location_metrocode location metro_code;
    #   $geoip2_data_location_timezone location time_zone;
    #   $geoip2_data_postal_code postal code;
    #   $geoip2_data_rcountry_geonameid registered_country geoname_id;
    #   $geoip2_data_rcountry_iso registered_country iso_code;
    #   $geoip2_data_rcountry_name registered_country names en;
    #   $geoip2_data_rcountry_is_eu registered_country is_in_european_union;
    #   $geoip2_data_region_geonameid subdivisions 0 geoname_id;
    #   $geoip2_data_region_iso subdivisions 0 iso_code;
    #   $geoip2_data_region_name subdivisions 0 names en;
   #}

#=================Basic Compression=================#
    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/css text/xml text/plain application/javascript image/jpeg image/png image/gif image/x-icon image/svg+xml image/webp application/font-woff application/json application/vnd.ms-fontobject application/vnd.ms-powerpoint;
    gzip_static on;

    include /etc/nginx/sites-enabled/example.com-https.conf;
}

이제 /etc/nginx/sessages-available/example.com -sessages.conf에서 이 SSL 및 proxy_sessages 사용 구성을 사용하여 가상 호스트를 구성해 보겠습니다.

server {
    real_ip_header proxy_protocol;
    set_real_ip_from 192.168.1.1; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    server_name 192.168.1.4; #Your current server ip address. It will redirect to the domain name.
    listen 80;
    listen 443 ssl http2;
    listen [::]:80;
    listen [::]:443 ssl http2;
    ssl_certificate     /etc/nginx/certs/example.com.crt;
    ssl_certificate_key /etc/nginx/certs/example.com.key;
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;
    return 301 https://example.com$request_uri;
}
server {
    real_ip_header proxy_protocol;
    set_real_ip_from 192.168.1.1; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    server_name  example.com;
    listen       *:80;
    return 301   https://example.com$request_uri;
}
server {
    real_ip_header proxy_protocol;
    set_real_ip_from 192.168.1.1; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    server_name www.example.com;
    listen 80;
    listen 443 http2;
    listen [::]:80;
    listen [::]:443 ssl http2 ;
    ssl_certificate     /etc/nginx/certs/example.com.crt;
    ssl_certificate_key /etc/nginx/certs/example.com.key;
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;
    return 301 https://example.com$request_uri;
}
server {
    real_ip_header proxy_protocol;
    set_real_ip_from 192.168.1.1; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    server_name example.com;
    listen 443 proxy_protocol ssl http2;
    listen [::]:443 proxy_protocol ssl http2;
    root /var/www/html;
    charset UTF-8;
    add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains; preload';
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Referrer-Policy no-referrer;
    ssl_prefer_server_ciphers on;
    ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
    ssl_protocols TLSv1.2 TLSv1.1 TLSv1;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    keepalive_timeout   70;
    ssl_buffer_size 1400;
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=86400;
    resolver_timeout 10;
    ssl_certificate     /etc/nginx/certs/example.com.crt;
    ssl_certificate_key /etc/nginx/certs/example.com.key;
    ssl_trusted_certificate /etc/nginx/certs/example.com.crt;
location ~* \.(jpg|jpe?g|gif|png|ico|cur|gz|svgz|mp4|ogg|ogv|webm|htc|css|js|otf|eot|svg|ttf|woff|woff2)(\?ver=[0-9.]+)?$ {
    expires modified 1M;
    add_header Access-Control-Allow-Origin '*';
    add_header Pragma public;
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    access_log off;
    }
    location ~ /.well-known { #For issuing LetsEncrypt Certificates
        allow all;
    }
location / {
    index index.php;
    try_files $uri $uri/ /index.php?$args;
    }
error_page  404    /404.php;

location ~ \.php$ {
    try_files       $uri =404;
    fastcgi_index   index.php;
    fastcgi_pass    unix:/tmp/php7-fpm.sock;
    #fastcgi_pass    php-container-hostname:9000; (if using docker)
    fastcgi_pass_request_headers on;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_param   SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_ignore_client_abort off;
    fastcgi_connect_timeout 60;
    fastcgi_send_timeout 180;
    fastcgi_read_timeout 180;
    fastcgi_request_buffering on;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 4 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    include fastcgi_params;
}
location = /robots.txt {
    access_log off;
    log_not_found off;
    }
location ~ /\. {
    deny  all;
    access_log off;
    log_not_found off;
    }
}

마지막으로, 2개의 nodejs 웹 서버 샘플:첫 번째 서버:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello From Nodejs\n');
}).listen(8080, "192.168.1.4");
console.log('Server running at http://192.168.1.4:8080/');

두 번째 서버:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello From Nodejs\n');
}).listen(8080, "192.168.1.5");
console.log('Server running at http://192.168.1.5:8080/');

이제 모든 것이 완벽하게 작동하고 로드 밸런싱이 되어야 합니다.

얼마 전에 도커에서 Nginx를 TCP 로드 밸런서로 설정하는 방법에 대해 썼습니다.도커를 사용하는 경우 확인하십시오.

각 마이크로서비스 수단을 관리하고 실행하려는 경우 pm2를 사용하여 nodejs를 실행할 수 있습니다.노드가 포트에서 실행 중입니다. Nginx에서 해당 포트를 구성하십시오(/etc/nginx/sites-enabled/domain.example)

server{
    listen 80;
    server_name domain.example www.domain.example;

  location / {
     return 403;
  }
    location /url {
        proxy_pass http://localhost:51967/info;
    }
}

ping을 사용하여 로컬 호스트가 실행 중인지 여부를 확인합니다.

그리고.

Create one single Node.js server which handles all Node.js requests. This reads the requested files and evals their contents. So the files are interpreted on each request, but the server logic is much simpler.

이것이 최선이고 당신이 말한 것처럼 더 쉽습니다.

언급URL : https://stackoverflow.com/questions/5009324/node-js-nginx-what-now

반응형