80
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

Vagrant + VirtualBoxで仮想環境側のポートをあける

環境

ホストマシーン:mac
ゲストOS:Linux

やりたいこと

ホストマシーンから
ゲストOSのポート3000で動いているNode.jsアプリに
http://localhost:3000 でアクセスしたい。

やること

1. Vagrantfileにネットワーク設定追記

config.vm.network :private_networkでhostonlyネットワーク設定。
config.vm.network :forwarded_port, host: 3000, guest: 3000でホストマシーンの3000番ポートをゲストOSの3000番ポートへフォワードする

# -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "milk"
  config.vm.provider "virtualbox" do |vb|
    vb.customize [
      "modifyvm", :id,
      "--name", "milky_box",
      "--memory", "1024"
    ]
  end

  config.vm.hostname = "milky-vagrant"
  config.vm.network :private_network, ip: "192.168.33.10"
  config.vm.network :forwarded_port, host: 3000, guest: 3000
  config.vm.provision "shell", path: "setup.sh"
end

2. ゲストOSのポート解放設定

sudo vi /etc/sysconfig/iptables
-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT追記

追記後iptablesファイルの中身

# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited

3. 確認

/etc/hostsファイルに 127.0.0.1 localhost があるか確認し、
なければ追記。

ホストマシーンからhttp://localhost:3000 アクセス。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
80
Help us understand the problem. What are the problem?