Node.js + Nginx-이제 무엇입니까?
내 서버에 Node.js와 Nginx를 설정했습니다. 이제 사용하고 싶지만 시작하기 전에 두 가지 질문이 있습니다.
- 어떻게 함께 작동해야합니까? 요청을 어떻게 처리해야합니까?
Node.js 서버에는 두 가지 개념이 있습니다.
ㅏ. 필요한 각 웹 사이트에 대해 별도의 HTTP 서버를 만듭니다. 그런 다음 프로그램 시작시 모든 JavaScript 코드를로드하여 코드가 한 번 해석되도록합니다.
비. 모든 Node.js 요청을 처리하는 단일 Node.js 서버를 만듭니다. 요청 된 파일을 읽고 내용을 평가합니다. 따라서 파일은 각 요청에서 해석되지만 서버 논리는 훨씬 간단합니다.
Node.js를 올바르게 사용하는 방법이 명확하지 않습니다.
Nginx는 프런트 엔드 서버로 작동하며,이 경우 요청을 node.js 서버로 프록시합니다. 따라서 노드에 대한 nginx 구성 파일을 설정해야합니다.
이것은 우분투 상자에서 내가 한 일입니다.
다음 위치에서 파일 yourdomain.com
을 만듭니다 /etc/nginx/sites-available/
.
vim /etc/nginx/sites-available/yourdomain.com
그 안에 다음과 같은 것이 있어야합니다.
# 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.com www.yourdomain.com;
access_log /var/log/nginx/yourdomain.com.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)가 websocket 요청도 처리하도록하려면 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.com yourdomain.com
에서 노드 서버 앱을 /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
이제 yourdomain.com에 "Hello World"가 표시됩니다.
노드 서버 시작에 관한 마지막 참고 사항 : 노드 데몬에 대해 일종의 모니터링 시스템을 사용해야합니다. upstart 및 monit이있는 노드에 대한 멋진 튜토리얼 이 있습니다 .
nginx로 여러 도메인을 설정하여 여러 node.js 프로세스로 전달할 수도 있습니다.
예를 들어 다음을 달성하려면 :
- domain1.com-> 로컬에서 실행되는 Node.js 프로세스 http://127.0.0.1:4000
- domain2.com-> 로컬에서 실행되는 Node.js 프로세스 http://127.0.0.1:5000
이러한 포트 (4000 및 5000)는 앱 코드에서 앱 요청을 수신하는 데 사용해야합니다.
/ etc / nginx / sites-enabled / domain1
server {
listen 80;
listen [::]:80;
server_name domain1.com;
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.com;
access_log /var/log/nginx/domain2.access.log;
location / {
proxy_pass http://127.0.0.1:5000/;
}
}
하나의 서버 구성에서 앱에 대해 다른 URL을 가질 수도 있습니다.
- yourdomain.com/app1/*-> 로컬에서 실행되는 Node.js 프로세스 http://127.0.0.1:3000
- yourdomain.com/app2/*-> 로컬에서 실행되는 Node.js 프로세스 http://127.0.0.1:4000
에서 의 / etc / nginx를 / 사이트 사용 / 사용자 도메인 :
server {
listen 80;
listen [::]:80;
server_name yourdomain.com;
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를 사용하여 하위 폴더의 하나의 웹 서버에 여러 노드 애플리케이션 배포
로컬 호스트에서 인터넷으로 애플리케이션을 이동해야 할 때 Node를 사용하면 문제가 발생합니다.
노드 배포에 대한 일반적인 접근 방식은 없습니다.
Google은이 주제에 대한 수많은 기사를 찾을 수 있지만 필요한 설정에 적합한 솔루션을 찾기 위해 고군분투했습니다.
기본적으로 웹 서버가 있고 노드 응용 프로그램 이 응용 프로그램 코드에 대한 구성 종속성을 도입하지 않고 하위 폴더 (예 : 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와 같은 중복 레이어를 가질 필요가 없습니다. 정적 미들웨어.
Then all other requests are overwritten and proxied to Pet Project Node application, so the Node application does not need to know where it is actually mounted and thus can be moved anywhere purely by configuration.
proxy_redirect is a must to handle Location header properly. This is extremely important if you use res.redirect() in your Node application.
You can easily replicate this setup for multiple Node applications running on different ports and add more location handlers for other purposes.
From: http://skovalyov.blogspot.dk/2012/07/deploy-multiple-node-applications-on.html
Node.js with Nginx configuration.
$ sudo nano /etc/nginx/sites-available/subdomain.your_domain.com
add the following configuration so that Nginx acting as a proxy redirect to port 3000 traffic from the server when we come from “subdomain.your_domain.com”
upstream subdomain.your_domain.com {
server 127.0.0.1:3000;
}
server {
listen 80;
listen [::]:80;
server_name subdomain.your_domain.com;
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.com;
proxy_redirect off;
}
}
answering your question 2:
I would use option b
simply because it consumes much less resources. with option 'a', every client will cause the server to consume a lot of memory, loading all the files you need (even though i like php, this is one of the problems with it). With option 'b' you can load your libraries (reusable code) and share them among all client requests.
But be ware that if you have multiple cores you should tweak node.js to use all of them.
I made a repository in Github which you can clone, vagrant-node-nginx-boilerplate
basically the node.js app at /var/www/nodeapp
is
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/');
and the nginx config at /etc/nginx/sites-available/
is
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;
}
}
You could also use node.js to generate static files into a directory served by nginx. Of course, some dynamic parts of your site could be served by node, and some by nginx (static).
Having some of them served by nginx increases your performance..
We can easily setup a Nodejs app by Nginx acting as a reverse proxy.
The following configuration assumes the NodeJS application is running on 127.0.0.1:8080,
server{
server_name domain.com sub.domain.com; # 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
}
}
in above setup your Nodejs app will,
- get
HTTP_HOST
header where you can apply domain specific logic to serve the response. ' Your Application must be managed by a process manager like pm2 or supervisor for handling situations/reusing sockets or resources etc.
Setup an error reporting service for getting production errors like sentry or rollbar
NOTE: you can setup logic for handing domain specific request routes, create a middleware for expressjs application
Nginx can act as a reverse proxy server which works just like a project manager. When it gets a request it analyses it and forwards the request to upstream(project members) or handles itself. Nginx has two ways of handling a request based on how its configured.
- serve the request
forward the request to another server
server{ server_name mydomain.com sub.mydomain.com; 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; }
}
Server the request
With this configuration, when the request url is
mydomain.com/static/myjs.js
it returns themyjs.js
file in/my/static/files/path
folder. When you configure nginx to serve static files, it handles the request itself.
forward the request to another server
When the request url is
mydomain.com/dothis
nginx will forwards the request to http://127.0.0.1:8000. The service which is running on the localhost 8000 port will receive the request and returns the response to nginx and nginx returns the response to the client.
When you run node.js server on the port 8000 nginx will forward the request to node.js. Write node.js logic and handle the request. That's it you have your nodejs server running behind the nginx server.
If you wish to run any other services other than nodejs just run another service like Django, flask, php on different ports and config it in nginx.
You can run nodejs using pm2 if you want to manage each microservice means and run it. Node will be running in a port right just configure that port in nginx(/etc/nginx/sites-enabled/domain.com)
server{
listen 80;
server_name domain.com www.domain.com;
location / {
return 403;
}
location /url {
proxy_pass http://localhost:51967/info;
}
}
Check whether localhost is running or not by using ping.
And
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.
This is best and as you said easier too
참고URL : https://stackoverflow.com/questions/5009324/node-js-nginx-what-now
'Programing' 카테고리의 다른 글
데이터 속성으로 요소 선택 (0) | 2020.09.28 |
---|---|
로컬 저장소와 쿠키 (0) | 2020.09.28 |
주문 후 Oracle 쿼리에서 반환되는 행 수를 어떻게 제한합니까? (0) | 2020.09.28 |
문자의 ASCII 값을 얻는 방법은 무엇입니까? (0) | 2020.09.28 |
.gitignore가 추적되지 않는 파일 목록에 나타나지 않도록하려면 어떻게해야합니까? (0) | 2020.09.28 |