Linux hosts несколько ip адресов

Assign multiple IPs to 1 Entry in hosts file

I have a web sever that connects to an internal database through a VPN. There are 2 IPs (primary and secondary) to the database from the web server. How can I setup my /etc/hosts file so that if the primary IP is not available then the secondary IP will be used? Would this work for my hosts file?

141.131.286.1 abc.efg.datastore.com #primary 141.131.286.237 abc.efg.datastore.com #secondary 

As an alternative and corret solution, install a local dns server. For example the easy-peasy to configure dnsmasq thekelleys.org.uk/dnsmasq/doc.html

9 Answers 9

The hosts file does not provide such mechanism. If you list two IPs for the same name, only the first one will be used. So, there is no such thing as primary and secondary IPs.

Also, the hosts file does not handle URLs. It just handles names like the ones provided in the question. A URL contains complete path and protocol such as http://host/path/to/resource .

This is not true, at least not blanketly. If the hosts file is used and has multiple entries, every resolver I have seen returns all of them to the program, just as it does when a DNS server returns multiple A or AAAA records. What the program does varies — some use only the first entry, some do more complicated things that might or might not match what the user would like.

You can’t provide resilience or round robin load balancing via the /etc/hosts file — it is not designed for that purpose.

Instead, your options are . (in no particular order)

  1. Configure your network properly, so that routes change when a link is dropped
  2. Use DNS round-robin load balancing (not A Good Idea TM ) using a managed service (eg. loaddns.com or dnsmadeeasy.com etc.)
  3. Use a local L3 load balancer for the outbound traffic (HAProxy?) with the back-ends defined as necessary
  4. Build the resilience into your web application itself

Another option could be to use netcat or another software to forward the connection to an IP. Then change the forward if one IP is lost.

@anttiR DNS RR alone has no resilience, but used via a managed DNS service provider it does. I’ve edited my answers and given some examples to be clearer.

I doubt it would work great with database. They have the tendency to fetch one IP and stick to it. An internet website on the other hand would work great.

That would depend on the resolver of the host machine. If the DNS resolver is set to be a non-caching service — or polls the DNS registrars DB directly, then it would work. But like I said, its not a good idea, its just an idea.

Читайте также:  Мой ip linux terminal

/etc/hosts doesn’t support round robin but you can write a simple bash script to sed replace an entry tagged with a #RoundRobin comment (or any other tag you wish to use, just reflect it in the grep line in the script).

#!/bin/bash fqdnips=( $(nslookup sub.domain.com|grep Address:|awk -F\ '< print $2 >'|grep -v '#') ) new=`printf "$"` old=`grep "#RoundRobin" /etc/hosts|awk -F\ '< print $1 >'` sed -i "s/$old/$new/g" /etc/hosts 

The above script grabs the output of nslookup for sub.domain.com and stores it in an array. It then prints the top most value to $new and grabs the existing value for tag #RoundRobin assigned in /etc/hosts . lastly, it performs a sed replace

/etc/hosts file entry would look like this

127.0.0.1 localhost ::1 localhost 11.12.13.14 sub.domain.com #RoundRobin 

Lastly, place this script in the root’s crontab to run every hour or so and you’ll now have an /etc/host round-robin.

This is particularly useful if you have a coded page that is pulling some data from an API and the DNS lookup for the API server is causing a lot of hang time in the page’s script execution. resulting in high cpu consumption for what would otherwise appear to be a simple page. To avoid the costly DNS lookup (particularly if your site is doing hundreds of them per minute do to heavy traffic), you should use /etc/hosts to resolve the FQDN of the remote API server. This will dramatically reduce the CPU usage for pulling the API data and generating the page.

Источник

Назначить несколько IP-адресов для одной записи в файле hosts

У меня есть веб-сервер, который подключается к внутренней базе данных через VPN. В базе данных есть 2 IP-адреса (основной и дополнительный) с веб-сервера. Как я могу настроить свой файл / etc / hosts так, чтобы, если основной IP-адрес был недоступен, использовался дополнительный IP-адрес?

Будет ли это работать для моего файла хостов?

141.131.286.1 abc.efg.datastore.com #primary 141.131.286.237 abc.efg.datastore.com #secondary 

Файл hosts не предоставляет такой механизм. Если вы укажете два IP-адреса для одного и того же имени, будет использоваться только первый. Таким образом, не существует такой вещи, как первичные и вторичные IP-адреса.

Кроме того, файл hosts не обрабатывает URL-адреса. Он просто обрабатывает имена, подобные тем, которые указаны в вопросе. URL содержит полный путь и протокол, например http://host/path/to/resource .

Отредактированный заголовок и вопрос об именах в OPs, чтобы избежать путаницы относительно URL / хостов.

Вы не можете обеспечить устойчивость или циклическую балансировку нагрузки через /etc/hosts файл — он не предназначен для этой цели.

Вместо этого ваши варианты . (без определенного порядка)

  1. Правильно настройте свою сеть, чтобы при удалении ссылки маршруты изменялись
  2. Использовать циклическое распределение нагрузки DNS (не A Good Idea TM ) с использованием управляемой службы (например, loaddns.com или dnsmadeeasy.com и т. Д.)
  3. Используйте локальный балансировщик нагрузки L3 для исходящего трафика (HAProxy?) С серверными областями, определенными как необходимые
  4. Внедрите устойчивость в свое веб-приложение

Циклическая балансировка нагрузки DNS обычно не является устойчивой. Один выбран, а другие не пробовали.

Другим вариантом может быть использование netcat или другого программного обеспечения для пересылки соединения по IP. Затем измените переадресацию, если один IP потерян.

@anttiR DNS RR один не имеет устойчивости, но используется через управляемого поставщика услуг DNS. Я отредактировал свои ответы и привел несколько примеров, которые будут понятнее.

Читайте также:  Linux windows tiling manager

Я сомневаюсь, что это будет прекрасно работать с базой данных. Они имеют тенденцию получать один IP и придерживаться его. Интернет-сайт, с другой стороны, будет отлично работать.

Это будет зависеть от решателя хост-машины. Если DNS-преобразователь настроен как служба без кэширования или опрашивает базу данных DNS-регистраторов напрямую, он будет работать. Но, как я уже сказал, это не очень хорошая идея , это просто идея .

/ etc / hosts не поддерживает циклический перебор, но вы можете написать простой скрипт bash, который заменяет запись, помеченную комментарием #RoundRobin (или любым другим тегом, который вы хотите использовать, просто отразите его в строке grep в сценарии) ,

#!/bin/bash fqdnips=( $(nslookup sub.domain.com|grep Address:|awk -F\ '< print $2 >'|grep -v '#') ) new=`printf "$"` old=`grep "#RoundRobin" /etc/hosts|awk -F\ '< print $1 >'` sed -i "s/$old/$new/g" /etc/hosts 

Приведенный выше скрипт получает вывод nslookup для sub.domain.com и сохраняет его в массиве. Затем он печатает самое верхнее значение в $ new и извлекает существующее значение для тега #RoundRobin, назначенного в / etc / hosts . и, наконец, выполняет sed-замену

Запись файла / etc / hosts будет выглядеть так

127.0.0.1 localhost ::1 localhost 11.12.13.14 sub.domain.com #RoundRobin 

Наконец, поместите этот скрипт в crontab для запуска каждый час или около того, и теперь у вас будет / etc / host round-robin.

Это особенно полезно, если у вас есть закодированная страница, которая извлекает некоторые данные из API, и поиск DNS для сервера API вызывает много времени зависания при выполнении скрипта страницы . что приводит к высокому потреблению ЦП для того, что в противном случае кажется простой страницей. Чтобы избежать дорогостоящего поиска DNS (особенно если ваш сайт выполняет сотни из них в минуту при интенсивном трафике), вы должны использовать / etc / hosts для разрешения полного доменного имени удаленного сервера API. Это значительно сократит использование ЦП для извлечения данных API и создания страницы.

Источник

Hosts file: Is it incorrect to have the same IP address on multiple lines?

However, I don’t like this method because you can’t easily comment out certain aliases or add comments to particular aliases, like this:

 a.b.c.d foo.mydevsite.com # myDevSite on box 1 # a.b.c.d foo.myOtherSite.com # myOtherSite on box 1 a.b.c.d ubuntuBox e.f.g.h foo.myOtherSite.com # myOtherSite testing environment 

3 Answers 3

I found this thread that discusses doing something along these lines. The thread is pretty adamant about not having multiple lines line the /etc/hosts file.

No, it will not. The resolvers stop at the first resolution. Having something like:

 127.0.0.1 localhost.localdomain localhost 127.0.0.1 somenode.somedom.com somenode 

Will not do what you are talking about. BUT having:

 127.0.0.1 somenode.somedom.com somenode 127.0.0.1 localhost.localdomain localhost 

Will cause all kinds of havoc. Including forwarding.

I would generally not do what you’re attempting. If you need more evidence the man page even says not to do this:

This manual page describes the format of the /etc/hosts file. This file is a simple text file that associates IP addresses with hostnames, one line per IP address. For each host a single line should be present with the following information:

 IP_address canonical_hostname [aliases. ] 

All this being said, if your hostnames are FQDN and they don’t overlap then you’re probably safe to do what you’re doing. Just keep in mind that if there is any overlap such as what was mentioned in the thread above, then you may run into resolving issues.

Читайте также:  Linux забыли пароль root

Источник

Is it possible to give two IP addresses for the same host name?

It’s not really possible as in this specific example. Your hosts file essentially forms part of your system’s ability to map a hostname into an IP address. So when your system wants to know the IP address of «example», it’ll get a single IP address in reply. The hosts file allows no way of distinguishing different «record types» for its resolution. So for hostname to IP address mapping, you only get one IP address per hostname (but multiple hostnames could resolve to the same IP address, which is the opposite).

Depending on what you’re doing, might it be possible to use an external DNS service like dyndns.org to map a constant hostname, that will work on either network, to your IP address?

Strictly, the above answer is incorrect.

In older code, using gethostbyname() would indeed return only one result.

In newer code, using getaddrinfo() will return all results, and the /etc/hosts file in the question will work as wanted.

You must log in to answer this question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

Ubuntu and the circle of friends logo are trade marks of Canonical Limited and are used under licence.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Is it possible to use multiple IP addresses for the same host name in a linux hosts file?

The scenario is I have a machine that can be accessed both locally (when I am in the same network as the machine) and publicly (when I am on any external network). I want my hosts file to look something like this:

10.11.82.40 master.parallel.edu master 123.90.132.98 master.parallel.edu master 

So that the system will first try the first IP address, and if that doesn’t work, try the next one. Is this possible and advisable?

2 Answers 2

Normally IP adress resolving is done via dedicated name services like dnsmasq, bind etc.

The local hosts file /etc/hosts is generally only used if you have a small internal network — listing all internal hosts and their respectives ip addresses; otherwise it should just contain your server’s local name (and localhost).

One solution to your question could be to use your server’s name in different subdomains, e.g. master.exernal.example.com and master.internal.example.com ; now to address master from the external network you have to make external.example.com your primary search domain in /etc/resolv.conf :

# /etc/resolv.conf at external host search external.example.com example.com nameserver ns.example.com # /etc/resolv.conf at internal host search internal.example.com example.com nameserver ns.example.com 

(asssuming you have a nameserver at ns.example.com)

In each zone file for .external. and .internal.example.com the hostname points to the respective ip address

# zonefile external network $ORIGIN external.example.com. master IN A 123.90.132.98 # zonefile internal network $ORIGIN internal.example.com. master IN A 10.11.82.40 

Источник

Оцените статью
Adblock
detector