Skip to content

Instantly share code, notes, and snippets.

@JamesHopbourn
Created August 2, 2025 01:34
Show Gist options
  • Save JamesHopbourn/7be49bfe4ec3c2c6cdf10e4382d2fe77 to your computer and use it in GitHub Desktop.
Save JamesHopbourn/7be49bfe4ec3c2c6cdf10e4382d2fe77 to your computer and use it in GitHub Desktop.
小型虚拟网络环境搭建 - Gateway-Server-Client架构

小型虚拟网络环境配置教程

本教程将指导你使用 Multipass 搭建一个 Gateway-Server-Client 架构的虚拟网络环境,实现网关转发通信的场景。

目录

环境要求

软件要求

  • Multipass - 跨平台虚拟机管理工具
  • 宿主机至少 8GB 内存和 50GB 可用磁盘空间
  • 支持虚拟化的操作系统 (Windows/macOS/Linux)

安装 Multipass

macOS:

brew install --cask multipass

Ubuntu/Debian:

sudo snap install multipass

Windows: 下载并安装 Multipass Windows Installer

架构概述

[Client VM]  ──>  [Gateway VM]  ──>  [Server VM]
192.168.69.24    192.168.69.22      192.168.69.23
                     ↓
               IP 转发 + NAT

网络拓扑

  • Client (192.168.69.24): 客户端,发起请求
  • Gateway (192.168.69.22): 网关,负责转发流量
  • Server (192.168.69.23): 服务器,提供 HTTP 服务

快速开始

如果你只想快速搭建环境,可以运行我们提供的自动化脚本:

# 下载配置脚本
curl -O https://raw.githubusercontent.com/your-repo/network-lab/main/setup_network.sh

# 运行配置脚本
chmod +x setup_network.sh
./setup_network.sh

# 运行测试脚本
./test_network.sh

详细配置步骤

第一步:创建虚拟机

创建三台 Ubuntu 虚拟机:

# 创建 Gateway VM
multipass launch --name gateway --cpus 2 --memory 4G --disk 10G

# 创建 Server VM
multipass launch --name server --cpus 2 --memory 4G --disk 10G

# 创建 Client VM
multipass launch --name client --cpus 2 --memory 4G --disk 10G

验证虚拟机状态:

multipass list

预期输出:

Name                    State             IPv4             Image
client                  Running           192.168.69.24    Ubuntu 24.04 LTS
gateway                 Running           192.168.69.22    Ubuntu 24.04 LTS
server                  Running           192.168.69.23    Ubuntu 24.04 LTS

第二步:配置 Gateway VM

启用 IP 转发

# 临时启用 IP 转发
multipass exec gateway -- sudo sysctl -w net.ipv4.ip_forward=1

# 永久启用 IP 转发
multipass exec gateway -- sudo bash -c 'echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf'

配置 iptables NAT 规则

# 设置 NAT 规则 - 允许内网访问外网
multipass exec gateway -- sudo iptables -t nat -A POSTROUTING -s 192.168.69.0/24 -o enp0s1 -j MASQUERADE

# 允许已建立连接的转发
multipass exec gateway -- sudo iptables -A FORWARD -i enp0s1 -o enp0s1 -m state --state RELATED,ESTABLISHED -j ACCEPT

# 允许内网之间的转发
multipass exec gateway -- sudo iptables -A FORWARD -i enp0s1 -o enp0s1 -j ACCEPT

验证 Gateway 配置

# 检查 IP 转发状态
multipass exec gateway -- sysctl net.ipv4.ip_forward

# 查看 NAT 规则
multipass exec gateway -- sudo iptables -t nat -L POSTROUTING

第三步:配置 Server VM

创建 HTTP 服务

# 创建简单的 HTML 文件
multipass exec server -- bash -c 'cd /home/ubuntu && echo "Hello from Server - IP: $(hostname -I)" > index.html'

# 启动 Python HTTP 服务
multipass exec server -- bash -c 'cd /home/ubuntu && nohup python3 -m http.server 8000 > server.log 2>&1 &'

验证服务运行

# 检查服务进程
multipass exec server -- ps aux | grep python

# 检查服务端口
multipass exec server -- ss -tlnp | grep 8000

第四步:配置 Client VM

安装网络工具

# 安装测试工具
multipass exec client -- sudo apt update
multipass exec client -- sudo apt install -y curl traceroute net-tools

第五步:网络连接测试

基本连通性测试

# 从 Client 访问 Server HTTP 服务
multipass exec client -- curl http://192.168.69.23:8000

预期输出:

Hello from Server - IP: 192.168.69.23 fd97:7251:3a98:39aa:5054:ff:fed2:cce3

路由跟踪测试

# 跟踪从 Client 到 Server 的路由
multipass exec client -- traceroute 192.168.69.23

预期输出:

traceroute to 192.168.69.23 (192.168.69.23), 30 hops max, 60 byte packets
 1  192.168.69.23 (192.168.69.23)  0.408 ms  0.387 ms  0.382 ms

验证测试

自动化测试脚本

使用提供的测试脚本进行全面验证:

./test_network.sh

手动测试命令

# 1. 测试 HTTP 连接
multipass exec client -- curl -v http://192.168.69.23:8000

# 2. 测试路由跟踪
multipass exec client -- traceroute 192.168.69.23

# 3. 检查 Gateway 转发规则
multipass exec gateway -- sudo iptables -L

# 4. 检查网络接口状态
multipass exec gateway -- ip addr show
multipass exec server -- ip addr show
multipass exec client -- ip addr show

# 5. 测试服务可用性
multipass exec server -- curl localhost:8000

高级配置

持久化 iptables 规则

为了确保重启后规则依然有效:

# 安装 iptables-persistent
multipass exec gateway -- sudo apt install -y iptables-persistent

# 保存当前规则
multipass exec gateway -- sudo iptables-save | sudo tee /etc/iptables/rules.v4

创建服务自启动

创建 systemd 服务文件让 HTTP 服务开机自启:

multipass exec server -- sudo tee /etc/systemd/system/webserver.service > /dev/null << 'EOF'
[Unit]
Description=Python Web Server
After=network.target

[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu
ExecStart=/usr/bin/python3 -m http.server 8000
Restart=always

[Install]
WantedBy=multi-user.target
EOF

# 启用并启动服务
multipass exec server -- sudo systemctl enable webserver.service
multipass exec server -- sudo systemctl start webserver.service

网络监控

添加流量监控功能:

# 在 Gateway 上安装网络监控工具
multipass exec gateway -- sudo apt install -y iftop tcpdump

# 监控网络流量
multipass exec gateway -- sudo tcpdump -i enp0s1 host 192.168.69.23

故障排除

常见问题

1. 虚拟机无法启动

# 检查 Multipass 状态
multipass version
multipass list

# 重启 Multipass 服务 (macOS/Linux)
sudo multipass restart

2. HTTP 服务无法访问

# 检查服务状态
multipass exec server -- ps aux | grep python
multipass exec server -- ss -tlnp | grep 8000

# 重启服务
multipass exec server -- pkill python3
multipass exec server -- bash -c 'cd /home/ubuntu && nohup python3 -m http.server 8000 > server.log 2>&1 &'

3. 网络转发不工作

# 检查 IP 转发设置
multipass exec gateway -- sysctl net.ipv4.ip_forward

# 重新配置 iptables 规则
multipass exec gateway -- sudo iptables -F
multipass exec gateway -- sudo iptables -t nat -F
# 然后重新添加规则(参考第二步)

4. 无法 ping 通其他虚拟机

# 检查防火墙状态
multipass exec gateway -- sudo ufw status
multipass exec server -- sudo ufw status
multipass exec client -- sudo ufw status

# 如果防火墙启用,可以临时关闭测试
multipass exec gateway -- sudo ufw disable

日志查看

# 查看 Server 日志
multipass exec server -- cat server.log

# 查看系统日志
multipass exec gateway -- sudo journalctl -f

网络诊断

# 检查路由表
multipass exec client -- ip route
multipass exec server -- ip route
multipass exec gateway -- ip route

# 检查 ARP 表
multipass exec client -- arp -a

# 检查连接状态
multipass exec client -- netstat -tuln

性能优化

调整虚拟机资源

根据需要调整虚拟机配置:

# 停止虚拟机
multipass stop gateway server client

# 修改配置(需要重新创建)
multipass delete gateway server client
multipass purge

# 重新创建具有更多资源的虚拟机
multipass launch --name gateway --cpus 4 --memory 8G --disk 20G

网络性能测试

# 安装网络性能测试工具
multipass exec server -- sudo apt install -y iperf3
multipass exec client -- sudo apt install -y iperf3

# 在 Server 上启动 iperf3 服务
multipass exec server -- iperf3 -s &

# 在 Client 上测试带宽
multipass exec client -- iperf3 -c 192.168.69.23

清理环境

停止和删除虚拟机

# 停止所有虚拟机
multipass stop gateway server client

# 删除虚拟机
multipass delete gateway server client

# 清理已删除的虚拟机
multipass purge

# 验证清理完成
multipass list

清理脚本文件

# 删除配置脚本
rm -f setup_network.sh test_network.sh

# 删除日志文件
rm -f *.log

扩展实验

实验 1:添加防火墙规则

# 在 Gateway 上设置更严格的防火墙规则
multipass exec gateway -- sudo iptables -P FORWARD DROP
multipass exec gateway -- sudo iptables -A FORWARD -s 192.168.69.24 -d 192.168.69.23 -p tcp --dport 8000 -j ACCEPT
multipass exec gateway -- sudo iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT

实验 2:负载均衡配置

# 创建第二台服务器
multipass launch --name server2 --cpus 2 --memory 4G --disk 10G

# 在 Gateway 上配置负载均衡
multipass exec gateway -- sudo apt install -y nginx
# 配置 nginx 作为负载均衡器...

实验 3:VPN 隧道

# 安装 OpenVPN
multipass exec gateway -- sudo apt install -y openvpn

# 配置 VPN 服务器...

参考资料

技术支持

如果遇到问题,可以:

  1. 查看本文档的故障排除部分
  2. 检查 Multipass 官方文档
  3. 在项目 GitHub 仓库提交 Issue
  4. 查看相关日志文件进行诊断

注意: 本教程基于 Ubuntu 24.04 LTS 系统,其他版本可能需要适当调整命令。

#!/bin/bash
# Network setup script for Gateway-Server-Client architecture
# This script configures the network topology as described in the requirements
echo "Starting network configuration..."
# Start all VMs
echo "Starting VMs..."
multipass start gateway server client
# Wait for VMs to be ready
sleep 10
echo "Configuring Gateway VM..."
# Gateway configuration - enable IP forwarding and set up NAT
multipass exec gateway -- sudo bash -c '
# Enable IP forwarding
echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p
# Install iptables-persistent to save rules
apt update
apt install -y iptables-persistent
# Set up NAT rules for forwarding traffic
# Allow forwarding from internal network to external
iptables -t nat -A POSTROUTING -s 192.168.69.0/24 -o enp0s1 -j MASQUERADE
iptables -A FORWARD -i enp0s1 -o enp0s1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i enp0s1 -o enp0s1 -j ACCEPT
# Allow traffic between VMs in the same subnet
iptables -A INPUT -s 192.168.69.0/24 -j ACCEPT
iptables -A FORWARD -s 192.168.69.0/24 -d 192.168.69.0/24 -j ACCEPT
# Save iptables rules
iptables-save > /etc/iptables/rules.v4
echo "Gateway configuration completed"
'
echo "Configuring Server VM..."
# Server configuration - set up Python service
multipass exec server -- sudo bash -c '
# Update package list and install Python3
apt update
apt install -y python3 python3-pip
# Create a simple web service
cat > /home/ubuntu/server.py << EOF
#!/usr/bin/env python3
import http.server
import socketserver
import os
PORT = 8000
class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
response = f"""
<html>
<head><title>Network Lab Server</title></head>
<body>
<h1>Hello from Server!</h1>
<p>Server IP: {os.popen("hostname -I").read().strip()}</p>
<p>You have successfully accessed the server through the gateway!</p>
<p>Request from: {self.client_address[0]}</p>
</body>
</html>
"""
self.wfile.write(response.encode())
with socketserver.TCPServer(("", PORT), MyHTTPRequestHandler) as httpd:
print(f"Server running on port {PORT}")
print(f"Server IP: {os.popen("hostname -I").read().strip()}")
httpd.serve_forever()
EOF
chmod +x /home/ubuntu/server.py
# Create systemd service for auto-start
cat > /etc/systemd/system/webserver.service << EOF
[Unit]
Description=Python Web Server
After=network.target
[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu
ExecStart=/usr/bin/python3 /home/ubuntu/server.py
Restart=always
[Install]
WantedBy=multi-user.target
EOF
systemctl enable webserver.service
systemctl start webserver.service
echo "Server configuration completed"
'
echo "Configuring Client VM..."
# Client configuration
multipass exec client -- sudo bash -c '
# Install curl and network tools for testing
apt update
apt install -y curl traceroute net-tools
echo "Client configuration completed"
'
echo "Network configuration completed!"
echo "You can now test the setup by running:"
echo "multipass exec client -- curl http://$(multipass info server | grep IPv4 | awk '{print $2}'):8000"
#!/bin/bash
echo "========================================="
echo "Network Environment Test Script"
echo "========================================="
echo
echo "1. Testing VMs status:"
multipass list
echo
echo "2. Testing connectivity from Client to Server:"
echo "Client -> Server (HTTP):"
multipass exec client -- curl -s http://192.168.69.23:8000
echo
echo
echo "3. Testing route tracing:"
echo "Traceroute from Client to Server:"
multipass exec client -- traceroute 192.168.69.23
echo
echo "4. Testing Gateway routing configuration:"
echo "Gateway IP forwarding status:"
multipass exec gateway -- sysctl net.ipv4.ip_forward
echo
echo "Gateway iptables NAT rules:"
multipass exec gateway -- sudo iptables -t nat -L POSTROUTING
echo
echo "5. Testing Server service:"
echo "Server processes:"
multipass exec server -- ps aux | grep python
echo
echo "6. Network configuration summary:"
echo "Gateway IP: $(multipass info gateway | grep IPv4 | awk '{print $2}')"
echo "Server IP: $(multipass info server | grep IPv4 | awk '{print $2}')"
echo "Client IP: $(multipass info client | grep IPv4 | awk '{print $2}')"
echo
echo "========================================="
echo "Network Environment Setup Complete!"
echo "========================================="
echo
echo "Test commands you can run:"
echo "multipass exec client -- curl http://192.168.69.23:8000"
echo "multipass exec client -- traceroute 192.168.69.23"
echo "multipass exec gateway -- sudo iptables -L"
echo

以下是根据你的描述整理的技术需求文档,适用于使用三台 Multipass 虚拟机搭建一个小型互联网实验环境:


技术需求文档:小型虚拟网络环境搭建(Gateway-Server-Client架构)

一、项目目标

构建一个基于 Multipass 虚拟机的隔离小型互联网环境,模拟真实网络中网关转发通信的场景。通过设置三台虚拟机(Gateway、Server、Client),实现如下通信流程:

  • Server 提供一个 Python 服务。
  • Client 无法直接访问 Server,必须通过 Gateway 中转访问 Server。
  • 所有网络流量由 Client → Gateway → Server。

二、虚拟机环境说明

使用 Multipass 快速部署 Ubuntu 虚拟机,默认镜像为 Ubuntu 20.04 或更新版本。

通用创建命令示例:

multipass launch --name <vm-name> --cpus 2 --memory 4G --disk 10G

三台虚拟机定义:

角色 名称 功能描述
Gateway gateway 路由转发、NAT 中继
Server server 运行 Python 服务
Client client 访问服务的客户端

三、网络拓扑目标图(逻辑)

[Client]  ──>  [Gateway]  ──>  [Server]
           NAT/路由器     服务端

四、网络配置需求

  1. 关闭 Multipass 默认 NAT 接口或增加自定义桥接接口

    • 需要为虚拟机绑定一个内部网段,例如:192.168.100.0/24
    • 使用 Host-only / macvtap / bridge 模式(具体操作视宿主系统支持情况)
  2. Gateway 网络配置

    • 两块网卡:

      • eth0: 外网接口,用于与宿主或互联网通信(默认 NAT)
      • eth1: 内网接口,与 client/server 通信(自定义桥接)
    • 启用 IP 转发:

      echo 1 > /proc/sys/net/ipv4/ip_forward
    • 设置 NAT 转发规则(使用 iptables):

      iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
      iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
      iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
  3. Server 网络配置

    • 仅连接到内网接口,IP 地址例如 192.168.100.10
    • 不直接访问外网
  4. Client 网络配置

    • 仅连接到内网接口,IP 地址例如 192.168.100.20
    • 默认网关设置为 Gateway 的内网 IP(例如 192.168.100.1
    • 验证是否能访问外网与 server(都经由 gateway)

五、Server 服务部署

  1. 安装 Python3:

    sudo apt update && sudo apt install -y python3
  2. 创建简单 HTTP 服务:

    cd ~
    echo 'Hello from server' > index.html
    python3 -m http.server 8000
  3. 确认 server 上服务运行在 192.168.100.10:8000


六、验证任务

  • 在 client 上运行:

    curl http://192.168.100.10:8000

    应该通过 gateway 成功访问 server 上的 Python 服务。

  • traceroute 验证路径:

    traceroute 192.168.100.10
  • iptables 日志可用于验证流量是否经过 gateway。


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment