Apache和Node.js的共存

如何使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

给予除了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

代理设置。

$ 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

这样就可以了。

4. httpd.conf文件的设置

将Apache处理的默认端口从80更改为8080。

$ vi httpd.conf 

NameVirtualHost *:8080
Listen 8080

如果您正在进行虚拟主机设置,也请考虑以下内容。

<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

为了始终保持节点程序运行,可通过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

广告
将在 10 秒后关闭
bannerAds