
我目前在為虛擬網路介面配置網關時遇到一些問題。
這是我所做的:
我建立了一個虛擬網路介面:
# brctl addbr lxc0
# brctl setfd lxc0 0
# ifconfig lxc0 192.168.0.1 promisc up
# route add -net default gw 192.168.0.1 lxc0
的輸出ifconfig
給了我我想要的:
lxc0 Link encap:Ethernet HWaddr 22:4f:e4:40:89:bb
inet adr:192.168.0.1 Bcast:192.168.0.255 Masque:255.255.255.0
adr inet6: fe80::88cf:d4ff:fe47:3b6b/64 Scope:Lien
UP BROADCAST RUNNING PROMISC MULTICAST MTU:1500 Metric:1
RX packets:623 errors:0 dropped:0 overruns:0 frame:0
TX packets:7412 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 lg file transmission:0
RX bytes:50329 (49.1 KiB) TX bytes:335738 (327.8 KiB)
我配置dnsmasq
為提供 DNS 伺服器(使用預設值:)192.168.1.1
和 DHCP 伺服器。
然後,我的 LXC guest 配置如下:
lxc.network.type=veth
lxc.network.link=lxc0
lxc.network.flags=up
一切都運作良好,我的容器有一個 IP (192.168.0.57
和192.168.0.98
)。我可以從容器和主機 ping 主機和容器:
(host)# ping -c 3 192.168.0.114
PING 192.168.0.114 (192.168.0.114) 56(84) bytes of data.
64 bytes from 192.168.0.114: icmp_req=1 ttl=64 time=0.044 ms
64 bytes from 192.168.0.114: icmp_req=2 ttl=64 time=0.038 ms
64 bytes from 192.168.0.114: icmp_req=3 ttl=64 time=0.043 ms
--- 192.168.0.114 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1998ms
rtt min/avg/max/mdev = 0.038/0.041/0.044/0.007 ms
(guest)# ping -c 3 192.168.0.1
PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data.
64 bytes from 192.168.0.1: icmp_req=1 ttl=64 time=0.048 ms
64 bytes from 192.168.0.1: icmp_req=2 ttl=64 time=0.042 ms
64 bytes from 192.168.0.1: icmp_req=3 ttl=64 time=0.042 ms
--- 192.168.0.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1999ms
rtt min/avg/max/mdev = 0.042/0.044/0.048/0.003 ms
現在,是時候將主機配置為網路的網關了192.168.0.0/24
:
#!/bin/sh
# Clear rules
iptables -F
iptables -t nat -F
iptables -t mangle -F
iptables -X
iptables -A FORWARD -i lxc0 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o lxc0 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
echo 1 > /proc/sys/net/ipv4/ip_forward
最終測試完全失敗,ping外部:
(guest)# ping -c 3 google.fr
PING google.fr (173.194.67.94) 56(84) bytes of data.
From 192.168.0.1: icmp_seq=3 Redirect Host(New nexthop: wi-in-f94.1e100.net (173.194.67.94))
From 192.168.0.1 icmp_seq=1 Destination Host Unreachable
From 192.168.0.1 icmp_seq=2 Destination Host Unreachable
From 192.168.0.1 icmp_seq=3 Destination Host Unreachable
--- google.fr ping statistics ---
3 packets transmitted, 0 received, +3 errors, 100% packet loss, time 2017ms
我錯過了什麼嗎?
答案1
我終於成功地透過使用這個 iptables 規則讓它運作:
#!/bin/sh
# Clear rules
iptables -F
iptables -t nat -F
iptables -t mangle -F
iptables -X
iptables -t nat -A POSTROUTING -s 192.168.0.0/24 -o eth0 -j MASQUERADE
echo 1 > /proc/sys/net/ipv4/ip_forward
該選項-s src_net
缺失。