- Как смонтировать общий ресурс NFS в Linux
- Установка клиентских пакетов NFS
- Монтирование файловых систем NFS вручную
- Автоматическое монтирование файловых систем NFS с помощью /etc/fstab
- Размонтирование файловых систем NFS
- Выводы
- Linux mount all nfs
- Contents
- Installation
- Configuration
- Server
- Starting the server
- Restricting NFS to interfaces/IPs
- Firewall configuration
- Enabling NFSv4 idmapping
- Client
- Manual mounting
- Mount using /etc/fstab
- Mount using /etc/fstab with systemd
- As systemd unit
- Mount using autofs
- Tips and tricks
- Performance tuning
- Automatic mount handling
- systemd/Timers
- Using a NetworkManager dispatcher
- Troubleshooting
Как смонтировать общий ресурс NFS в Linux
Сетевая файловая система (NFS) — это протокол распределенной файловой системы, который позволяет вам обмениваться удаленными каталогами по сети. С помощью NFS вы можете монтировать удаленные каталоги в своей системе и работать с удаленными файлами, как если бы они были локальными файлами.
В операционных системах Linux и UNIX вы можете использовать команду mount для монтирования общего каталога NFS в определенной точке монтирования в локальном дереве каталогов.
В этом руководстве мы покажем вам, как вручную и автоматически смонтировать общий ресурс NFS на машинах Linux.
Установка клиентских пакетов NFS
Чтобы смонтировать общий ресурс NFS в системе Linux, сначала необходимо установить клиентский пакет NFS. Название пакета отличается в разных дистрибутивах Linux.
Установка клиента NFS в Ubuntu и Debian:
Установка клиента NFS на CentOS и Fedora:
Монтирование файловых систем NFS вручную
Подключение удаленного общего ресурса NFS аналогично монтированию обычных файловых систем.
Чтобы смонтировать файловую систему NFS в заданной точке монтирования, используйте команду mount в следующей форме:
Выполните следующие действия, чтобы вручную смонтировать удаленный общий ресурс NFS в вашей системе Linux:
Сначала создайте каталог, который будет точкой монтирования для удаленного общего ресурса NFS:
Точка монтирования — это каталог на локальном компьютере, где должен быть смонтирован общий ресурс NFS.
Подключите общий ресурс NFS, выполнив следующую команду от имени пользователя root или пользователя с привилегиями sudo :
Где 10.10.0.10 — это IP-адрес сервера NFS, /backup — это каталог, который сервер экспортирует, а /var/backups — локальная точка монтирования.
В случае успеха вывод не производится.
Если вы хотите указать дополнительные параметры монтирования , используйте параметр -o . Несколько вариантов могут быть представлены в виде списка, разделенного запятыми. Чтобы получить список всех параметров монтирования, введите в терминале man mount .
Чтобы убедиться, что удаленный том NFS успешно смонтирован, используйте команду mount или df -h .
После монтирования общего ресурса точка монтирования становится корневым каталогом смонтированной файловой системы.
Когда вы монтируете общий ресурс вручную, подключение общего ресурса NFS не сохраняется после перезагрузки.
Автоматическое монтирование файловых систем NFS с помощью /etc/fstab
Как правило, вы хотите автоматически монтировать удаленный каталог NFS при загрузке системы.
Файл /etc/fstab содержит список записей, определяющих, где, как и какая файловая система будет монтироваться при запуске системы.
Чтобы автоматически монтировать общий ресурс NFS при запуске системы Linux, добавьте строку в файл /etc/fstab . Строка должна включать имя хоста или IP-адрес сервера NFS, экспортированный каталог и точку монтирования на локальном компьютере.
Используйте следующую процедуру для автоматического монтирования общего ресурса NFS в системах Linux:
Настройте точку монтирования для удаленного общего ресурса NFS:
Добавьте в файл следующую строку:
Где 10.10.0.10 — IP-адрес сервера NFS, /backup — это экспортированный каталог, а /var/backups — локальная точка монтирования.
Выполните команду mount в одной из следующих форм, чтобы смонтировать общий ресурс NFS:
Команда mount прочитает содержимое /etc/fstab и смонтирует общий ресурс.
В следующий раз, когда вы перезагрузите систему, общий ресурс NFS будет смонтирован автоматически.
Размонтирование файловых систем NFS
Команда umount отсоединяет (размонтирует) смонтированную файловую систему от дерева каталогов.
Чтобы отсоединить смонтированный общий ресурс NFS, используйте команду umount за которой следует либо каталог, в котором он был смонтирован, либо удаленный общий ресурс:
Если для монтирования NFS есть запись в fstab , удалите ее.
Команда umount не сможет отсоединить общий ресурс, когда смонтированный том используется. Чтобы узнать, какие процессы обращаются к общему ресурсу NFS, используйте команду fuser :
Как только вы найдете процессы, вы можете остановить их с помощью команды kill и отключить общий ресурс NFS.
Если у вас все еще есть проблемы с —lazy ресурса, используйте параметр -l ( —lazy ), который позволяет вам отключать загруженную файловую систему, как только она больше не занята.
Если удаленная система NFS недоступна, используйте параметр -f ( —force ) для принудительного размонтирования.
Как правило, не рекомендуется использовать опцию принудительного выполнения, так как это может повредить данные в файловой системе.
Выводы
Мы показали вам, как подключать и отключать удаленный общий ресурс NFS. Те же команды применимы для любого дистрибутива Linux, включая Ubuntu, CentOS, RHEL, Debian и Linux Mint.
Не стесняйтесь оставлять комментарии, если у вас есть вопросы.
Источник
Linux mount all nfs
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:
- The NFS root is /srv/nfs .
- 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:
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:
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.
Источник