- Automount
- Configure export directory
- Enabling nfsv4 idmapping
- Firewall configuration
- Important commands for nfs
- Installing nfs server and nfs client
- Mount shared directories on nfs client
- Mount shared nfs directory
- Mount using /etc/fstab with systemd
- Nfs services
- Performance tuning
- Removing the nfs mount
- Restricting nfs to interfaces/ips
- Setting up the nfs client
- Setting up the nfs server
- Setup and configure nfs mounts on linux server
- Starting the server
- Systemd/timers
- Test the working of nfs setup
- Troubleshooting
- Using a networkmanager dispatcher
- Использование на ноутбуке
- Установка и настройка сервера и клиента nfs в centos linux 7.2 [вики it-kb]
- At the nfsserver end
- At the nfsclient end
Automount
To automatically mount a share, one may use the following automount unit:
/etc/systemd/system/mnt-home.automount
Configure export directory
For sharing a directory with NFS, we need to make an entry in “/etc/exports” configuration file. Here I’ll be creating a new directory named “nfsshare” in “/” partition to share with client server, you can also share an already existing directory with NFS.
[[email protected] ~]# mkdir /nfsshareNow we need to make an entry in “/etc/exports” and restart the services to make our directory shareable in the network.
[[email protected] ~]# vi /etc/exports
/nfsshare 192.168.0.101(rw,sync,no_root_squash)In the above example, there is a directory in / partition named “nfsshare” is being shared with client IP “192.168.0.101” with read and write (rw) privilege, you can also use hostname of the client in the place of IP in above example.
Enabling nfsv4 idmapping
# dmesg | grep id_resolver
[ 3238.356001] NFS: Registering the id_resolver key type [ 3238.356009] Key type id_resolver registered
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:
$ rpcinfo -p | grep nfs
100003 3 tcp 2049 nfs 100003 4 tcp 2049 nfs 100227 3 tcp 2049 nfs_acl
When using NFSv4, make sure TCP port 2049 is open. No other port opening should be required:
Important commands for nfs
Some more important commands for NFS.
- showmount -e : Shows the available shares on your local machine
- showmount -e<server-ip or hostname>: Lists the available shares at the remote server
- showmount -d : Lists all the sub directories
- exportfs -v : Displays a list of shares files and options on a server
- exportfs -a : Exports all shares listed in /etc/exports, or given name
- exportfs -u : Unexports all shares listed in /etc/exports, or given name
- exportfs -r : Refresh the server’s list after modifying /etc/exports
Installing nfs server and nfs client
We need to install NFS packages on our NFS Server as well as on NFS Client machine. We can install it via “yum” (Red Hat Linux) and “apt-get” (Debian and Ubuntu) package installers.
[[email protected] ~]# yum install nfs-utils nfs-utils-lib [[email protected] ~]# yum install portmap (not required with NFSv4)
[[email protected] ~]# apt-get install nfs-utils nfs-utils-libMount shared directories on nfs client
Now at the NFS client end, we need to mount that directory in our server to access it locally. To do so, first we need to find out that shares available on the remote server or NFS Server.
[[email protected] ~]# showmount -e 192.168.0.100
Export list for 192.168.0.100:
/nfsshare 192.168.0.101Above command shows that a directory named “nfsshare” is available at “192.168.0.100” to share with your server.
Mount shared nfs directory
To mount that shared NFS directory we can use following mount command.
[[email protected] ~]# mount -t nfs 192.168.0.100:/nfsshare /mnt/nfsshareThe above command will mount that shared directory in “/mnt/nfsshare” on the client server. You can verify it following command.
[[email protected] ~]# mount | grep nfs
sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)
nfsd on /proc/fs/nfsd type nfsd (rw)
192.168.0.100:/nfsshare on /mnt type nfs (rw,addr=192.168.0.100)The above mount command mounted the nfs shared directory on to nfs client temporarily, to mount an NFS directory permanently on your system across the reboots, we need to make an entry in “/etc/fstab“.
[[email protected] ~]# vi /etc/fstabAdd the following new line as shown below.
192.168.0.100:/nfsshare /mnt nfs defaults 0 0
Mount using /etc/fstab with systemd
Another method is using the x-systemd.automount option which mounts the filesystem upon access:
/etc/fstab
servername:/home /mountpoint/on/client nfs _netdev,noauto,x-systemd.automount,x-systemd.mount-timeout=10,timeo=14,x-systemd.idle-timeout=1min 0 0To make systemd aware of the changes to fstab, reload systemd and restart remote-fs.target[3].
Nfs services
Its a System V-launched service. The NFS server package includes three facilities, included in the portmap and nfs-utils packages.
- portmap : It maps calls made from other machines to the correct RPC service (not required with NFSv4).
- nfs: It translates remote file sharing requests into requests on the local file system.
- rpc.mountd: This service is responsible for mounting and unmounting of file systems.
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:
/etc/nfs.conf
[nfsd] threads=16
It may be necessary to tune the rsize and wsize mount options to meet the requirements of the network configuration.
Removing the nfs mount
If you want to unmount that shared directory from your server after you are done with the file sharing, you can simply unmount that particular directory with “umount” command. See this example below.
[email protected] ~]# umount /mnt/nfsshareYou can see that the mounts were removed by then looking at the filesystem again.
[[email protected] ~]# df -h -F nfsYou’ll see that those shared directories are not available any more.
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.
/etc/nfs.conf
[nfsd] host=192.168.1.123 # Alternatively, use the hostname. # host=myhostname
Restartnfs-server.service to apply the changes immediately.
Setting up the nfs client
After configuring the NFS server, we need to mount that shared directory or partition in the client server.
Setting up the nfs server
First we will be configuring the NFS server.
Setup and configure nfs mounts on linux server
To setup NFS mounts, we’ll be needing at least two Linux/Unix machines. Here in this tutorial, I’ll be using two servers.
Starting the server
Start and enablenfs-server.service.
Systemd/timers
/etc/systemd/system/auto_share.timer
[Unit] Description=Automount NFS shares every minute [Timer] OnCalendar=*-*-* *:*:00 [Install] WantedBy=timers.target
/etc/systemd/system/auto_share.service
Test the working of nfs setup
We can test our NFS server setup by creating a test file on the server end and check its availability at nfs client side or vice-versa.
Troubleshooting
There is a dedicated article NFS/Troubleshooting.
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:
# ln -s /usr/local/bin/auto_share /etc/NetworkManager/dispatcher.d/30-nfs.sh
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 down, pre-down and vpn-pre-down events, make sure the script is executable:
/etc/NetworkManager/dispatcher.d/30-nfs.sh
#!/bin/bash # Find the connection UUID with "nmcli con show" in terminal. # All NetworkManager connection types are supported: wireless, VPN, wired... WANTED_CON_UUID="CHANGE-ME-NOW-9c7eff15-010a-4b1c-a786-9b4efa218ba9" if [[ "$CONNECTION_UUID" == "$WANTED_CON_UUID" ]]; then # Script parameter $1: NetworkManager connection name, not used # Script parameter $2: dispatched event case "$2" in "up") mount -a -t nfs4,nfs ;; "down");& "pre-down");& "vpn-pre-down") umount -l -a -t nfs4,nfs -f >/dev/null ;; esac fi
Note: This script ignores mounts with the noauto option, remove this mount option or use auto to allow the dispatcher to manage these mounts.
Create a symlink inside /etc/NetworkManager/dispatcher.d/pre-down to catch the pre-down events:
# ln -s /etc/NetworkManager/dispatcher.d/30-nfs.sh /etc/NetworkManager/dispatcher.d/pre-down.d/30-nfs.sh
Использование на ноутбуке
При монтировании удаленных папок NFS посредством fstab, в ситуации, когда сеть с сервером будет не доступна, ноутбук невозможно выключить или отправить в спящий режим. Для использования удаленных папок NFS на ноутбуке лучше воспользоваться монтированием при помощи autofs
Установка и настройка сервера и клиента nfs в centos linux 7.2 [вики it-kb]
В этой статье мы рассмотрим простой пример того, как установить и настроить Network File System (NFS) в CentOS Linux 7.2.
На стороне сервера будет настроена NFS-шара, а на стороне клиента эта шара будет подключена.
В некоторых дистрибутивах Linux NFS-сервер и клиент устанавливаются при установке ОС.
Например в CentOS 6 NFS-сервер устанавливался по умолчанию, но служба не была включена в автозагрузку.
В CentOS 7 серверные и клиентские компоненты NFS нужно устанавливать самостоятельно.
При этом в CentOS 7 используется обновлённая усовершенствованная версия NFS 4.1.
Устанавливаем пакеты для организации NFS-сервера
# yum install nfs-utils
Включаем автозагрузку для служб rpcbind и nfs-server:
# systemctl enable rpcbind nfs-server Created symlink from /etc/systemd/system/multi-user.target.wants/nfs-server.service to /usr/lib/systemd/system/nfs-server.service.
Запускаем службы:
# systemctl start rpcbind nfs-server
Проверяем для каких версий NFS способен принимать подключения наш NFS-сервер:
# rpcinfo -p localhost program vers proto port service ... 100003 3 tcp 2049 nfs 100003 4 tcp 2049 nfs 100003 3 udp 2049 nfs 100003 4 udp 2049 nfs ...
Как видим, наш NFS сервер должен принимать подключения как NFSv3 так и NFSv4.
Создаём каталог под NFS-шару
# mkdir -p /var/nfs # chmod -R 777 /var/nfs
Создаём NFS-шару в файле /etc/exports:
# cat /etc/exports /var/nfs 10.1.1.0/24(rw,sync,no_root_squash,no_all_squash)
Описание использованных опций позаиствовано отсюда:
rw – доступ на чтение и запись (может принимать значение ro-только чтение);
sync – синхронный режим доступа(может принимать обратное значение- async). sync (async) — указывает, что сервер должен отвечать на запросы только после записи на диск изменений, выполненных этими запросами. Опция async указывает серверу не ждать записи информации на диск, что повышает производительность, но понижает надежность, т.к. в случае обрыва соединения или отказа оборудования возможна потеря данных;
no_root_squash – запрет подмены uid/gid для суперпользователя (root). По умолчанию пользователь root на клиентской машине не будет иметь доступа к разделяемой директории сервера. Этой опцией мы снимаем это ограничение. В целях безопасности этого лучше не делать;
all_squash / no_all_squash — установка подмены идентификатора от всех пользователей
all_squash — подмена запросов от ВСЕХ пользователей (не только root) на анонимного uid/gid, либо на пользователя, заданного в параметре anonuid/anongid. Используется обычно для публичного экспорта директорий.
no_all_squash — запрет подмены uid/gid для от всех пользователей
Чтобы служба nfs-server перечитала конфигурацию, выполним
# exportfs -r
Выполнив команду exportfs убедимся в том, что ресурс опубликован:
# exportfs /var/nfs 10.1.1.0/24
Добавляем разрешающие правила брандмауэра:
# firewall-cmd --permanent --zone=public --add-service=nfs # firewall-cmd --permanent --zone=public --add-service=mountd # firewall-cmd --permanent --zone=public --add-service=rpc-bind # firewall-cmd --reload
Устанавливаем пакетов поддержки NFS:
# yum install nfs-utils
Включаем и запускаем включаем службы NFS:
# systemctl start rpcbind # systemctl enable rpcbind
Создаем каталог, в который будет смонтирована шара и монтируем шару:
# mkdir /mnt/nfs-share # mount -t nfs KOM-FS03.holding.com:/var/nfs/ /mnt/nfs-share/
Проверяем то, что каталог примонтирован:
# mount | grep nfs4 KOM-FS03.holding.com:/var/nfs/ on /mnt/nfs-share type nfs4 (rw,relatime,vers=4.0,rsize=1048576,wsize=1048576, namlen=255,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys, clientaddr=10.1.1.201,local_lock=none,addr=10.1.1.4)
# df -hT | grep nfs4 KOM-FS03.holding.com:/var/nfs nfs4 3.6T 88M 3.4T 1% /mnt/nfs-share
Проверим возможность записи в шару
# touch /mnt/nfs-share/test.txt # rm /mnt/nfs-share/test.txt
Настраиваем автоматическое монтирование шары при перезагрузке системы, добавляя запись в конец файла /etc/fstab:
# cat /etc/fstab ... KOM-FS03.holding.com:/var/nfs/ /mnt/nfs-share/ nfs defaults 0 0
Автор первичной редакции:
Алексей Максимов
Время публикации: 01.09.2021 15:30
At the nfsserver end
I have created a new text file named “nfstest.txt’ in that shared directory.
[[email protected] ~]# cat > /nfsshare/nfstest.txt
This is a test file to test the working of NFS server setup.At the nfsclient end
Go to that shared directory in client server and you’ll find that shared file without any manual refresh or service restart.
[[email protected]]# ll /mnt/nfsshare total 4 -rw-r--r-- 1 root root 61 Sep 21 21:44 nfstest.txt[email protected] ~]# cat /mnt/nfsshare/nfstest.txt This is a test file to test the working of NFS server setup.





