What is local host in linux

How to Setup Local DNS Using /etc/hosts File in Linux

DNS (Domain Name System or Service) is a hierarchical decentralized naming system/service that translates domain names into IP addresses on the Internet or a private network and a server that provides such a service is called a DNS server.

This article explains, how to setup a local DNS using the hosts file (/etc/hosts) in Linux systems for local domain resolution or testing the website before taking live.

For example, you may want to test a website locally with a custom domain name before going live publicly by modifying the /etc/hosts file on your local system to point the domain name to the IP address of the local DNS server you configured.

The /etc/hosts is an operating system file that translate hostnames or domain names to IP addresses. This is useful for testing websites changes or the SSL setup before taking a website publicly live.

Attention: This method will only work if the hosts have a static IP address. Therefore ensure that you have set static IP addresses for your Linux hosts or nodes running other operating systems.

For the purpose of this article, we will be using the following domain, hostnames and IP addresses (use values that apply to your local setting).

Understanding Name Service Switch in Linux

Before moving any further, you should understand a few things about another important file that is /etc/nsswitch.conf. It provides Name Service Switch functionality which controls the order in which services are queried for name service lookups.

The configuration is based on order; if files is before dns it means the system will query the /etc/hosts file before checking DNS for name service requests. But if DNS is before files then the domain lookup process will consult DNS first before any other appropriate services or files.

In this scenario, we want to query the “files” service. To check the order, type.

Check Name Service Switch

Configure DNS Locally Using /etc/hosts File in Linux

Now open the /etc/hosts file using your editor of choice as follows

Then add the lines below to the end of the file as shown in the screen shot below.

Next, test if everything is working well as expected, using the ping command from Host 1, you can ping Host 2 using it domain name like so.

Ping Domain Locally

On the Host 2, we have setup Apache HTTP server. So we can also test if the name translation service is working as follows by going to URL http://centos.tecmint.lan.

Check Domain Locally

Important: To use the domain names on any host on the network, you must configure the above settings in its /etc/hosts file.

What does this mean, in the above example, we only configured the hosts file of Host 1 and we can only use the domain names on it. To use the same names on Host 2, we have to add the addresses and names to its hosts file as well.

Читайте также:  Аппаратная платформа для windows

Lastly, you should use host command or nslookup command to test if the name translation service is actually working, these commands only query DNS and overlook any configurations in /etc/hosts and /etc/nsswitch.conf files.

You may also like to read these following related articles.

That’s it! Do share any additional thoughts or questions about this topic with us, via the comment section below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Файл hosts в Linux

Система доменных имен DNS используется для определения, какой IP принадлежит к нужному домену в сети интернет. Когда какой-либо программе понадобится обратиться к сайту по его доменному имени, операционная система отправляет к DNS-серверу запрос, чтобы узнать, по какому IP ей дальше передавать пакеты. Но так происходит не всегда. Например, когда мы обращаемся к домену localhost, то всегда запрос отправляется нашему локальному компьютеру.

Всему причиной файл hosts. Если вы раньше пользовались Windows, то, наверное, уже слышали о таком файле. Там чаще всего он использовался для того, чтобы быстро заблокировать доступ к какому-либо ресурсу. Но применение его гораздо шире. В этой статье мы рассмотрим, как настроить файл hosts в Linux, а также какие возможности он нам предоставляет.

Разрешение доменных имён в Linux

Прежде чем мы перейдём к самому файлу hosts, нужно разобраться, как происходит поиск IP-адреса для доменного имени в Linux. Я говорил, что операционная система сразу же отправляет запрос DNS-серверу, но это не совсем так. Существует определённый порядок поиска, согласно которому он выполняется. Этот порядок установлен в конфигурационном файле /etc/nsswitch.conf

Здесь нас интересует строчка hosts. В ней в порядке очередности записаны службы, которые используются для поиска IP-адреса для доменного имени. Пункт files означает использование файла /etc/hosts, а dns — сервиса доменных имён интернета. Если files расположена перед hosts, это означает, что сначала система попытается найти домен в /etc/hosts, а уже потом по DNS. По умолчанию дело обстоит именно так.

Настройка файла hosts в Linux

Нужный нам файл находится в директории /etc/. Для его открытия можно использовать любой текстовый редактор как в командной строке, так и в графическом интерфейсе, только открывать его нужно с правами суперпользователя. Например, с помощью vim:

sudo vi /etc/hosts

sudo gedit /etc/hosts

Синтаксис файла довольно простой. В нём находится несколько строчек с доменными именами и IP-адресами, которые нужно для них использовать. Каждая из них выглядит вот так:

ip_адрес домен алиас

Обычно первая же строчка создаёт правило для перенаправления всех запросов к домену localhost на локальный IP-адрес — 127.0.0.1:

Также в этом файле по умолчанию размещаются перенаправления для имени вашего компьютера и для IPv6-адресов. Вы можете создать свои настройки для любого нужного домена. Для этого нужно добавить строчку в конец файла. Например, направим все запросы к домену losst.ru на ip 127.0.0.1:

Читайте также:  Как увеличить размер системного диска windows без потери данных

Обратите внимание, что здесь указывается только домен, без протокола. Префикс http или https указывать не нужно, иначе ничего работать не будет. А вот для поддомена www нужно создавать отдельную запись или записывать его в виде алиаса. Например:

127.0.0.1 losst.ru www.losst.ru

Теперь при запросе домена losst.ru будет открываться наш локальный IP. Чтобы вернуть доступ к оригинальному ресурсу, достаточно убрать добавленную строчку. Но вы можете использовать не только локальный адрес, но и любой другой. Это очень удобно, если вы только зарегистрировали домен и доменная зона ещё не успела обновиться, а вы уже хотите работать с новым сайтом. Просто добавьте данные в /etc/hosts и работайте как обычно.

Выводы

В этой небольшой статье мы разобрали, как выполняется настройка DNS через файл hosts Linux. Как видите, с его помощью вы можете блокировать доступ к нежелательным ресурсам, например, к которым программы не должны получить доступ, а также использовать его в работе веб-мастера.

Источник

Linux hostname command

On Unix-like operating systems, the hostname command shows or sets the system hostname.

This page covers the GNU/Linux version of hostname.

Description

hostname is used to display the system’s DNS name, and to display or set its hostname or NIS (Network Information Services) domain name.

When called without any arguments, hostname displays the name of the system as returned by the gethostname function.

When called with one argument or with the —file option, hostname sets the system’s hostname using the sethostname function. Only the superuser can set the hostname.

The hostname is usually set once at system startup in the script /etc/init.d/hostname.sh normally by reading the contents of a file which contains the hostname, e.g., /etc/hostname.

Syntax

Options

-a, —alias Display the alias name of the host (if used). This option is deprecated and should not be used anymore.
-A, —all-fqdns Displays every FQDN of the machine. This option enumerates all configured network addresses on all configured network interfaces, and translates them to DNS domain names. Addresses that cannot be translated (i.e., because they do not have an appropriate reverse DNS entry) are skipped. Note that different addresses may resolve to the same name, therefore the output may contain duplicate entries. Do not make any assumptions about the order of the output.
-b, —boot Always set a hostname; this allows the file specified by -F to be non-existant or empty, in which case the default hostname localhost will be used if none is yet set.
-d, —domain Display the name of the DNS domain. Don’t use the command domainname to get the DNS domain name because it shows the NIS domain name and not the DNS domain name. Use dnsdomainname instead. See the warnings in the FQDN section, and avoid using this option if at all possible.
-f, —fqdn, —long Display the FQDN (fully qualified domain name). A FQDN consists of a short hostname and the DNS domain name. Unless you are using BIND (Berkeley Internet Name Domain) or NIS for host lookups, you can change the FQDN and the DNS domain name (which is part of the FQDN) in the /etc/hosts file. See the warnings in the FQDN section, and avoid using this option if at all possible; use hostname —all-fqdns instead.
-F, —file file name Read the hostname from the specified file. Comments (lines starting with a `#‘) are ignored.
-i, —ip-address Display the network address(es) of the hostname. Note that this works only if the hostname can be resolved. Avoid using this option if at all possible; use hostname —all-ip-addresses instead.
-I,
—all-ip-addresses
Display all network addresses of the host. This option enumerates all configured addresses on all network interfaces. The loopback interface and IPv6 link-local addresses are omitted. Contrary to option -i, this option does not depend on name resolution. Do not make any assumptions about the order of the output.
-s, —short Display the short hostname. This is the hostname cut at the first dot.
-v, —verbose Be verbose with all output.
-V, —version Print version information on standard output and exit successfully.
-y, —yp, —nis Display the NIS domain name. If a parameter is given (or —file name ) then root (the superuser) can also set a new NIS domain.
-h, —help Print a help message and exit.
Читайте также:  All about windows app studio

The FQDN

The FQDN (fully qualified domain name) of the system is the name that the resolver returns for the hostname, such as mysubdomain.example.com. It is usually the hostname followed by the DNS domain name (the part after the first dot). You can check the FQDN using hostname —fqdn or the domain name using dnsdomainname.

You cannot change the FQDN with hostname or dnsdomainname.

The recommended method of setting the FQDN is to make the hostname be an alias for the fully qualified name using /etc/hosts, DNS, or NIS. For example, if the hostname was «mysubdomain«, one might have a line in /etc/hosts which reads:

Technically: The FQDN is the name getaddrinfo returns for the hostname returned by gethostname. The DNS domain name is the part after the first dot.

Therefore it depends on the configuration of the resolver (usually in /etc/host.conf) how you can change it. Usually, the hosts file is parsed before DNS or NIS, so it is most common to change the FQDN in /etc/hosts.

If a machine has multiple network interfaces/addresses or is used in a mobile environment, then it may either have multiple FQDNs/domain names or none at all. Therefore avoid using hostname —fqdn, hostname —domain and dnsdomainname.

hostname —ip-address is subject to the same limitations so it should be avoided as well.

Files

/etc/hostname Historically this file was supposed to only contain the hostname and not the full canonical FQDN. Nowadays most software can cope with a full FQDN here. This file is read at boot time by the system initialization scripts to set the hostname.
/etc/hosts Usually, this is where one sets the domain name by aliasing the hostname to the FQDN.

Examples

Displays the system hostname.

hostid — Print the numeric identifier for the current host.
uname — Print information about the current system.

Источник

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