LoginSignup
103
105

More than 5 years have passed since last update.

ApacheとNode.jsの共存

Last updated at Posted at 2014-08-23

ApacheとNode.jsを共存させる方法。

さくらVPSでApacheで立てたサーバの他にNodeで立てたサーバが必要になったので、その作業のメモ。

ApacheやNode.jsは既にインストールされているものとする。

構成は以下の通り。

node-http-proxy (Port 80)
│
├─Apache  (Port 8080) example.com, apache.example.com
│
└─Node.js (Port 8081) node.example.com

使用した環境

  • CentOS 6.5
  • node v0.10.29
  • npm 1.3.6
  • apache 2.2.15

1. rootユーザ以外にもポート80番の実行権を与える

80番はrootでないと使用できないため、任意のユーザ(ここではhogeとする)に実行権を与える。

任意のユーザの追加とグループをwheelに変更

$ useradd hoge
$ passwd hoge

$ usermod -G wheel hoge

追加したユーザのIDを調べる

$ id -u hoge

ここで吐出された番号(たぶん500)をメモっておく。

2. node-http-proxyの導入

npmでhttp-proxyをインストール。

npm install http-proxy
npm link http-proxy

proxyの設定。

$ vi proxy.js

var http = require('http');
var httpProxy = require('http-proxy');

var apacheProxy = new httpProxy.createProxyServer({
    target: {
    host: 'localhost',
    port: 8080
}});

var nodeProxy = new httpProxy.createProxyServer({
    target: {
    host: 'localhost',
    port: 8081
}});

var server = http.createServer(function ( req, res ) {
    if (req.headers.host == 'example.com' || req.headers.host == 'apache.example.com') {
        apacheProxy.web( req, res );
    } else if (req.headers.host == 'node.example.com') {
        nodeProxy.web( req, res );
    } else {
        res.writeHead(404);
        res.end();
    }
});

server.listen(80, function(){
  process.setuid(500); //上記で設定したユーザID
});
console.log('It Works!');

3. iptablesの設定

iptablesを設定しているなら、サーバ内部でルーティングしているため、80ポートのみが通ればよく、8080や8081は通さなくてもいい。

$ vi  /etc/sysconfig/iptables

-A SERVICES -p tcp --dport 80 -j ACCEPT

これでOK.

4. httpd.confの設定

apacheで処理しているデフォルトのポートを80から8080に変更する。

$ vi httpd.conf 

NameVirtualHost *:8080
Listen 8080

Virtual Hostの設定をしているなら以下も。

<VirtualHost *:8080>
  DocumentRoot /home/www/public
  ServerName example.com
</VirtualHost>

<VirtualHost *:8080>
  DocumentRoot /home/www/hoge/public
  ServerName apache.example.com
</VirtualHost>

httpdの再起動

$ service httpd restart

5. foreverのインストール

nodeのプログラムを常に動かすようにするため、npmでforeverのインストール

$ sudo npm install forever -g
$ forever start proxy.js

これで終わり。

参考

http://o.inchiki.jp/obbr/50
http://com4tis.net/2013/05/23/sakura-vps-apache-node-js-install-2/
https://gist.github.com/nnnnathann/3491640
http://qiita.com/kakakazuma/items/a65a984378c0c291cfda

103
105
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
103
105