- Как настроить сетевой мост (br0) на Ubuntu Linux 14.04 и 16.04 LTS
- Установка bridge-utils
- Создаем сетевой мост на сервере с Ubuntu
- Network bridge
- Contents
- Creating a bridge
- With iproute2
- With bridge-utils
- With netctl
- With systemd-networkd
- With NetworkManager
- Assigning an IP address
- With iproute2
- With NetworkManager
- Tips and tricks
- Wireless interface on a bridge
- Speeding up traffic destinated to the bridge itself
- Troubleshooting
- No networking after bridge configuration
- No networking on hosted servers after bridge configuration
- brctl addif и brctl addbr
- Опции, которые могут потребоваться при работе с сетевыми мостами:
- How To Setup Bridge (br0) Network on Ubuntu Linux 14.04 and 16.04 LTS
- Our sample bridged networking
- Install bridge-utils
- Creating a network bridge on the Ubuntu server
- A note about br0 and DHCP
- Restart the server or networking service
- Verify connectivity
Как настроить сетевой мост (br0) на Ubuntu Linux 14.04 и 16.04 LTS
В данном посте пойдет речь о том, как настроить сетевой мост на сервере с ОС Ubuntu 14.04 LTS или 16.04 LTS.
Сетевой мост — это ничто иное, как простой технический способ соединения с внешней сетью через физический интерфейс. Это полезно при использовании виртуализации LXC/KVM/Xen/Containers и других виртуальных интерфейсов. В этом туториале будет рассказано как можно настроить мост Linux используя bridge-utils (brctl) на сервер с Ubuntu.
Пример сетевого моста:
В этом примере eth0 и eth1 — это физический сетевой интерфейс. eth0 соединяется с LAN и eth1 соединен непосредственно с оборудованием провайдера.
Установка bridge-utils
Введите команду apt-get для установки bridge-utils:
Создаем сетевой мост на сервере с Ubuntu
Редактируем /etc/network/interfaces используя текстовый редактор такой как nano, vi или любой другой любимый Вами редактор, и вводим:
Далее установим eth1 и метим его как br1, вводим:
Устанавливаем eth0 и метим его как br0, вводим:
Заметка про br0 и DHCP
Сохраните и закройте файл.
Перезапускаем сервер или сетевой сервис
Теперь нужно перезагрузить сервер или ввести команду для перезапуска сетевого сервиса:
Если используется Ubuntu 14.04 LTS или более старая версия дистрибутива, введите:
Команда проверки связности
Используем команду ping/ip для того, чтобы убедиться в доступности интерфейсов LAN и WAN:
Теперь можно сконфигурировать XEN/KVM/LXC контейнеры, чтобы использовать br0 и br1 и получить доступ непосредственно к Интернету или внутренней LAN. Таким образом отпадает потребность в установке специальной таблицы маршрутизации или создания iptables, SNAT правил.
Источник
Network bridge
A bridge is a piece of software used to unite two or more network segments. A bridge behaves like a virtual network switch, working transparently (the other machines do not need to know about its existence). Any real devices (e.g. eth0 ) and virtual devices (e.g. tap0 ) can be connected to it.
This article explains how to create a bridge that contains at least an ethernet device. This is useful for things like the bridge mode of QEMU, setting a software based access point, etc.
Contents
Creating a bridge
There are a number of ways to create a bridge.
With iproute2
This section describes the management of a network bridge using the ip tool from the iproute2 package, which is required by the base meta package.
Create a new bridge and change its state to up:
To add an interface (e.g. eth0) into the bridge, its state must be up:
Adding the interface into the bridge is done by setting its master to bridge_name :
To show the existing bridges and associated interfaces, use the bridge utility (also part of iproute2 ). See bridge(8) for details.
This is how to remove an interface from a bridge:
The interface will still be up, so you may also want to bring it down:
To delete a bridge issue the following command:
This will automatically remove all interfaces from the bridge. The slave interfaces will still be up, though, so you may also want to bring them down after.
With bridge-utils
This section describes the management of a network bridge using the legacy brctl tool from the bridge-utils package, which is available in the official repositories. See brctl(8) for full listing of options.
Create a new bridge:
Add a device to a bridge, for example eth0 :
Show current bridges and what interfaces they are connected to:
Set the bridge device up:
Delete a bridge, you need to first set it to down:
With netctl
With systemd-networkd
With NetworkManager
GNOME’s Network settings can create bridges, but currently will not auto-connect to them or slave/attached interfaces. Open Network Settings, add a new interface of type Bridge, add a new bridged connection, and select the MAC address of the device to attach to the bridge.
KDE’s plasma-nm can create bridges. In order to view, create and modify bridge interfaces open the Connections window either by right clicking the Networks applet in the system tray and selecting Configure Network Connections. or from System Settings > Connections. Click the Configuration button in the lower left corner of the module and enable «Show virtual connections». A session restart will be necessary to use the enabled functionality.
nm-connection-editor can create bridges in the same manner as GNOME’s Network settings.
nmcli from networkmanager can create bridges. Creating a bridge with STP disabled (to avoid the bridge being advertised on the network):
Making interface enp30s0 a slave to the bridge:
Setting the existing connection as down (you can get it with nmcli connection show —active ):
Setting the new bridge as up:
If NetworkManager’s default interface for the device you added to the bridge connects automatically, you may want to disable that by clicking the gear next to it in Network Settings, and unchecking «Connect automatically» under «Identity.»
Assigning an IP address
This article or section needs expansion.
When the bridge is fully set up, it can be assigned an IP address:
With iproute2
With NetworkManager
Give it the desired address:
Set up a DNS server (this will also avoid not being able to load any pages after you apply the changes):
Set the IP address to static:
Apply the changes:
Tips and tricks
Wireless interface on a bridge
To add a wireless interface to a bridge, you first have to assign the wireless interface to an access point or start an access point with hostapd. Otherwise the wireless interface will not be added to the bridge.
Speeding up traffic destinated to the bridge itself
In some situations the bridge not only serves as a bridge box, but also talks to other hosts. Packets that arrive on a bridge port and that are destinated to the bridge box itself will by default enter the iptables INPUT chain with the logical bridge port as input device. These packets will be queued twice by the network code, the first time they are queued after they are received by the network device. The second time after the bridge code examined the destination MAC address and determined it was a locally destinated packet and therefore decided to pass the frame up to the higher protocol stack.[1]
The way to let locally destinated packets be queued only once is by brouting them in the BROUTING chain of the broute table. Suppose br0 has an IP address and that br0’s bridge ports do not have an IP address. Using the following rule should make all locally directed traffic be queued only once:
The replies from the bridge will be sent out through the br0 device (assuming your routing table is correct and sends all traffic through br0), so everything keeps working neatly, without the performance loss caused by the packet being queued twice.
The redirect target is needed because the MAC address of the bridge port is not necessarily equal to the MAC address of the bridge device. The packets destinated to the bridge box will have a destination MAC address equal to that of the bridge br0, so that destination address must be changed to that of the bridge port.
Troubleshooting
No networking after bridge configuration
This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.
It may help to remove all IP addresses and routes from the interface (e.g. eth0 ) that was added to the bridge and configure these parameters for the bridge instead.
First of all, make sure there is no dhcpcd instance running for eth0 , otherwise the deleted addresses may be reassigned.
Remove address and route from the eth0 interface:
Now IP address and route for the earlier configured bridge must be set. This is usually done by starting a DHCP client for this interface. Otherwise, consult Network configuration for manual configuration.
No networking on hosted servers after bridge configuration
This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.
Источник
brctl addif и brctl addbr
Прежде всего установим пакет
Добавляем сетевой мост
Интерфейсы (в примере, eth0) можно добавлять в бридж (br0) так:
Их имена можно узнать из вывода ip a (ip addr show). Добавляется обычно 2 интерфейса. В примере один, так требуется делать, например, при настройке моста для системы LXC контейнеризации.
Несколько интерфейсов добавляются в мост в любом порядке
При необходимости так же интерфейс убирается:
Все включенные в сетевой мост интерфейсы работают как одно устройство. Таковым бридж и является выполняя те же функции, что физический коммутатор.
Один интерфейс включается не больше, чем в один бридж.
У самого бриджа нет IP адреса, что делает невозможным подключение к нему извне. Если бриджей несколько можно настроить STP (spanning-tree-protocol), что предотвратит возникновение петель при коммутации.
При базовой конфигурации с одним сетевым мостом это не требуется.
Чтобы изменения сохранялись после перезагрузки нужно внести правки в /etc/network/interfaces
# The loopback network interface
auto lo
iface lo inet loopback
# Set up interfaces manually, avoiding conflicts with, e.g., network manager
iface eth0 inet manual
iface eth1 inet manual
# Bridge setup
iface br0 inet dhcp
bridge_ports eth0 eth1
Затем выполняется ifup br0 чтобы поднять мост и все интерфейсы, в него включенные.
Для статического IP:
# The loopback network interface
auto lo br0
iface lo inet loopback
# Set up interfaces manually, avoiding conflicts with, e.g., network manager
iface eth0 inet manual
iface eth1 inet manual
# Bridge setup
iface br0 inet static
bridge_ports eth0 eth1
address 192.168.1.1
broadcast 192.168.4.255
netmask 255.255.255.0
gateway 192.168.1.1
Поддерживаются регулярные выражения — bridge_ports regex eth*
Опции, которые могут потребоваться при работе с сетевыми мостами:
bridge_stp off — выключает Spanning Tree Protocol
bridge_waitport 0 — нулевая задержка при смене состояния порта
bridge_fd 0 — нулевая задержка при пересылке
Посмотреть информацию по всем сетевым мостам на машине можно так:
Пример добавления моста для LXC
После установки LXC полноценно пакет работать не будет если отсутствует сетевой мост. Добавляется он при этом очень легко.
Сначала нужно посмотреть имя моста:
lxc.network.type = veth
lxc.network.link = lxcbr0
lxc.network.flags = up
lxc.network.hwaddr = 00:16:3e:xx:xx:xx
Затем добавить его
bridge name bridge id STP enabled interfaces
lxcbr0 8000.000000000000 no
brctl addif и добавление интерфейсов обычно не требуется, в /etc/network/interaces для моста прописывается сетевые настройки идентичные существующим для интерфейса, смотрящего во внешнюю сеть.
Источник
How To Setup Bridge (br0) Network on Ubuntu Linux 14.04 and 16.04 LTS
Our sample bridged networking
Fig.01: Sample Ubuntu Bridged Networking Setup For Kvm/Xen/LXC Containers (br0)
Install bridge-utils
Type the following apt-get command to install the bridge-utils:
$ sudo apt-get install bridge-utils
OR
$ sudo apt install bridge-utils
Sample outputs:
Fig.02: Ubuntu Linux install bridge-utils package
Creating a network bridge on the Ubuntu server
Edit /etc/network/interfaces using a text editor such as nano or vi, enter:
$ sudo cp /etc/network/interfaces /etc/network/interfaces.bakup-1-july-2016
$ sudo vi /etc/network/interfaces
Let us setup eth1 and map it to br1, enter (delete or comment out all eth1 entries):
To setup eth0 and map it to br0, enter (delete or comment out all eth1 entries):
A note about br0 and DHCP
DHCP config options:
Save and close the file.
Restart the server or networking service
You need to reboot the server or type the following command to restart the networking service (this may not work on SSH based session):
$ sudo systemctl restart networking
If you are using Ubuntu 14.04 LTS or older not systemd based system, enter:
$ sudo /etc/init.d/restart networking
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Verify connectivity
Use the ping/ip commands to verify that both LAN and WAN interfaces are reachable:
# See br0 and br1
ip a show
# See routing info
ip r
# ping public site
ping -c 2 cyberciti.biz
# ping lan server
ping -c 2 10.0.80.12
Sample outputs:
Fig.03: Verify Bridging Ethernet Connections
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник