Настройка nfs archlinux linux

Настройка nfs archlinux linux

Network File System (NFS) is a distributed file system protocol originally developed by Sun Microsystems in 1984, allowing a user on a client computer to access files over a network in a manner similar to how local storage is accessed.

Contents

Installation

Both client and server only require the installation of the nfs-utils package.

It is highly recommended to use a time synchronization daemon to keep client/server clocks in sync. Without accurate clocks on all nodes, NFS can introduce unwanted delays.

Configuration

Server

Global configuration options are set in /etc/nfs.conf . Users of simple configurations should not need to edit this file.

The NFS server needs a list of exports (see exports(5) for details) which are defined in /etc/exports or /etc/exports.d/*.exports . These shares are relative to the so-called NFS root. A good security practice is to define a NFS root in a discrete directory tree which will keep users limited to that mount point. Bind mounts are used to link the share mount point to the actual directory elsewhere on the filesystem.

Consider this following example wherein:

  1. The NFS root is /srv/nfs .
  2. The export is /srv/nfs/music via a bind mount to the actual target /mnt/music .

To make the bind mount persistent across reboots, add it to fstab:

Add directories to be shared and limit them to a range of addresses via a CIDR or hostname(s) of client machines that will be allowed to mount them in /etc/exports , e.g.:

It should be noted that modifying /etc/exports while the server is running will require a re-export for changes to take effect:

To view the current loaded exports state in more detail, use:

For more information about all available options see exports(5) .

Starting the server

Restricting NFS to interfaces/IPs

By default, starting nfs-server.service will listen for connections on all network interfaces, regardless of /etc/exports . This can be changed by defining which IPs and/or hostnames to listen on.

Restart nfs-server.service to apply the changes immediately.

Firewall configuration

To enable access through a firewall, TCP and UDP ports 111 , 2049 , and 20048 may need to be opened when using the default configuration; use rpcinfo -p to examine the exact ports in use on the server:

When using NFSv4, make sure TCP port 2049 is open. No other port opening should be required:

When using an older NFS version, make sure other ports are open:

To have this configuration load on every system start, edit /etc/iptables/iptables.rules to include the following lines:

The previous commands can be saved by executing:

If using NFSv3 and the above listed static ports for rpc.statd and lockd the following ports may also need to be added to the configuration:

To apply changes, Restart iptables.service .

Enabling NFSv4 idmapping

This article or section needs expansion.

The NFSv4 protocol represents the local system’s UID and GID values on the wire as strings of the form user@domain . The process of translating from UID to string and string to UID is referred to as ID mapping. See nfsidmap(8) for details.

Even though idmapd may be running, it may not be fully enabled. If /sys/module/nfs/parameters/nfs4_disable_idmapping or /sys/module/nfsd/parameters/nfs4_disable_idmapping returns Y on a client/server, enable it by:

Set as module option to make this change permanent, i.e.:

To fully use idmapping, make sure the domain is configured in /etc/idmapd.conf on both the server and the client:

Читайте также:  Synaptics touchpad driver windows 10 64 bit samsung

See [2] for details.

Client

Users intending to use NFS4 with Kerberos need to start and enable nfs-client.target .

Manual mounting

For NFSv3 use this command to show the server’s exported file systems:

For NFSv4 mount the root NFS directory and look around for available mounts:

Then mount omitting the server’s NFS export root:

If mount fails try including the server’s export root (required for Debian/RHEL/SLES, some distributions need -t nfs4 instead of -t nfs ):

Mount using /etc/fstab

Using fstab is useful for a server which is always on, and the NFS shares are available whenever the client boots up. Edit /etc/fstab file, and add an appropriate line reflecting the setup. Again, the server’s NFS export root is omitted.

Some additional mount options to consider:

rsize and wsize The rsize value is the number of bytes used when reading from the server. The wsize value is the number of bytes used when writing to the server. By default, if these options are not specified, the client and server negotiate the largest values they can both support (see nfs(5) for details). After changing these values, it is recommended to test the performance (see #Performance tuning). soft or hard Determines the recovery behaviour of the NFS client after an NFS request times out. If neither option is specified (or if the hard option is specified), NFS requests are retried indefinitely. If the soft option is specified, then the NFS client fails a NFS request after retrans retransmissions have been sent, causing the NFS client to return an error to the calling application.

Mount using /etc/fstab with systemd

Another method is using the x-systemd.automount option which mounts the filesystem upon access:

To make systemd aware of the changes to fstab, reload systemd and restart remote-fs.target [3].

The factual accuracy of this article or section is disputed.

As systemd unit

Create a new .mount file inside /etc/systemd/system , e.g. mnt-myshare.mount . See systemd.mount(5) for details.

What= path to share

Where= path to mount the share

Options= share mounting options

To use mnt-myshare.mount , start the unit and enable it to run on system boot.

automount

To automatically mount a share, one may use the following automount unit:

Disable/stop the mnt-myshare.mount unit, and enable/start mnt-myshare.automount to automount the share when the mount path is being accessed.

Mount using autofs

Using autofs is useful when multiple machines want to connect via NFS; they could both be clients as well as servers. The reason this method is preferable over the earlier one is that if the server is switched off, the client will not throw errors about being unable to find NFS shares. See autofs#NFS network mounts for details.

Tips and tricks

Performance tuning

When using NFS on a network with a significant number of clients one may increase the default NFS threads from 8 to 16 or even a higher, depending on the server/network requirements:

It may be necessary to tune the rsize and wsize mount options to meet the requirements of the network configuration.

In recent linux kernels (>2.6.18) the size of I/O operations allowed by the NFS server (default max block size) varies depending on RAM size, with a maximum of 1M (1048576 bytes), the max block size of the server will be used even if nfs clients requires bigger rsize and wsize . See https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/5/html/5.8_Technical_Notes/Known_Issues-kernel.html It is possible to change the default max block size allowed by the server by writing to the /proc/fs/nfsd/max_block_size before starting nfsd. For example, the following command restores the previous default iosize of 32k:

Читайте также:  Нет значка подключение по локальной сети windows

To make the change permanent, create a systemd-tmpfile:

To mount with the increased rsize and wsize mount options:

Furthermore, despite the violation of NFS protocol, setting async instead of sync or sync,no_wdelay may potentially achieve a significant performance gain especially on spinning disks. Configure exports with this option and then execute exportfs -arv to apply.

Automatic mount handling

This trick is useful for NFS-shares on a wireless network and/or on a network that may be unreliable. If the NFS host becomes unreachable, the NFS share will be unmounted to hopefully prevent system hangs when using the hard mount option [5].

Make sure that the NFS mount points are correctly indicated in fstab:

Create the auto_share script that will be used by cron or systemd/Timers to use ICMP ping to check if the NFS host is reachable:

in the auto_share script above.

Make sure the script is executable.

Next check configure the script to run every X, in the examples below this is every minute.

systemd/Timers

Finally, enable and start auto_share.timer .

Using a NetworkManager dispatcher

NetworkManager can also be configured to run a script on network status change.

The easiest method for mount shares on network status change is to symlink the auto_share script:

However, in that particular case unmounting will happen only after the network connection has already been disabled, which is unclean and may result in effects like freezing of KDE Plasma applets.

The following script safely unmounts the NFS shares before the relevant network connection is disabled by listening for the pre-down and vpn-pre-down events, make the script is executable:

Create a symlink inside /etc/NetworkManager/dispatcher.d/pre-down to catch the pre-down events:

Troubleshooting

There is a dedicated article NFS/Troubleshooting.

Источник

Как настроить сервер NFS и смонтировать общие ресурсы NFS в Linux

Сетевая файловая система (NFS) – это популярный протокол распределенной файловой системы, который позволяет пользователям монтировать удаленные каталоги на своем компьютере. NFS довольно хорошо работает c каталогами, к которым пользователям требуется частый доступ. Практически во всех версиях Linux команды будут одинаковые. Мы рассмотрим как монтировать общий ресурс NFS на примере сервера Ubuntu 18.04.
Пусть компьютеры будут иметь следующие адреса:

Сервер: 192.168.1.5
Клиент: 192.168.1.100

Требуется подключить существующую папку /home и специально созданную папку /var/nfs с сервера к клиенту.

Установка пакетов

Прежде всего, требуется установить необходимые компоненты как на сервере, так и на клиентских компьютерах. На сервере вам потребуется установить пакет nfs-kernel-server , который позволит использовать совместный доступ к вашим каталогам.

На клиентском компьютере вам потребуется установить пакет nfs-common.

Создание общего каталога на сервере

Мы будем монтировать специально созданный на сервере каталог на клиентский компьютер. Создадим каталог nfs.

Теперь отредактируем файл, отвечающий за совместное использование ресурсов NFS

Здесь нужно создать строку для каждого из каталогов, которые должны быть общими и указать с какими компьютерами мы разделяем ресурсы. В нашем примере IP-адрес клиента – 192.168.1.100, поэтому строки должны выглядеть примерно так:

В случае если нужно раздать каталог на все компьютеры подсети вместо 192.168.1.100 нужно указать 192.168.1.0/24

Давайте разберем, что здесь написано.

rw: эта опция позволяет клиентскому компьютеру как читать, так и записывать в данный каталог.
sync: заставляет NFS записывать изменения на диск перед ответом, что приводит к более стабильной и согласованной среде. Это связано прежде всего с тем, что ответ повторяет фактическое состояние удаленного тома.
no_subtree_check: эта опция предотвращает проверку поддеревьев. Сервер при каждом запросе проверяет, действительно ли файл все еще доступен в экспортируемом дереве. Отключение проверки уменьшает безопасность, но увеличивает скорость передачи данных.
no_root_squash: по умолчанию NFS переводит запросы от пользователя root на клиентском компьютере в непривилегированного на сервере. Это параметр безопасности который не позволяет учетной записи root на клиенте использовать файловую систему сервера в качестве root.

Читайте также:  Mac os sidecar compatibility

После того, как необходимые изменения внесены и сохранены, выполним команду:

и запустим службу NFS

Данная команда сделает ваши ресурсы доступными для клиентов, которых вы настроили. Теперь перейдем к следующему шагу.

Создание точек монтирования и монтирование удаленных общих ресурсов на клиентском компьютере

Сперва создадим точки монтирования удаленных ресурсов.

Автоматическое монтирование производится через fstab

Допишем в конец файла

Если вам больше не требуется монтировать удаленный каталог в вашей системе, вы можете легко размонтировать его используя следующие команды:

NFS предлагает простой и быстрый механизм доступа к удаленным системам по сети. Однако протокол является не зашифрованным. Если вы намерены использовать это в производственной среде, рекомендуется рассмотреть возможность запуска NFS через SSH или VPN-соединение.

Источник

NFS-сервер с нуля

Здравствуйте. Полнейший нуб с сетевыми делами. Неделями перевариваю инструкцию английской вики по настройке NFS-сервера, а времени на изыски мало, поэтому прошу помочь собрать требуемую конфигурацию.

Есть один ноут с арчем, хочу сделать из него NFS-сервер для раздачи файлов. К ноуту подключается 5 компов с форточками через свич, особой проверки на ip-машин не надо, даю полный доступ тому что подключено кабелем. Как это проще всего реализовать? Какие программы установить, какие файлы создать.

Другой момент: клиенты на сколько я понимаю подключатся к nfs по ip сервера. Как ноуту в таком случае присвоить статический адрес?

Прошу простить за наглость, но мне требуются готовые настройки, а не отсылка к мануалам. Заранее благодарю за помощь и понимание, если таковые будут.

Я что-то проспал и в форточках появился встроенный nfs клиент?
# 7 лет, 1 месяц назад (отредактировано 7 лет, 1 месяц назад)

domov0y
Я что-то проспал и в форточках появился встроенный nfs клиент?

NFS в винде — это гемор. Поставьте SAMBA и никаких проблем не будет + появится возможность разграничения доступа, так как NFS не поддерживает разграничения. разграничения не интересуют, думал о скорости передачи данных, слышал что NFS быстрее Samba
# 7 лет, 1 месяц назад (отредактировано 7 лет, 1 месяц назад)

так а какие проблемы в настройке nfs-сервера ?
если никаких сложных настроек не нужно, то помимо запуска необходимых служб там единственное что надо это внести изменения в файл /etc/exports.
вот например мой /etc/exports позволяющий подключатся к серверу из любой точки сети 192.168.4.0 и записывать на него информацию
# 7 лет, 1 месяц назад (отредактировано 7 лет, 1 месяц назад)

red
так а какие проблемы в настройке nfs-сервера ?

z-vladimir
После нескольких лет непрерывной работы у меня совсем недавно NFS-сервер перестал запускаться.

ага, было такое когда прилетело обновление на новую версию 1.3, но там вроде как всё просто решилось(по крайней мере в моём случае), в логе обновлений было написано:

в общем решилось банальным запуском nfs-server.service

z-vladimir
Статический ip для сервера — другой вопрос. Если все подключены через свич, а не роутер я не до конца понимаю, как же все организовано. Как подсетка организована?

Знаете очень тяжелый вопрос для меня — это сетевой вопрос. Свитч неуправляемый D-LINK DES-1008D , а значит все настройки должны быть внутри компов и ноутов, надеялся обойтись без покупки роутера. Ума не приложу как настроить ноут чтобы его видели остальные компы. В инструкциях по форточкам говорится, чтобы ip-адреса были одного диапазона и NetBios через TCP/IP, как в арче такое сделать, к сожалению, не знаю.

Другой вопрос: будет ли прирост скорости по сети через неуправляемый свич, где клиенты будут идти на винде? Если нет, то лучше с самбу буду добивать в таком случае

смог подключить пока линуксы через D-LINK DES-1008D : надо было задать адрес серверу командой

имя интерфейса брал: ip link
ip-адрес — ставил из одного диапазона

настройка /etc/exports как писали выше.
теперь буду пытаться подключить винду к NFS-серверу

© 2006-2021, Русскоязычное сообщество Arch Linux.
Название и логотип Arch Linux ™ являются признанными торговыми марками.
Linux ® — зарегистрированная торговая марка Linus Torvalds и LMI.

Источник

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