Создание и настройка виртуальных сетевых интерфейсов в Linux
1. Введение
Знаете ли вы, что можете присвоить более чем один IP-адрес физическому сетевому интерфейсу? Эта техника очень полезна, например при работе с Apache и виртуальными хостами, так как позволяет получить доступ к одному и тому же серверу Apache с двух разных IP-адресов.
2. Временный виртуальный сетевой интерфейс
Процесс создания виртуального сетевого интерфейса в Linux не занимает много времени. Он включает один запуск команды ifconfig.
Приведенная выше команда создает виртуальный сетевой интерфейс, базирующийся на оригинальном физическом сетевом интерфейсе eth0. Самое важное условие для создания виртуального сетевого интерфейса — должен существовать физический сетевой интерфейс, в нашем случае eth0. Ниже приведен полный пример:
Теперь мы можем настроить новый виртуальный интерфейс на базе eth0. После выполнения команды ifconfig новый виртуальный интерфейс готов к немедленному использованию.
2.1. Отключение виртуального сетевого интерфейса
Для отключения нашего, созданного ранее, временного сетевого интерфейса мы можем также использовать команду ifconfig с флагом down.
3. Присвоение виртуальному интерфейсу постоянного адреса
Описанные выше настройки не сохраняются после перезагрузки. Если вы хотите, чтобы виртуальный сетевой интерфейс работал постоянно, необходимо модифицировать конфигурационные файлы в соответствии с требованиями вашего дистрибутива Linux. Ниже описан этот процесс для самых распространенных дистрибутивов:
3.1. Debian / Ubuntu
3.1.1. Статический адрес
В Debian или Ubuntu вам необходимо отредактировать файл /etc/network/interfaces, добавив в него следующие строки:
3.1.2. Dhcp
Возможно также использовать витруальный сетевой интерфейс с DHCP. В этом случае вам необходимо добавить в /etc/network/interfaces следующую строку:
Для того, чтобы изменения вступили в силу, необходимо перезапустить сеть:
3.2. Redhat / Fedora / CentOS
3.2.1. Статический адрес
В Redhat, Fedora или CentOS Linux директория, отвечающая за присвоение постоянных IP-адресов — это /etc/sysconfig/network-scripts. В этой директории необходимо создать файл, соответствующий вашему новому виртуальному интерфейсу. В нашем случае этот файл будет называться ifcfg-eth0:0. Создайте этот новый файл и вставьте в него приведенные ниже строки. После перезагрузки адрес будет присвоен виртуальному интерфейсу на постоянной основе.
3.2.2. Dhcp
Когда закончите, перезапустите ваши интерфейсы:
4. Заключение
Раньше один физический сервер обслуживал один веб-сайт. Сегодня такой способ хостинга уже не является жизнеспособным, поэтому способность операционной системы создавать виртуальные сетевые интерфейсы действительно необходима.
Configuring virtual network interfaces in Linux
Did you know that you can assign more that one IP address to a single physical network interface? This technique is quite useful, for example when working with Apache and virtual hosts, as it allows you to access same Apache server by using two different IP addresses.
The process of creating a virtual network interface in Linux is a quite simple matter. It involves a single execution of the ifconfig command.
The above command will create a new virtual network interface based on original eth0 physical interface. The only most important condition for creating the virtual network interface is the physical network interface, as in our case eth0 must exists. The whole example is shown below:
At this point we can configure a new virtual interface based on eth0. Once you execute the ifconfig command the new virtual interface will be immediately ready to use.
Disable virtual network interface
To disable our temporary network interface created earlier we can use the ifconfig command again but with a down flag.
Virtual address permanent assignment
The above configuration would not last after reboot. If you wish the virtual network interface to be permanent you would need to modify config files relevant to your particular Linux distribution. Below, you can find information describing this procedure for the major Linux distributions:
Debian / Ubuntu
Static
For Debian or Ubuntu Linux you need to edit /etc/network/interfaces file with your favorite text editor and add the following lines:
It is also possible to use virtual network interface with DHCP. In that case, you will need to add to your /etc/network/interfaces the following line.
To apply your change restart the network with:
Redhat / Fedora / CentOS
Static
For Redhat, Fedora or CentOS Linux the directory responsible for permanent IP address assignment is /etc/sysconfig/network-scripts. In this directory you need to create a file corresponding to your new virtual interface. In our case, that will be a file called: ifcfg-eth0:0 . Create this new file and insert following lines to make your virtual address assignment permanent after reboot:
Once ready restart your interfaces with:
Conclusion
In the old days one physical server served a single website. This is no longer a viable option for hosting websites today so ability of an operating system to create virtual network interface is really a must.
Centos virtual interfaces linux
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Are you new to LinuxQuestions.org? Visit the following links:
Site Howto | Site FAQ | Sitemap | Register Now
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Introduction to Linux — A Hands on Guide This guide was created as an overview of the Linux Operating System, geared toward new users as an exploration tour and getting started guide, with exercises at the end of each chapter. For more advanced trainees it can be a desktop reference, and a collection of the base knowledge needed to proceed with system and network administration. This book contains many real life examples derived from the author’s experience as a Linux system and network administrator, trainer and consultant. They hope these examples will help you to get a better understanding of the Linux system and that you feel encouraged to try out things on your own. How To Configure a Virtual Network Interface on RHEL 8 / CentOS 8There are plenty of reasons why you’d need to set up virtual network interfaces on a RHEL 8 / CentOS 8 server or workstation. The process has changed a bit since RHEL 7, but it’s still fairly straightforward. In this tutorial you will learn:
Software Requirements and Conventions Used
How to Locate Your Network InterfacesBefore you can start modifying your network interfaces to create a virtual one, you’re going to need to find out exactly what they’re called. Since RHEL switched to systemd , interface names aren’t as simple as they once were. Run ip a to get a full read out of the interfaces on your system. The one you’re connected to your network with will have a local IP address listed next to inet . How to Edit Your Main Network ConfigurationNow that you know which interface you’re looking to work with, you’ll need to modify its configuration file to set up a static IP and make everything work. Open your configuration at /etc/sysconfig/network-scripts/ifcfg-eth0 . Replace eth0 with the actual name of your interface. First, make any changes that you want to the file, like disabling IP6 support, if you don’t want it. Then, change BOOTPROTO to static . At the bottom of the file, add entries for IPADDR , NETMASK , GATEWAY , and DNS . Configure them to match your network. Save your configuration, and exit. How to Duplicate Your Network ConfigurationYou’re going to use that original configuration that you just modified as the template for your new virtual networks. cd into the network-scripts directory to make this easier. Then, copy the original to create two virtual network configurations. How to Create The Virtual Interface ConfgOpen up ifcfg-eth0:0 to modify the NAME and DEVICE attributes to match eth0:0 . Of course, use your actual device’s interface in place of eth0 here too. Do the same with ifcfg-eth0:1 , this time filling in eth0:1 . For this one, you’ll need to change the IPADDR value too. Use a different IP that isn’t used on your network. When you’re ready, and everything looks correct, restart your computer. You can try restarting the NetworkManager service, but it has a tendency to be uncooperative. After your computer comes back up, run ip a again. You should see your virtual address this time, complete with the IP address that you set for it. If you would like to test that your interface is working, you can send it a ping from another computer on your network. ConclusionThere you have it! You can create multiple virtual network interfaces as you need. They’ll remain active as long as your configurations remain in place. |