2014年6月27日 星期五

【Apache2 in Ubuntu】Host a node.js site through apache

目的:在單一 ip 上的相同 port 運行 apache 與 nodejs 服務
之所以會那麼麻煩,是因為 Apache2 in Ubuntu 所在的 ip 位置
對外服務只開放 80 port
所以才想要在單一 port 上 run apache2 與 node.js
步驟如下:
  1. install mod_proxy and mod_proxy_http
  2. update apache2 conf
  3. run node.js app
  4. restart apache2 service
  • install mod_proxy
    1. sudo apt-get install libapache2-mod-proxy-html
    2. apt-get install libxml2-dev
    3. a2enmod proxy proxy_http

  • update apache2 conf
    1. vi /etc/apache2/site-available/000-default.conf
    2. 編輯 conf 檔案,加入以下數行 code
    3. <Virtual *:80>
          ProxyRequests off
       
          <Proxy *>
              Order deny,allow
              Allow from all
          </Proxy*>
       
          ProxyPass /api http://localhost:2368
          ProxyPassReverse /api http://localhost:2368
      </Virtual>
      

  • run node.js app
    1. app.js 程式碼如下:
    2. var express = require('express');
      var app = express();
      app.get('/', function(req, res) {
          res.send("Welcome nodejs and express app api");    
      });
      app.listen(2368);
      
    3. forever start app.js(須先安裝 forever 套件)

  • restart apache2 service
    1. service apache2 reload
    2. service apache2 restart
重啟 apache 服務後
這樣連線 www.servername.com.tw 就會連到 apache index.html
而連線 www.servername.com.tw/api 則 apache 會將 request 導向 nodejs 服務
這個方法可以保持 80 port 對外,但 /api 則可以送出 request 至 node.js 監聽的 port