도메인이 다른 동일한 IP / 서버에서 여러 Node.js 사이트를 호스팅하려면 어떻게해야합니까?
단일 IP가 바인딩 된 Linux 서버가 있습니다. 이 IP의이 서버에서 여러 Node.js 사이트를 호스팅하고 싶습니다. 각각 고유 한 도메인 또는 하위 도메인이 있습니다. 나는 그것들을 모두 포트 80에서 원합니다.
이 작업을 수행 할 수있는 옵션은 무엇입니까?
명백한 해결책은 프록시 역할을하고 고유 포트에서 실행되는 다른 node.js 앱을 통과하는 node.js 웹 앱에서 모든 도메인을 서비스하는 것 같습니다.
다음 중 하나를 선택하십시오.
- 다른 서버 ( 예 : nginx )를 역방향 프록시로 사용합니다.
- node-http-proxy 를 역방향 프록시로 사용 합니다 .
- 각 도메인이 동일한 Connect / Express 코드베이스 및 node.js 인스턴스에서 제공 될 수있는 경우 vhost 미들웨어를 사용하십시오 .
Diet.js 는 동일한 서버 인스턴스로 여러 도메인을 호스팅하는 매우 훌륭하고 간단한 방법을 제공합니다. server()
각 도메인에 대해간단히 새 전화를 걸 수 있습니다.
간단한 예
// Require diet
var server = require('diet');
// Main domain
var app = server()
app.listen('http://example.com/')
app.get('/', function($){
$.end('hello world ')
})
// Sub domain
var sub = server()
sub.listen('http://subdomain.example.com/')
sub.get('/', function($){
$.end('hello world at sub domain!')
})
// Other domain
var other = server()
other.listen('http://other.com/')
other.get('/', function($){
$.end('hello world at other domain')
})
앱 분리
앱에 대해 다른 폴더를 갖고 싶다면 다음과 같은 폴더 구조를 가질 수 있습니다.
/server
/yourApp
/node_modules
index.js
/yourOtherApp
/node_modules
index.js
/node_modules
index.js
에서 /server/index.js
당신이 그것의 폴더에 각 응용 프로그램을 요구한다 :
require('./yourApp')
require('./yourOtherApp')
다음 과 같은 첫 번째 도메인을/server/yourApp/index.js
설정합니다 .
// Require diet
var server = require('diet')
// Create app
var app = server()
app.listen('http://example.com/')
app.get('/', function($){
$.end('hello world ')
})
그리고 /server/yourOtherApp/index.js
다음 과 같은 두 번째 도메인을 설정합니다 .
// Require diet
var server = require('diet')
// Create app
var app = server()
app.listen('http://other.com/')
app.get('/', function($){
$.end('hello world at other.com ')
});
더 읽어보기 :
흠 ... nodejs가 프록시 역할을해야한다고 생각하는 이유. 다른 포트에서 수신 대기하는 여러 노드 앱을 실행하는 것이 좋습니다. 그런 다음 nginx를 사용하여 요청을 올바른 포트로 전달합니다. 단일 nodejs를 사용하는 경우 단일 실패 지점도 있습니다. 해당 앱이 충돌하면 모든 사이트가 다운됩니다.
nginx를 역방향 프록시로 사용합니다.
http://www.nginxtips.com/how-to-setup-nginx-as-proxy-for-nodejs/
Nginx는 캐싱, 정적 파일 처리, SSL 및로드 밸런싱의 형태로 애플리케이션에 모든 이점을 제공합니다.
사이트에서 사용하는 API가 있으며 아래는 내 구성입니다. SSL 및 GZIP도 있습니다. 누군가 필요하면 저에게 댓글을 달아주세요.
var http = require('http'),
httpProxy = require('http-proxy');
var proxy_web = new httpProxy.createProxyServer({
target: {
host: 'localhost',
port: 8080
}
});
var proxy_api = new httpProxy.createProxyServer({
target: {
host: 'localhost',
port: 8081
}
});
http.createServer(function(req, res) {
if (req.headers.host === 'http://www.domain.com') {
proxy_web.proxyRequest(req, res);
proxy_web.on('error', function(err, req, res) {
if (err) console.log(err);
res.writeHead(500);
res.end('Oops, something went very wrong...');
});
} else if (req.headers.host === 'http://api.domain.com') {
proxy_api.proxyRequest(req, res);
proxy_api.on('error', function(err, req, res) {
if (err) console.log(err);
res.writeHead(500);
res.end('Oops, something went very wrong...');
});
}
}).listen(80);
연결 / 익스프레스 서버를 사용하는 경우 vhost
미들웨어를 볼 수 있습니다 . 서버 주소로 여러 도메인 (하위 도메인)을 사용할 수 있습니다.
You can follow the example given here, which looks exactly like what you need.
The best way to do it is to use Express's vhost Middleware. Check out this tutorial for a step-by-step explanation:
http://shamadeh.com/blog/web/nodejs/express/2014/07/20/ExpressMultipleSites.html
This is my simplest demo project without any middleware or proxy.
This requires only a few codes, and it's enough.
https://github.com/hitokun-s/node-express-multiapp-demo
With this structure, you can easily set up and maintain each app independently.
I hope this would be a help for you.
First install forever and bouncy.
Then write a startup script. In this script, add a rule to the iptables firewall utility to tell it to forward the traffic on port 80 to port 8000 (or anything else that you choose). In my example, 8000 is where I run bouncy
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8000
Using forever, let's tell the script to run bouncy on port 8000
forever start --spinSleepTime 10000 /path/to/bouncy /path/to/bouncy/routes.json 8000
The routes.json would something like
{
“subdomain1.domain.com" : 5000,
“subdomain2.domain.com" : 5001,
“subdomain3.domain.com" : 5002
}
NodeJS application1, application2 and application3 run on port 5000, 5001 and 5002 respectively.
The script I use in my case can be found here and you might have to change a little to fit in your environment.
I also wrote about this in more details and you can find it here.
Here's how to do it using vanilla Node.js:
const http = require('http')
const url = require('url')
const port = 5555
const sites = {
exampleSite1: 544,
exampleSite2: 543
}
const proxy = http.createServer( (req, res) => {
const { pathname:path } = url.parse(req.url)
const { method, headers } = req
const hostname = headers.host.split(':')[0].replace('www.', '')
if (!sites.hasOwnProperty(hostname)) throw new Error(`invalid hostname ${hostname}`)
const proxiedRequest = http.request({
hostname,
path,
port: sites[hostname],
method,
headers
})
proxiedRequest.on('response', remoteRes => {
res.writeHead(remoteRes.statusCode, remoteRes.headers)
remoteRes.pipe(res)
})
proxiedRequest.on('error', () => {
res.writeHead(500)
res.end()
})
req.pipe(proxiedRequest)
})
proxy.listen(port, () => {
console.log(`reverse proxy listening on port ${port}`)
})
Pretty simple, huh?
This guide from digital ocean is an excellent way. It uses the pm2 module which daemonizes your app(runs them as a service). No need for additional modules like Forever, because it will restart your app automatically if it crashes. It has many features that help you monitor the various applications running on your server. It's pretty awesome!
litterly when you get the request and response object, you can get the domain through "request.headers.host"... (not the ip, actually the domain)
'Nice programing' 카테고리의 다른 글
일식에서 줄 번호의 왼쪽에있는 노란색 가로 화살표는 무엇을합니까? (0) | 2020.10.11 |
---|---|
mongodb-native findOne ()에서 변수를 필드 이름으로 사용하는 방법은 무엇입니까? (0) | 2020.10.11 |
ipython 노트북에 목차를 추가하려면 어떻게해야합니까? (0) | 2020.10.11 |
Xcode에서 빌드 타이밍을 활성화하는 방법은 무엇입니까? (0) | 2020.10.11 |
이름으로 C # .Net 어셈블리를 얻는 방법? (0) | 2020.10.11 |