KVM/nat接続(CUI)

Last-modified: 2011-11-23 (水) 17:15:04
最終更新:2011-11-23 (水) 17:15:04
アクセス数(合計):?
利用者; ? アクセス数(本日):? アクセス数(昨日):?

仮想サーバ構築 nat接続(CUI作業)

仮想化サーバ環境であるKVMを導入する。
KVMはKernel-based Virtual Machineの略。Intel VTまたはAMD-VをサポートするCPU上で完全仮想化を実現する。


サーバが遠隔地にある・GUI環境をサーバで構築してない等でGUI(グラフィック)によるインストールが出来ない場合、Telnet等によるCUI(コマンド)作業が必要となる。今回、nat接続をCUIにて構築する。


目的

仮想化によりホストサーバ上で複数サーバをnat接続で稼動させる。

構築条件

構築機器

  • 以下構成のPC上で構築
    CPUAthlon64x2 3600+
    ChipsetAMD 690G
    メモリ2GB

作成環境

OS    CentOS 6.0 64bit版

※動作CPUがIntel VT(インテルCPU)またはAMD-V(AMDCPU)をサポートしていること。
 インテルのどのCPUがサポートしているかは以下URLにて確認
http://www.pc-koubou.jp/info/win7_vt.php

サーバ作成条件

ホストOSサーバIP192.168.0.20/24
サーバMAC00:19:DB:88:74:4E
ホスト名KVMhost
user   hogehoge
userpasswdhogehogepass
ゲストOSサーバIP(外部)192.168.0.100/24
サーバIP(内部)192.168.122.100/24
ホスト名KVMguest
user   hogehoge
userpasswdhogehogepass

手順記入ルール

  • コマンド行頭記号で 「$」はユーザ権限 「#」はスーパーユーザー権限 を表示
  • コマンドが長くなる場合は、行末に「\」を記述し複数行に記述。

前準備

  1. CentOSインストール 実施
  2. yumリポジトリ設定 実施

KVMインストール

  • グループリスト確認
# yum grouplist
Loaded plugins: fastestmirror, refresh-packagekit
Setting up Group Process
Loading mirror speeds from cached hostfile

  :

  仮想化
  仮想化クライアント
  仮想化ツール
  仮想化プラットフォーム

  :

  • yumで仮想化のグループインストール実施
# yum groupinstall "仮想化" "仮想化クライアント" "仮想化ツール" "仮想化プラットフォーム"
Loaded plugins: fastestmirror, refresh-packagekit
Loading mirror speeds from cached hostfile

  :

==========================================================================================
 Package                      Arch     Version                            Repository
                                                                                     Size
==========================================================================================
Installing:
 libguestfs                   x86_64   1:1.2.7-1.24.el6                   base      805 k
 libvirt                      x86_64   0.8.1-27.el6_0.6                   updates   847 k
 libvirt-client               x86_64   0.8.1-27.el6_0.6                   updates   1.9 M
 python-virtinst              noarch   0.500.3-7.el6                      base      460 k
 qemu-kvm                     x86_64   2:0.12.1.2-2.113.el6_0.8           updates   976 k
 virt-manager                 noarch   0.8.4-8.el6                        base      1.0 M
 virt-top                     x86_64   1.0.4-3.1.el6                      base      359 k
 virt-viewer                  x86_64   0.2.1-2.el6                        base       68 k
Installing for dependencies:
 augeas-libs                  x86_64   0.7.2-3.el6                        base      289 k
 bridge-utils                 x86_64   1.2-9.el6                          base       30 k
 btrfs-progs                  x86_64   0.19-11.el6                        base      163 k

  :(略)

Transaction Summary
==========================================================================================
Install      59 Package(s)
Upgrade       1 Package(s)
Total download size: 23 M
Is this ok [y/N]:y

  :

Complete!
  • 再起動
#  reboot

★再起動実施

ゲストOS仮想化設定

★ゲストOSとして「CentOS6.0」をqcow2形式 8GBにて作成する手順

(1)仮想デスク作成

[telnet]

  • 仮想HDD作成
# qemu-img create -f qcow2 /var/lib/libvirt/images/KVMguest.qcow2 8GB
Formatting '/var/lib/libvirt/images/KVMguest.qcow2', fmt=qcow2 size=8589934592 encryption=off
cluster_size=0
  • 確認
# ls -l  /var/lib/libvirt/images/
-rw-r--r--. 1 root root 262144 11月 23 14:19 2011 KVMguest.qcow2
  • モード変更
# chmod 600 /var/lib/libvirt/images/KVMguest.qcow2
  • 確認
# ls -l  /var/lib/libvirt/images/
-rw-------. 1 root root 262144 11月 23 14:19 2011 KVMguest.qcow2

(2)ゲストOS定義ファイル作成

  • 仮想OS起動用テンプレート作成
# vi /etc/libvirt/qemu/public.kvm
  • 以下新規追加(一行で記入すること)

/usr/libexec/qemu-kvm -name KVMguest -boot d -no-reboot -m 1024 -smp 1 -net nic,model=virtio -net tap,ifname=network -vnc :1 -k ja -serial pty -drive index=0,format=qcow2,cache=none,file=/var/lib/libvirt/images/KVMguest.qcow2,if=virtio -cdrom /home/hogehoge/CentOS6.0_64bit.iso -usbdevice tablet

  • XML定義ファイル出力
# virsh domxml-from-native qemu-argv /etc/libvirt/qemu/public.kvm \
  > /etc/libvirt/qemu/KVMguest.xml
  • 確認
# ls -l  /etc/libvirt/qemu/KVMguest.xml
-rw-r--r--. 1 root root 1500 11月 23 14:23 2011 /etc/libvirt/qemu/KVMguest.xml
  • 確認
# cat /etc/libvirt/qemu/KVMguest.xml
<domain type='kvm'>
  <name>KVMguest</name>
  <uuid>25c79cef-99f6-61b0-d9a1-2bc8a283a5fc</uuid>
  <memory>1048576</memory>
  <currentMemory>1048576</currentMemory>
  <vcpu>1</vcpu>
  <os>
    <type arch='i686'>hvm</type>
    <boot dev='cdrom'/>
  </os>
  <features>
    <acpi/>
    <pae/>
  </features>
  <clock offset='utc'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>destroy</on_reboot>
  <on_crash>destroy</on_crash>
  <devices>
    <emulator>/usr/libexec/qemu-kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2' cache='none'/>
      <source file='/var/lib/libvirt/images/KVMguest.qcow2'/>
      <target dev='vda' bus='virtio'/>
    </disk>
    <disk type='file' device='cdrom'>
      <source file='/home/hogehoge/CentOS6.0_64bit.iso'/>
      <target dev='hdc' bus='ide'/>
      <readonly/>
      <address type='drive' controller='0' bus='1' unit='0'/>
    </disk>
    <controller type='ide' index='0'/>
    <interface type='ethernet'>
      <mac address='52:54:00:44:a3:f5'/>
      <target dev='network'/>
      <model type='virtio'/>
    </interface>
    <serial type='pty'>
      <target port='0'/>
    </serial>
    <console type='pty'>
      <target port='0'/>
    </console>
    <input type='tablet' bus='usb'/>
    <input type='mouse' bus='ps2'/>
    <graphics type='vnc' port='5901' autoport='no' listen=''/>
    <video>
      <model type='cirrus' vram='9216' heads='1'/>
    </video>
    <memballoon model='virtio'/>
  </devices>
</domain>

(3)ゲストOS定義ファイル編集

  • 確認
# vi /etc/libvirt/qemu/KVMguest.xml
  • 必要な箇所を編集
    <domain type='kvm'>
      <name>KVMguest</name>
      <uuid>25c79cef-99f6-61b0-d9a1-2bc8a283a5fc</uuid>
      <memory>1048576</memory>
      <currentMemory>1048576</currentMemory>
      <vcpu>1</vcpu>
      <os>
        <type arch='x86_64' machine='rhel6.0.0'>hvm</type>  ←旧:'i686'
        <boot dev='cdrom'/>
      </os>
      <features>
        <acpi/>
        <pae/>
      </features>
      <clock offset='utc'/>
      <on_poweroff>destroy</on_poweroff>
      <on_reboot>destroy</on_reboot>
      <on_crash>destroy</on_crash>
      <devices>
        <emulator>/usr/libexec/qemu-kvm</emulator>
        <disk type='file' device='disk'>
          <driver name='qemu' type='qcow2' cache='none'/>
          <source file='/var/lib/libvirt/images/KVMguest.qcow2'/>
          <target dev='vda' bus='virtio'/>
        </disk>
        <disk type='file' device='cdrom'>
          <source file='/home/hogehoge/CentOS6.0_64bit.iso'/>
          <target dev='hdc' bus='ide'/>
          <readonly/>
          <address type='drive' controller='0' bus='1' unit='0'/>
        </disk>
        <controller type='ide' index='0'/>
        <interface type='network'>  ←旧:ethernet
          <mac address='52:54:00:44:a3:f5'/>
         <source network='default'/> ←追加
          <target dev='network'/>  ←削除
          <model type='virtio'/>
        </interface>
        <serial type='pty'>
          <target port='0'/>
        </serial>
        <console type='pty'>
          <target port='0'/>
        </console>
        <input type='tablet' bus='usb'/>
        <input type='mouse' bus='ps2'/>
        <graphics type='vnc' port='5901' autoport='no' listen=''/>
        <video>
          <model type='cirrus' vram='9216' heads='1'/>
        </video>
        <memballoon model='virtio'/>
      </devices>
    </domain>

(4)XML定義ファイル修正後の反映

  • XML定義ファイル修正後の反映
# virsh define /etc/libvirt/qemu/KVMguest.xml
ドメイン KVMguest が /etc/libvirt/qemu/KVMguest.xml から定義されました
  • 確認
#  virsh list --all
 Id 名前               状態
----------------------------------
  - KVMguest             シャットオフ

★KVMguestが追加されていること

ゲストOS インストール

(1)ISOイメージOS準備

ftpやwgetにて、ユーザエリア「/home/hogehoge」にインストールするOSのISOファイルをアップ
今回は「CentOS6.0_64bit.iso」を使用

(2)OSインストール

  • 権限付与
# ls -l ../
drwx------. 4 hogehoge hogehoge  4096 11月 23 11:49 2011 hogehoge
# chmod go+rx ../hogehoge/
# ls -l ../
drwxr-xr-x. 4 hogehoge hogehoge  4096 11月 23 11:49 2011 hogehoge
  • OSインストール
# virsh start KVMguest
ドメイン KVMguest が起動されました
  • VNC接続
    realvncツールで、「192.168.0.20:5901」に接続
    ★「-vnc :x」の指定で「port 590x」接続となる。 -vnc:1 指定の場合は 192.168.0.20:5901 となる。
  • 以下画面が表示

KVMcui-01.png

(3)ゲストOSのインストール実施

ゲストOSを以下条件でインストール。

  • ホスト名  KVMguest
  • 設定アドレス 192.168.122.100
  • ネットマスク 255.255.255.0
  • ゲートウェイ 192.168.122.1

★Defaultゲートウェイが「192.168.122.1/24」であるため、ここに接続できるIPアドレスを設定する。


★インストール完了後「再起動」押下でシャットオフ状態に移行

  • 確認
# virsh list --all
 Id 名前               状態
----------------------------------
  - KVMguest             シャットオフ

(3)ゲストOS定義ファイル編集

  • HDDブートなるよう修正
# vi /etc/libvirt/qemu/KVMguest.xml
  • 必要な箇所を編集
    <domain type='kvm'>
      <name>KVMguest</name>
      <uuid>25c79cef-99f6-61b0-d9a1-2bc8a283a5fc</uuid>
      <memory>1048576</memory>
      <currentMemory>1048576</currentMemory>
      <vcpu>1</vcpu>
      <os>
        <type arch='x86_64' machine='rhel6.0.0'>hvm</type>
        <boot dev='hd'/>     ←旧:cdrom
      </os>
      <features>
        <acpi/>
        <pae/>
      </features>
      <clock offset='utc'/>
      <on_poweroff>destroy</on_poweroff>
      <on_reboot>restart</on_reboot>    ←旧:destroy
      <on_crash>restart</on_crash>    ←旧:destroy
      <devices>
        <emulator>/usr/libexec/qemu-kvm</emulator>
        <disk type='file' device='disk'>
          <driver name='qemu' type='qcow2' cache='none'/>
          <source file='/var/lib/libvirt/images/KVMguest.qcow2'/>
          <target dev='vda' bus='virtio'/>
        </disk>
        <disk type='file' device='cdrom'>   ←削除
          <driver name='qemu' type='raw'/>   ←削除
          <source file='/home/hogehoge/CentOS6.0_64bit.iso'/>   ←削除
          <target dev='hdc' bus='ide'/>   ←削除
          <readonly/>   ←削除
          <address type='drive' controller='0' bus='1' unit='0'/>   ←削除
        </disk>   ←削除
        <controller type='ide' index='0'/>
        <interface type='network'>
          <mac address='52:54:00:44:a3:f5'/>
          <source network='default'/>
          <target dev='network'/>
          <model type='virtio'/>
        </interface>
        <serial type='pty'>
          <target port='0'/>
        </serial>
        <console type='pty'>
          <target port='0'/>
        </console>
        <input type='tablet' bus='usb'/>
        <input type='mouse' bus='ps2'/>
        <graphics type='vnc' port='5901' autoport='no' listen=''/>
        <video>
          <model type='cirrus' vram='9216' heads='1'/>
        </video>
        <memballoon model='virtio'/>
      </devices>
    </domain>

(4)XML定義ファイル修正後の反映

  • XML定義ファイル修正後の反映
# virsh define /etc/libvirt/qemu/KVMguest.xml
ドメイン KVMguest が /etc/libvirt/qemu/KVMguest.xml から定義されました
  • 確認
# virsh list --all
 Id 名前               状態
----------------------------------
  - KVMguest             シャットオフ

(5)ゲストOS起動

  • OS起動
# virsh start KVMguest
ドメイン KVMguest が起動されました
  • インストールの続きおよびサーバの起動を実施
  • VNC接続
    ★インストールの続きおよびサーバの起動を実施
     
    realvncツールで、「192.168.0.20:5901」に接続
    ★「-vnc :x」の指定で「port 590x」接続となる。 -vnc:1 指定の場合は 192.168.0.20:5901 となる。

nat接続設定

(1)フォワード設定

外部ネット⇔(ホストOS)⇔ゲストOS 間のIP転送を有効化する

  • sysctl.confフォワード設定
# vi /etc/sysctl.conf
# Controls IP packet forwarding
net.ipv4.ip_forward = 0

   ↓

net.ipv4.ip_forward = 1
  • ip_forwardフォワード設定確認
# cat /proc/sys/net/ipv4/ip_forward
1

※「0」の場合は「1に変更」

  • ネットワーク再起動
# service network restart
インターフェース eth0 を終了中:  デバイスの状態: 3 (切断済み)
                                                           [  OK  ]
ループバックインターフェースを終了中                       [  OK  ]
ループバックインターフェイスを呼び込み中                   [  OK  ]
インターフェース eth0 を活性化中:  アクティブ接続の状態: アクティベート済み
アクティブ接続のパス: /org/freedesktop/NetworkManager/ActiveConnection/1
                                                           [  OK  ]

(2)仮想IP設定

外部ネット⇔192.168.0.100(ホストOS) 外部からゲストOSアクセス用のIPアドレスを設定


  • 仮想IPデータ設定
# vi /etc/sysconfig/network-scripts/ifcfg-eth0
  • 末尾3行に設定する仮想IPアドレス情報を追加
    DEVICE="eth0"
    NM_CONTROLLED="yes"
    ONBOOT=yes
    HWADDR=00:19:DB:88:74:4E
    TYPE=Ethernet
    BOOTPROTO=none
    IPADDR=192.168.0.20
    PREFIX=24
    GATEWAY=192.168.0.1
    DNS1=192.168.0.1
    DOMAIN=192.168.0.1
    DEFROUTE=yes
    IPV4_FAILURE_FATAL=yes
    IPV6INIT=no
    NAME="System eth0"
    UUID=5fb06bd0-0bb0-7ffb-45f1-d6edd65f3e03
    IPADDR2=192.168.0.100
    PREFIX2=24
    GATEWAY2=192.168.0.1
  • ネットワーク再起動
# ifup eth0
アクティブ接続の状態: アクティベート済み
アクティブ接続のパス: /org/freedesktop/NetworkManager/ActiveConnection/3
  • 確認
# ip addr show
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:19:db:88:74:4e brd ff:ff:ff:ff:ff:ff
    inet 192.168.0.20/24 brd 192.168.0.255 scope global eth0
    inet 192.168.0.100/24 brd 192.168.0.255 scope global secondary eth0
    inet6 fe80::219:dbff:fe88:744e/64 scope link
       valid_lft forever preferred_lft forever

 ★(#ifconfig)では追加アドレス 192.168.0.100は出ない

# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:19:DB:88:74:4E
          inet addr:192.168.0.20  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::219:dbff:fe88:744e/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:27800 errors:0 dropped:0 overruns:0 frame:0
          TX packets:34480 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:2342347 (2.2 MiB)  TX bytes:36708395 (35.0 MiB)
          Interrupt:25
  • 通信可能か確認
# ping 192.168.0.100
PING 192.168.0.100 (192.168.0.100) 56(84) bytes of data.
64 bytes from 192.168.0.100: icmp_seq=1 ttl=64 time=0.033 ms

  :

 ★応答があること

(3)nat設定

外部ネット⇔192.168.0.100(ホストOS)⇔192.168.122.100ゲストOS nat接続設定

  • テーブル情報クリア
# iptables -F
# iptables -F -t nat
  • 接続フィルター設定
# iptables -A INPUT -p all -j ACCEPT
# iptables -A FORWARD -p all -d 192.168.122.0/24 -j ACCEPT
# iptables -A FORWARD -p all -s 192.168.122.0/24 -j ACCEPT
  • nat設定
# iptables -t nat -A POSTROUTING -s 192.168.122.100 -j SNAT --to 192.168.0.100
# iptables -t nat -A PREROUTING -d 192.168.0.100 -p tcp -j DNAT --to 192.168.122.100
# iptables -t nat -A PREROUTING -d 192.168.0.100 -p icmp -j DNAT --to 192.168.122.100
  • 確認
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             192.168.122.0/24
ACCEPT     all  --  192.168.122.0/24     anywhere
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
  • 確認(NAT)
# iptables -L -t nat
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
DNAT       tcp  --  anywhere             192.168.0.100       to:192.168.122.100
DNAT       icmp --  anywhere             192.168.0.100       to:192.168.122.100
Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
SNAT       all  --  192.168.122.100      anywhere            to:192.168.0.100
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
  • 通信可能か確認
# ping 192.168.0.100
PING 192.168.0.100 (192.168.0.100) 56(84) bytes of data.
64 bytes from 192.168.0.100: icmp_seq=1 ttl=64 time=0.054 ms

  :
★応答があること

(4)nat保存

  • iptablesを保存し、再起動後も再設定されるようにする
# /etc/rc.d/init.d/iptables save
iptables: ファイアウォールのルールを /etc/sysconfig/iptable[  OK  ]中:

★実際には再開後は初期状態に戻るため、iptablesの再設定を行う必要あり

後処理

(1)ゲストOS停止

ゲストOSにtelnetでログイン後シャットダウン実施

  • 確認
# virsh list --all
 Id 名前               状態
----------------------------------
  - KVMguest             シャットオフ

(2)スナップショット作成

★不具合時に戻せるよう初期状態を保存しておく

  • スナップショット作成
# qemu-img snapshot -c KVMguestSnapshot0 /var/lib/libvirt/images/KVMguest.qcow2
  • 確認
# qemu-img snapshot -l /var/lib/libvirt/images/KVMguest.qcow2
Snapshot list:
ID        TAG                 VM SIZE                DATE       VM CLOCK
1         KVMguestSnapshot0         0 2011-11-23 17:10:02   00:00:00.000

(3)ゲストOS定義ファイル編集

  • vncアクセスを無効とする。
# vi /etc/libvirt/qemu/KVMguest.xml
  • 必要な箇所を編集
    <domain type='kvm'>
      <name>KVMguest</name>
      <uuid>25c79cef-99f6-61b0-d9a1-2bc8a283a5fc</uuid>
      <memory>1048576</memory>
      <currentMemory>1048576</currentMemory>
      <vcpu>1</vcpu>
      <os>
        <type arch='x86_64' machine='rhel6.0.0'>hvm</type>
        <boot dev='hd'/>
      </os>
      <features>
        <acpi/>
        <pae/>
      </features>
      <clock offset='utc'/>
      <on_poweroff>destroy</on_poweroff>
      <on_reboot>restart</on_reboot>
      <on_crash>restart</on_crash>
      <devices>
        <emulator>/usr/libexec/qemu-kvm</emulator>
        <disk type='file' device='disk'>
          <driver name='qemu' type='qcow2' cache='none'/>
          <source file='/var/lib/libvirt/images/KVMguest.qcow2'/>
          <target dev='vda' bus='virtio'/>
        </disk>
        <controller type='ide' index='0'/>
        <interface type='network'>
          <mac address='52:54:00:44:a3:f5'/>
          <source network='default'/>
          <target dev='network'/>
          <model type='virtio'/>
        </interface>
        <serial type='pty'>
          <target port='0'/>
        </serial>
        <console type='pty'>
          <target port='0'/>
        </console>
        <input type='tablet' bus='usb'/>
        <input type='mouse' bus='ps2'/>
        <graphics type='vnc' port='5901' autoport='no' listen=/>'' ←削除
        <video>
          <model type='cirrus' vram='9216' heads='1'/>
        </video>
        <memballoon model='virtio'/>
      </devices>
    </domain>

(4)XML定義ファイル修正後の反映

  • XML定義ファイル修正後の反映
# virsh define /etc/libvirt/qemu/KVMguest.xml
ドメイン KVMguest が /etc/libvirt/qemu/KVMguest.xml から定義されました

(5)ゲストOS起動

  • OS起動
# virsh start KVMguest
ドメイン KVMguest が起動されました
  • 確認
# virsh list --all
 Id 名前               状態
----------------------------------
 11 KVMguest             実行中
  • vnc接続不可確認
  • VNC接続
     
    realvncツールで、「192.168.0.20:5901」に接続
    ★接続エラーとなること

遭遇したトラブル

ゲストOSが作成できない

問題:
仮想マネージャーで仮想ホストを作成出来ない

原因:
CPUに仮想化支援機能が無い。・・特にインテルのモバイルCPUは最新CPUでも仮想化未対応の場合があるので注意!
以下URLにて仮想化対応しているか確認すること
http://www.pc-koubou.jp/info/win7_vt.php

vncが繋がらない

問題:
vncで5901ポートに接続に行ってもタイムアウトで繋がらない

原因:
ファイヤーウォールが有効となっているため。ファイヤウォールを無効とすること

xml再定義で「ドメイン定義に失敗しました」エラーになる

問題:
xml再定義でエラーが出る

# virsh define /etc/libvirt/qemu/KVMtest.xml

エラー: /etc/libvirt/qemu/KVMtest.xml からのドメイン定義に失敗しました
エラー: operation failed: domain 'KVMtest' already exists with uuid 691cc381-0142-07db-86a4-2d36567c21c4

原因:
virshで同じ仮想ドメイン名が残っているため。以下コマンドで仮想ドメインを消しておく

# virsh undefine KVMtest

謝辞

テキスト作成にあたり、以下サイトを参考にさせて頂きました。ありがとうございます。

http://wingse.blog57.fc2.com/blog-entry-274.html#more