LoginSignup
19
17

More than 5 years have passed since last update.

macでvagrant上の仮想環境でnode.jsでウェブサーバーを立て外部からアクセスするまで

Last updated at Posted at 2015-10-21

macでvagrantを使って仮想環境を作り、node.jsでサーバーを立てて外部からアクセスしてみた。
首尾一貫した説明がなくてちょいちょい手こずったので備忘録がてら書いてみる。

1 環境

  • mac
  • vagrant
  • centOS6.6
  • node.js(v0.10.40)

2 vagrant

せっかくなのでここから。
仮想環境を作るソフト、手軽に仮想環境が作れてかつ外部とのファイルのやり取りができて便利とかそんな感じ。

vagrant

https://www.vagrantup.com/downloads-archive.html
から本体をダウンロード

virtual box

https://www.virtualbox.org/wiki/Downloads
からvirtual box for OS X hostsをダウンロード

各々インストールしておく

CentOS

http://www.vagrantbox.es/
からcentos(この場合は6.6、boxと呼ぶらしい)をダウンロード

仮想環境を立てる

適当なディレクトリを作成し、そこに移動

$ mkdir centos66
$ cd centos66
$ vagrant init centos
$ vim Vagrantfile

Vagrantfileの中身に

config.vm.network :forwarded_port, guest: 8000, host: 8000

を追加、これで外部からアクセスできるようになる。

$ vagrant up
$ vagrant ssh

で仮想マシンに入れるので、とりあえず

cd ../../vagrant

と打とう、このフォルダが先ほどのVagrantfileがあったフォルダとの共有フォルダになる。

3 node.js

次はnode.jsのインストール、ググって出てきた情報ではうまくいかなかったので、
素直に公式サイトのやり方でやってみる。

centOSの場合Run as rootとのことなのでsudoをつけて

$sudo curl --silent --location https://rpm.nodesource.com/setup | bash -
$sudo yum -y install nodejs

これでnode.jsが入ったはずだ。
次に適当なフォルダ(共有フォルダ内がベター)で適当にjsファイルを作る。

script.js
// httpのモジュールを用意
var http = require('http');

// サーバーの作成
var server = http.createServer();
server.on('request', function(request,response){
    // ヘッダ
    res.writeHead(200,{'Content-Type' : 'text/plain'});
    // 出力
    res.write('Hello World!!');
    // 終了
    res.end();
});
// ポートの指定
server.listen(8000);

とりあえずここまできたらサーバーが動くかどうか確認しよう。

$node script.js

ブラウザ上で
http://http://127.0.0.1:8000
にアクセス。hello world!が確認できたら外部からアクセスできている。

4 ウェブサーバー

外部からアクセスさえできてしまえば、あとはサーバーの方のスクリプトで
htmlファイルを読み込んで表示してしまえばいい。

適当なindex.htmlファイルを作る。

index.html
<html>
<head>
<title>nodesテスト</title>
</head>
<body>
<h1>Hello World!!</h1>
</body>
</html>

そして
スクリプトの方も書き換える。

script.js
// httpのモジュールとfsのモジュールを用意
var http = require('http');
var fs = require('fs');

// サーバーの作成
var server = http.createServer();

// アクセスされた際の挙動
server.on('request', function(request, response) {
  // htmlファイルが指定されなかった場合はindex.htmlを入れる。
  if(request.url == '/'){
    request.url = 'index.html';
  }
  // リクエストされたURLに従い、ファイルの中身を読み込む。
  fs.readFile('./' + request.url,'utf-8',function(error,data){
    if(error){
      // 見つからなかった場合404エラーを返す。
      response.writeHead(404,{'content-Type': 'text/plain'});
            response.write("not found");
            return response.end();
    }
    // ファイルが存在する場合htmlファイルの中身が格納されたdataを書き出す。
    response.writeHead(200,{'content-Type': 'text/html'});
      response.write(data);
      response.end();
  });
});

5 最後に

以上のことを行えば最低限目標は達成されるはずだが、記憶を頼りに書いているので
抜け等あれば連絡いただけると助かります。

19
17
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
19
17