Difference between revisions of "NFS"

From ArchWiki
Jump to: navigation, search
m (add it to File_system category)
m (Manual mounting: mount: only root can do that)
 
(223 intermediate revisions by 82 users not shown)
Line 1: Line 1:
 
[[Category:File systems]]
 
[[Category:File systems]]
[[Category:Networking]]
+
[[Category:Network sharing]]
 
[[ar:NFS]]
 
[[ar:NFS]]
 +
[[cs:NFS]]
 
[[de:Network File System]]
 
[[de:Network File System]]
 
[[es:NFS]]
 
[[es:NFS]]
 
[[fr:NFS]]
 
[[fr:NFS]]
[[it:NFSv4]]
+
[[it:NFS]]
[[zh-CN:NFS]]
+
[[ja:NFS]]
{{Article summary start}}
+
[[ru:NFS]]
{{Article summary text|Article covers configuration of NFSv4 which is an open standard network file sharing protocol.}}
+
[[zh-hans:NFS]]
{{Article summary heading|Related}}
+
{{Related articles start}}
{{Article summary wiki|NFS Troubleshooting}} - Dedicated article for common problems and solutions.
+
{{Related|NFS/Troubleshooting}}
{{Article summary wiki|NFSv3}} - Deprecated v3 format.
+
{{Related articles end}}
{{Article summary end}}
 
 
From [[Wikipedia: Network File System|Wikipedia]]:  
 
From [[Wikipedia: Network File System|Wikipedia]]:  
:''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.''
+
: ''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.''
  
==Installing==
+
== Installation ==
Both client and server only require the [[Pacman|installation]] of the {{Pkg|nfs-utils}} package.
 
  
{{Note|It is HIGHLY recommended to use a time sync daemon on ALL nodes of your network to keep client/server clocks in sync.  Without accurate clocks on all nodes, NFS can introduce unwanted delays! The [[NTP]] system is recommended to sync both the server and the clients to the highly accurate NTP servers available on the Internet.}}
+
Both client and server only require the [[install|installation]] of the {{Pkg|nfs-utils}} package.
 +
 
 +
It is '''highly''' recommended to use a [[Time#Time synchronization|time sync daemon]] to keep client/server clocks in sync.  Without accurate clocks on all nodes, NFS can introduce unwanted delays.
  
 
==Configuration==
 
==Configuration==
  
 
===Server===
 
===Server===
==== ID mapping ====
 
Edit {{ic|/etc/idmapd.conf}} and set the {{ic|Domain}} field to your domain name.
 
 
{{hc|/etc/idmapd.conf|<nowiki>
 
[General]
 
 
Verbosity = 1
 
Pipefs-Directory = /var/lib/nfs/rpc_pipefs
 
Domain = atomic
 
 
[Mapping]
 
  
Nobody-User = nobody
+
NFS needs to see the list of shares (referred to as "exports" from here on out), which are defined in {{ic|/etc/exports}} in order to serve-up the content.  The NFS root directory can be any directory on the file system.  In the interest of security, it is recommended to use an NFS export root which will keep users limited to that mount point only.  The following example illustrates this concept.
Nobody-Group = nobody
 
</nowiki>}}
 
==== File system ====
 
{{Note|For security reasons, it is recommended to use an NFS export root which will keep users limited to that mount point only.  The following example illustrates this concept.}}
 
  
Define any NFS shares in {{ic|/etc/exports}} which are relative to the NFS root.  In this example, the NFS root will be {{ic|/srv/nfs4}} and we will be sharing {{ic|/mnt/music}}.
+
Any NFS shares defined in {{ic|/etc/exports}} are relative to the NFS root.  In this example, the NFS root will be {{ic|/srv/nfs}} and we are sharing {{ic|/mnt/music}}.
  
{{bc|# mkdir -p /srv/nfs4/music}}
+
# mkdir -p /srv/nfs/music /mnt/music
  
 
Read/Write permissions must be set on the music directory so clients may write to it.  
 
Read/Write permissions must be set on the music directory so clients may write to it.  
  
Now mount the actual target share, {{ic|/mnt/music}} to the NFS share via the mount command:
+
Now mount the actual target share, {{ic|/mnt/music}} to the directory under the NFS root via the mount --bind command:
  
{{bc|# mount --bind /mnt/music /srv/nfs4/music}}
+
# mount --bind /mnt/music /srv/nfs/music
  
 
To make it stick across server reboots, add the bind mount to {{ic|fstab}}:
 
To make it stick across server reboots, add the bind mount to {{ic|fstab}}:
 +
 
{{hc|/etc/fstab|
 
{{hc|/etc/fstab|
/mnt/music /srv/nfs4/music  none  bind  0  0
+
/mnt/music /srv/nfs/music  none  bind  0  0
 
}}
 
}}
  
==== Exports ====
+
{{Note|[[ZFS]] filesystems require special handling of bindmounts, see [[ZFS#Bindmount]].}}
 +
 
 
Add directories to be shared and an ip address or hostname(s) of client machines that will be allowed to mount them in {{ic|exports}}:
 
Add directories to be shared and an ip address or hostname(s) of client machines that will be allowed to mount them in {{ic|exports}}:
 +
 
{{hc|/etc/exports|<nowiki>
 
{{hc|/etc/exports|<nowiki>
/srv/nfs4/ 192.168.0.1/24(rw,fsid=root,no_subtree_check)
+
/srv/nfs 192.168.1.0/24(rw,fsid=root,no_subtree_check)
/srv/nfs4/music 192.168.0.1/24(rw,no_subtree_check,nohide) # note the nohide option which is applied to mounted directories on the file system.
+
/srv/nfs/music 192.168.1.0/24(rw,no_subtree_check,nohide) # note the nohide option which is applied to mounted directories on the file system.
 
</nowiki>}}
 
</nowiki>}}
 +
 +
{{Note|If the target export is a tmpfs filesystem, the {{ic|1=fsid=1}} option is required.}}
  
 
Users need-not open the share to the entire subnet; one can specify a single IP address or hostname as well.
 
Users need-not open the share to the entire subnet; one can specify a single IP address or hostname as well.
  
For more information about all available options see {{ic|man 5 exports}}.
+
For more information about all available options see {{man|5|exports}}.
 +
 
 +
{{Note|Modifying {{ic|/etc/exports}} while the server is running will require a re-export for changes to take effect as noted by the upstream comments in {{ic|/etc/exports}}:
 +
 
 +
# exportfs -rav
  
If you modify {{ic|/etc/exports}} while the server is running, you must re-export them for changes to take effect:
+
}}
{{bc|# exportfs -ra}}
 
  
====Starting the server====
+
==== Starting the server ====
  
[[Daemons|Start/enable]] {{ic|rpc-idmapd.service}} and {{ic|rpc-mountd.service}}.  Note that these units require other services, which are launched automatically by [[systemd]].
+
[[Start]] and [[enable]] {{ic|nfs-server.service}}.
  
===Client===
+
==== Miscellaneous ====
Clients need {{Pkg|nfs-utils}} to connect, but no special setup is required when connecting to NFS 4 servers.
 
  
====Mounting from Linux====
+
===== Optional configuration =====
Show the server's exported filesystems:
+
 
{{bc|$ showmount -e servername}}
+
Advanced configuration options can be set in {{ic|/etc/nfs.conf}}.  Users setting up a simple configuration may not need to edit this file.
 +
 
 +
===== Ensure NFSv4 idmapping is fully enabled =====
 +
 
 +
Even though idmapd may be running, it may not be fully enabled. Verify by checking {{ic|cat /sys/module/nfsd/parameters/nfs4_disable_idmapping}} returns {{ic|N}}. If not:
 +
 
 +
# echo "N" | sudo tee /sys/module/nfsd/parameters/nfs4_disable_idmapping
 +
 
 +
Set this to survive reboots by adding an option to the nfs kernel module:
 +
 
 +
# echo "options nfs nfs4_disable_idmapping=0" | sudo tee -a /etc/modprobe.d/nfs.conf
 +
 
 +
(See [https://bbs.archlinux.org/viewtopic.php?pid=1530693#p1530693 this forum reply] for more information.)
 +
 
 +
If journalctl reports lines like the following when starting nfs-server.service and nfs-idmapd.service, then this may be the solution.
 +
 
 +
rpc.idmapd[25010]: nfsdcb: authbuf=192.168.0.0/16 authtype=user
 +
rpc.idmapd[25010]: nfsdcb: bad name in upcall
 +
 
 +
===== Static ports for NFSv3 =====
 +
{{Out of date|Configuration should be done in /etc/nfs.conf since {{Pkg|nfs-utils}} 2.1.1.[https://sourceforge.net/projects/nfs/files/nfs-utils/2.1.1/]}}
 +
Users needing support for NFSv3 clients, may wish to consider using static ports. By default, for NFSv3 operation {{ic|rpc.statd}} and {{ic|lockd}} use random ephemeral ports; in order to allow NFSv3 operations through a firewall static ports need to be defined. Edit {{ic|/etc/sysconfig/nfs}} to set {{ic|STATDARGS}}:
 +
 
 +
{{hc|/etc/sysconfig/nfs|2=
 +
STATDARGS="-p 32765 -o 32766 -T 32803"
 +
}}
 +
 
 +
The {{ic|rpc.mountd}} should consult {{ic|/etc/services}} and bind to the same static port 20048 under normal operation; however, if it needs to be explicity defined edit {{ic|/etc/sysconfig/nfs}} to set {{ic|RPCMOUNTDARGS}}:
 +
 
 +
{{hc|/etc/sysconfig/nfs|2=
 +
RPCMOUNTDARGS="-p 20048"
 +
}}
 +
 
 +
After making these changes, several services need to be restarted; the first writes the configuration options out to {{ic|/run/sysconfig/nfs-utils}} (see {{ic|/usr/lib/systemd/scripts/nfs-utils_env.sh}}), the second restarts {{ic|rpc.statd}} with the new ports, the last reloads {{ic|lockd}} (kernel module) with the new ports. [[Restart]] these services now: {{ic|nfs-config}}, {{ic|rpcbind}}, {{ic|rpc-statd}}, and {{ic|nfs-server}}.
 +
 
 +
After the restarts, use {{ic|rpcinfo -p}} on the server to examine the static ports are as expected. Using {{ic|rpcinfo -p <server IP>}} from the client should reveal the exact same static ports.
 +
 
 +
===== NFSv2 compatibility =====
 +
{{Out of date|Configuration should be done in /etc/nfs.conf since {{Pkg|nfs-utils}} 2.1.1.[https://sourceforge.net/projects/nfs/files/nfs-utils/2.1.1/]}}
 +
Users needing to support clients using NFSv2 (for example U-Boot), should set {{ic|1=RPCNFSDARGS="-V 2"}} in {{ic|/etc/sysconfig/nfs}}.
 +
 
 +
===== Firewall configuration =====
 +
 
 +
To enable access through a firewall, tcp and udp ports 111, 2049, and 20048 need to be opened when using the default configuration; use {{ic|rpcinfo -p}} to examine the exact ports in use on the server. To configure this for [[iptables]], execute this commands:
 +
 
 +
# iptables -A INPUT -p tcp -m tcp --dport 111 -j ACCEPT
 +
# iptables -A INPUT -p tcp -m tcp --dport 2049 -j ACCEPT
 +
# iptables -A INPUT -p tcp -m tcp --dport 20048 -j ACCEPT
 +
# iptables -A INPUT -p udp -m udp --dport 111 -j ACCEPT
 +
# iptables -A INPUT -p udp -m udp --dport 2049 -j ACCEPT
 +
# iptables -A INPUT -p udp -m udp --dport 20048 -j ACCEPT
 +
 
 +
To have this configuration load on every system start, edit {{ic|/etc/iptables/iptables.rules}} to include the following lines:
 +
 
 +
{{hc|/etc/iptables/iptables.rules|<nowiki>
 +
-A INPUT -p tcp -m tcp --dport 111 -j ACCEPT
 +
-A INPUT -p tcp -m tcp --dport 2049 -j ACCEPT
 +
-A INPUT -p tcp -m tcp --dport 20048 -j ACCEPT
 +
-A INPUT -p udp -m udp --dport 111 -j ACCEPT
 +
-A INPUT -p udp -m udp --dport 2049 -j ACCEPT
 +
-A INPUT -p udp -m udp --dport 20048 -j ACCEPT
 +
</nowiki>}}
 +
 
 +
The previous commands can be saved by executing:
 +
 
 +
# iptables-save > /etc/iptables/iptables.rules
 +
 
 +
{{note|This command will '''override''' the current iptables start configuration with the current iptables configuration!}}
 +
 
 +
If using NFSv3 and the above listed static ports for {{ic|rpc.statd}} and {{ic|lockd}} these also need to be added to the configuration:
 +
 
 +
{{hc|/etc/iptables/iptables.rules|<nowiki>
 +
-A INPUT -p tcp -m tcp --dport 32765 -j ACCEPT
 +
-A INPUT -p tcp -m tcp --dport 32803 -j ACCEPT
 +
-A INPUT -p udp -m udp --dport 32765 -j ACCEPT
 +
-A INPUT -p udp -m udp --dport 32803 -j ACCEPT
 +
</nowiki>}}
 +
 
 +
If using V4-only setup, only tcp port 2049 need to be opened. Therefore only one line needed.
 +
 
 +
{{hc|/etc/iptables/iptables.rules|<nowiki>
 +
-A INPUT -p tcp -m tcp --dport 2049 -j ACCEPT
 +
</nowiki>}}
 +
 
 +
To apply changes, [[Restart]] {{ic|iptables.service}}.
 +
 
 +
=== Client ===
 +
Users intending to use NFS4 with [[Kerberos]], also need to [[start]] and [[enable]] {{ic|nfs-client.target}}, which starts {{ic|rpc-gssd.service}}. However, due to bug {{Bug|50663}} in glibc, {{ic|rpc-gssd.service}} currently fails to start. Adding the "-f" (foreground) flag in the service is a workaround:
 +
 
 +
{{hc|# systemctl edit rpc-gssd.service|2=
 +
[Unit]
 +
Requires=network-online.target
 +
After=network-online.target
 +
 
 +
[Service]
 +
Type=simple
 +
ExecStart=
 +
ExecStart=/usr/sbin/rpc.gssd -f
 +
}}
 +
 
 +
==== Error from systemd ====
 +
 
 +
Users experiencing the following may consider turning off the service using system's masking feature: "Dependency failed for pNFS block layout mapping daemon."
 +
 
 +
Example:
 +
 
 +
# systemctl mask nfs-blkmap.service
 +
 
 +
==== Manual mounting ====
 +
 
 +
For NFSv3 use this command to show the server's exported file systems:
 +
 
 +
$ showmount -e servername
 +
 
 +
For NFSv4 mount the root NFS directory and look around for available mounts:
 +
 
 +
# mount server:/ /mountpoint/on/client
  
 
Then mount omitting the server's NFS export root:  
 
Then mount omitting the server's NFS export root:  
{{bc|# mount -t nfs4 servername:/music /mountpoint/on/client}}
 
  
=====/etc/fstab Settings=====
+
# mount -t nfs -o vers=4 servername:/music /mountpoint/on/client
 +
 
 +
If mount fails try including the server's export root (required for Debian/RHEL/SLES, some distributions need {{ic|-t nfs4}} instead of {{ic|-t nfs}}):
 +
 
 +
# mount -t nfs -o vers=4 servername:/full/path/to/music /mountpoint/on/client
 +
 
 +
{{Note|Server name needs to be a valid hostname (not just IP address). Otherwise mounting of remote share will hang.}}
 +
 
 +
==== 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 {{ic|/etc/fstab}} file, and add an appropriate line reflecting the setup. Again, the server's NFS export root is omitted.
 
Using [[fstab]] is useful for a server which is always on, and the NFS shares are available whenever the client boots up. Edit {{ic|/etc/fstab}} file, and add an appropriate line reflecting the setup. Again, the server's NFS export root is omitted.
  
{{hc|# nano /etc/fstab|<nowiki>
+
{{hc|/etc/fstab|<nowiki>
servername:/music  /mountpoint/on/client  nfs4   rsize=8192,wsize=8192,timeo=14,intr,_netdev 0 0
+
servername:/music  /mountpoint/on/client  nfs   rsize=8192,wsize=8192,timeo=14,_netdev 0 0
 
</nowiki>}}
 
</nowiki>}}
  
{{note|Consult the nfs and mount man pages for more mount options.}}
+
{{Note|Consult {{man|5|nfs}} and {{man|8|mount}} for more mount options.}}
  
 
Some additional mount options to consider are include:
 
Some additional mount options to consider are include:
Line 100: Line 217:
 
; timeo: The {{ic|timeo}} value is the amount of time, in tenths of a second, to wait before resending a transmission after an RPC timeout. After the first timeout, the timeout value is doubled for each retry for a maximum of 60 seconds or until a major timeout occurs. If connecting to a slow server or over a busy network, better performance can be achieved by increasing this timeout value.  
 
; timeo: The {{ic|timeo}} value is the amount of time, in tenths of a second, to wait before resending a transmission after an RPC timeout. After the first timeout, the timeout value is doubled for each retry for a maximum of 60 seconds or until a major timeout occurs. If connecting to a slow server or over a busy network, better performance can be achieved by increasing this timeout value.  
  
; intr: The {{ic|intr}} option allows signals to interrupt the file operation if a major timeout occurs for a hard-mounted share.
+
; _netdev: The {{ic|_netdev}} option tells the system to wait until the network is up before trying to mount the share. systemd assumes this for NFS, but anyway it is good practice to use it for all types of networked file systems
  
; _netdev: The {{ic|_netdev}} option tells the system to wait until the network is up before trying to mount the share. systemd assumes this for NFS, but anyway it is good practice to use it for all types of networked filesystems
+
{{Note|Setting the sixth field ({{ic|fs_passno}}) to a nonzero value may lead to unexpected behaviour, e.g. hangs when the systemd automount waits for a check which will never happen.}}
  
=====Using autofs=====
+
==== Mount using /etc/fstab with systemd ====
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.
 
  
==== Mounting from Windows ====
+
Another method is using the systemd {{ic|automount}} service. This is a better option than {{ic|_netdev}}, because it remounts the network device quickly when the connection is broken and restored. As well, it solves the problem from autofs, see the example below:
{{note|Only the Ultimate and Enterprise editions of Windows 7 and the Enterprise edition of Windows 8 include "Client for NFS".}}
 
NFS shares can be mounted from Windows if the "Client for NFS" service is activated (which it is not by default).
 
To install the service go to "Programs and features" in the Control Panel and click on "Turn Windows features on or off". Locate "Services for NFS" and activate it as well as both subservices ("Administrative tools" and "Client for NFS").
 
  
Some global options can be set by opening the "Services for Network File System" (locate it with the search box) and right click on client->properties.
+
{{hc|1=/etc/fstab|2=
 
+
servername:/home  ''/mountpoint/on/client''  nfs  noauto,x-systemd.automount,x-systemd.device-timeout=10,timeo=14,x-systemd.idle-timeout=1min 0 0 
{{Warning|Serious performance issues may occur (it randomly takes 30-60 seconds to display a folder, 2 MB/s file copy speed on gigabit LAN, ...) to which Microsoft does not have a solution yet.[https://social.technet.microsoft.com/Forums/en-CA/w7itpronetworking/thread/40cc01e3-65e4-4bb6-855e-cef1364a60ac]}}
+
}}
  
To mount a share using Explorer:
+
One might have to reboot the client to make systemd aware of the changes to fstab. Alternatively, try [[Systemd#Using_units|reloading]] systemd and restarting {{ic|''mountpoint-on-client''.automount}} to reload the {{ic|/etc/fstab}} configuration.
  
{{ic|Computer}} > {{ic|Map network drive}} > {{ic|servername:/srv/nfs4/music}}
+
{{Tip|
 +
* The {{ic|noauto}} mount option will not mount the NFS share until it is accessed: use {{ic|auto}} for it to be available immediately. <br> If experiencing any issues with the mount failing due to the network not being up/available, [[enable]] {{ic|NetworkManager-wait-online.service}}. It will ensure that {{ic|network.target}} has all the links available prior to being active.
 +
* The {{ic|users}} mount option would allow user mounts, but be aware it implies further options as {{ic|noexec}} for example.
 +
* The {{ic|<nowiki>x-systemd.idle-timeout=1min</nowiki>}} option will unmount the NFS share automatically after 1 minute of non-use. Good for laptops which might suddenly disconnect from the network.
 +
* If shutdown/reboot holds too long because of NFS,  [[enable]] {{ic|NetworkManager-wait-online.service}} to ensure that NetworkManager is not exited before the NFS volumes are unmounted. You may also try to add the {{ic|<nowiki>x-systemd.requires=network.target</nowiki>}} mount option if shutdown takes too long. }}
  
==== Mounting from OS X ====
+
{{Note|Users trying to automount a NFS-share via systemd which is mounted the same way on the server may experience a freeze when handling larger amounts of data.}}
{{note|OS X by default uses an insecure (>1024) port to mount a share.}}
 
Either export the share with the {{ic|insecure}} flag, and mount using Finder:
 
  
{{ic|Go}} > {{ic|Connect to Server}} > {{ic|nfs://servername/}}
+
==== Mount using autofs ====
  
Or, mount the share using a secure port using the terminal:
+
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.
{{bc|# sudo mount -t nfs -o resvport servername:/srv/nfs4 /Volumes/servername}}
 
  
 
== Tips and tricks ==
 
== Tips and tricks ==
Line 133: Line 247:
 
=== Performance tuning ===
 
=== Performance tuning ===
  
In order to get the most out of nfs, it is necessary to tune the {{ic|rsize}} and {{ic|wsize}} mount options to meet the requirements of the network configuration.
+
In order to get the most out of NFS, it is necessary to tune the {{ic|rsize}} and {{ic|wsize}} mount options to meet the requirements of the network configuration.
 +
 
 +
=== Automounting shares with systemd-networkd ===
 +
 
 +
Users making use of systemd-networkd might notice nfs mounts the fstab are not mounted when booting; errors like the following are common:
 +
 
 +
mount[311]: mount.nfs4: Network is unreachable
 +
 
 +
The solution is simple; force systemd to wait for the network to be completely configured by [[enabling]] {{ic|systemd-networkd-wait-online.service}}. In theory this slows down the boot-process because less services run in parallel.
  
 
=== Automatic mount handling ===
 
=== Automatic mount handling ===
Line 139: Line 261:
 
This trick is useful for laptops that require nfs shares from a local wireless network. If the nfs host becomes unreachable, the nfs share will be unmounted to hopefully prevent system hangs when using the hard mount option. See https://bbs.archlinux.org/viewtopic.php?pid=1260240#p1260240
 
This trick is useful for laptops that require nfs shares from a local wireless network. If the nfs host becomes unreachable, the nfs share will be unmounted to hopefully prevent system hangs when using the hard mount option. See https://bbs.archlinux.org/viewtopic.php?pid=1260240#p1260240
  
Make sure that the nfs mount points are correctly indicated in {{ic|/etc/fstab}}:
+
Make sure that the NFS mount points are correctly indicated in {{ic|/etc/fstab}}:
  
{{hc|$ cat /etc/fstab|<nowiki>lithium:/mnt/data          /mnt/data         nfs noauto,noatime,rsize=32768,wsize=32768,intr,hard 0 0
+
{{hc|$ cat /etc/fstab|<nowiki>
lithium:/var/cache/pacman  /var/cache/pacman nfs noauto,noatime,rsize=32768,wsize=32768,intr,hard 0 0</nowiki>
+
lithium:/mnt/data          /mnt/data         nfs noauto,noatime,rsize=32768,wsize=32768 0 0
 +
lithium:/var/cache/pacman  /var/cache/pacman nfs noauto,noatime,rsize=32768,wsize=32768 0 0</nowiki>
 
}}
 
}}
 +
 +
{{Note|You must use hostnames in {{ic|/etc/fstab}} for this to work, not IP addresses.}}
  
 
The {{ic|noauto}} mount option tells systemd not to automatically mount the shares at boot. systemd would otherwise attempt to mount the nfs shares that may or may not exist on the network causing the boot process to appear to stall on a blank screen.
 
The {{ic|noauto}} mount option tells systemd not to automatically mount the shares at boot. systemd would otherwise attempt to mount the nfs shares that may or may not exist on the network causing the boot process to appear to stall on a blank screen.
  
Create the {{ic|auto_share}} script that will be used by cron to check if the nfs host is reachable,
+
In order to mount NFS shares with non-root users the {{ic|user}} option has to be added.
  
{{hc|# nano /root/bin/auto_share|<nowiki>#!/bin/bash
+
Create the {{ic|auto_share}} script that will be used by ''cron'' or ''systemd/Timers'' to use ICMP ping to check if the NFS host is reachable:
  
SERVER="YOUR_NFS_HOST"
+
{{hc|/usr/local/bin/auto_share|<nowiki>
 +
#!/bin/bash
  
MOUNT_POINTS=`sed -e '/^.*#/d' -e '/^.*:/!d' -e 's/\t/ /g' /etc/fstab | tr -s " " | cut -f2 -d" "`
+
function net_umount {
 +
  umount -l -f $1 &>/dev/null
 +
}
  
ping -c 1 "${SERVER}" &>/dev/null
+
function net_mount {
 +
  mountpoint -q $1 || mount $1
 +
}
  
if [ $? -ne 0 ]; then
+
NET_MOUNTS=$(sed -e '/^.*#/d' -e '/^.*:/!d' -e 's/\t/ /g' /etc/fstab | tr -s " ")$'\n'b
     # The server could not be reached, unmount the shares
+
 
     for umntpnt in ${MOUNT_POINTS}; do
+
printf %s "$NET_MOUNTS" | while IFS= read -r line
        umount -l -f $umntpnt &>/dev/null
+
do
     done
+
  SERVER=$(echo $line | cut -f1 -d":")
else
+
  MOUNT_POINT=$(echo $line | cut -f2 -d" ")
    # The server is up, make sure the shares are mounted
+
 
    for mntpnt in ${MOUNT_POINTS}; do
+
  # Check if server already tested
        mountpoint -q $mntpnt || mount $mntpnt
+
  if [[ "${server_ok[@]}" =~ "${SERVER}" ]]; then
     done
+
    # The server is up, make sure the share are mounted
fi
+
    net_mount $MOUNT_POINT
 +
  elif [[ "${server_notok[@]}" =~ "${SERVER}" ]]; then
 +
     # The server could not be reached, unmount the share
 +
     net_umount $MOUNT_POINT
 +
  else
 +
    # Check if the server is reachable
 +
    ping -c 1 "${SERVER}" &>/dev/null
 +
 
 +
     if [ $? -ne 0 ]; then
 +
      server_notok[${#Unix[@]}]=$SERVER
 +
      # The server could not be reached, unmount the share
 +
      net_umount $MOUNT_POINT
 +
    else
 +
      server_ok[${#Unix[@]}]=$SERVER
 +
      # The server is up, make sure the share are mounted
 +
      net_mount $MOUNT_POINT
 +
     fi
 +
  fi
 +
done
 
</nowiki>}}
 
</nowiki>}}
  
{{bc|# chmod +x /root/bin/auto_share}}
+
{{Note|If you want to test using a TCP probe instead of ICMP ping (default is tcp port 2049 in NFS4) then replace the line:
 +
 
 +
  # Check if the server is reachable
 +
  ping -c 1 "${SERVER}" &>/dev/null
 +
 
 +
with:
 +
 
 +
  # Check if the server is reachable
 +
  timeout 1 bash -c ": < /dev/tcp/${SERVER}/2049"
 +
 
 +
in the {{ic|auto_share}} script above.}}
 +
 
 +
# chmod +x /usr/local/bin/auto_share
 +
 
 +
Create a cron entry or a systemd/Timers timer to check every minute if the server of the shares are reachable.
  
Create the root cron entry to run {{ic|auto_share}} every minute:
+
==== Cron ====
  
 
{{hc|# crontab -e|<nowiki>
 
{{hc|# crontab -e|<nowiki>
* * * * * /root/bin/auto_share
+
* * * * * /usr/local/bin/auto_share
 +
</nowiki>}}
 +
 
 +
==== systemd/Timers ====
 +
 
 +
{{hc|# /etc/systemd/system/auto_share.timer|<nowiki>
 +
[Unit]
 +
Description=Check the network mounts
 +
 
 +
[Timer]
 +
OnCalendar=*-*-* *:*:00
 +
 
 +
[Install]
 +
WantedBy=timer.target
 +
</nowiki>}}
 +
 
 +
{{hc|# /etc/systemd/system/auto_share.service|<nowiki>
 +
[Unit]
 +
Description=Check the network mounts
 +
 
 +
[Service]
 +
Type=simple
 +
ExecStart=/usr/local/bin/auto_share
 
</nowiki>}}
 
</nowiki>}}
  
A systemd unit file can also be used to mount the nfs shares at startup. The unit file is not necessary if NetworkManager is installed and configured on the client system. See [[#NetworkManger dispatch]]
+
# systemctl enable auto_share.timer
 +
 
 +
==== Mount at startup via systemd ====
  
{{hc|$ cat /etc/systemd/system/auto_share.service|<nowiki>
+
A systemd unit file can also be used to mount the NFS shares at startup. The unit file is not necessary if NetworkManager is installed and configured on the client system. See [[#NetworkManager dispatcher]].
 +
 
 +
{{hc|/etc/systemd/system/auto_share.service|<nowiki>
 
[Unit]
 
[Unit]
 
Description=NFS automount
 
Description=NFS automount
 +
After=syslog.target network.target
  
 
[Service]
 
[Service]
 
Type=oneshot
 
Type=oneshot
 
RemainAfterExit=yes
 
RemainAfterExit=yes
ExecStart=/root/bin/auto_share
+
ExecStart=/usr/local/bin/auto_share
  
 
[Install]
 
[Install]
WantedBy=multi-user.target</nowiki>}}
+
WantedBy=multi-user.target
 +
</nowiki>}}
  
{{bc|# systemctl enable auto_share}}
+
Now [[enable]] the {{ic|auto_share.service}}.
  
==== NetworkManger dispatch ====
+
==== NetworkManager dispatcher ====
  
In addition to the method described previously, NetworkManager can also be configured to run a script on network status change.
+
In addition to the method described previously, [[NetworkManager#Network_services_with_NetworkManager_dispatcher|NetworkManager]] can also be configured to run a script on network status change: [[Enable]] and [[start]] the {{ic|NetworkManager-dispatcher.service}}.
  
Enable the {{ic|NetworkManager-dispatch}} service.
+
The easiest method for mount shares on network status change is to just symlink to the {{ic|auto_share}} script:
  
{{bc|# systemctl enable NetworkManager-dispatch
+
# ln -s /usr/local/bin/auto_share /etc/NetworkManager/dispatcher.d/30-nfs.sh
# systemctl start NetworkManager-dispatch}}
 
  
The easiest method for mount shares on network status change is to just symlink to the {{ic|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.
  
{{bc|# ln -s /root/bin/auto_share /etc/NetworkManager/dispatcher.d/30_nfs.sh }}
+
The following script safely unmounts the NFS shares before the relevant network connection is disabled by listening for the {{ic|pre-down}} and {{ic|vpn-pre-down}} events:
  
Or use the following mounting script that checks for network availability:
+
{{Note|This script ignores mounts with the noauto option.}}
  
{{hc|# nano /etc/NetworkManager/dispatcher.d/30_nfs.sh|<nowiki>#!/bin/bash
+
{{hc|/etc/NetworkManager/dispatcher.d/30-nfs.sh|<nowiki>
 +
#!/bin/bash
  
SSID="CHANGE_ME"
+
# 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"
  
MOUNT_POINTS=`sed -e '/^.*#/d' -e '/^.*:/!d' -e 's/\t/ /g' /etc/fstab | tr -s " " | cut -f2 -d" "`
+
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
 +
            ;;
 +
        "pre-down");&
 +
        "vpn-pre-down")
 +
            umount -l -a -t nfs4,nfs >/dev/null
 +
            ;;
 +
    esac
 +
fi
 +
</nowiki>}}
  
ISNETUP=`nmcli dev wifi | \grep $SSID | tr -s ' ' | cut -f 10 -d ' '` 2>/dev/null
+
Make the script executable with [[chmod]] and create a symlink inside {{ic|/etc/NetworkManager/dispatcher.d/pre-down}} to catch the {{ic|pre-down}} events:
  
# echo "$ISNETUP" >> /tmp/nm_dispatch_log
+
# ln -s /etc/NetworkManager/dispatcher.d/30-nfs.sh /etc/NetworkManager/dispatcher.d/pre-down.d/30-nfs.sh
  
if [[ "$ISNETUP" == "yes" ]]; then
+
The above script can be modified to mount different shares (even other than NFS) for different connections.
    for mntpnt in ${MOUNT_POINTS}; do
 
        mountpoint -q $mntpnt || mount $mntpnt
 
    done
 
else
 
    for srvexp in ${MOUNT_POINTS}; do
 
        umount -l -f $srvexp &>/dev/null
 
    done
 
fi
 
</nowiki>}}
 
  
Now when the wireless SSID "CHANGE_ME" goes up or down, the {{ic|nfs.sh}} script will be called to mount or unmount the shares as soon as possible.
+
See also: [[NetworkManager#Use dispatcher to handle mounting of CIFS shares]].
  
 
== Troubleshooting ==
 
== Troubleshooting ==
  
 
There is a dedicated article [[NFS Troubleshooting]].
 
There is a dedicated article [[NFS Troubleshooting]].
 +
 +
== See also ==
 +
 +
* See also [[Avahi]], a Zeroconf implementation which allows automatic discovery of NFS shares.
 +
* HOWTO: [[Diskless network boot NFS root]]
 +
* [http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.prftungd/doc/prftungd/nfs_perf.htm NFS Performance Management]
 +
* [http://blogs.msdn.com/sfu/archive/2008/04/14/all-well-almost-about-client-for-nfs-configuration-and-performance.aspx Microsoft Services for Unix NFS Client info]
 +
* [https://blogs.oracle.com/jag/entry/nfs_on_snow_leopard NFS on Snow Leopard]

Latest revision as of 11:21, 19 March 2017

Related articles

From Wikipedia:

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.

Installation

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

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

Configuration

Server

NFS needs to see the list of shares (referred to as "exports" from here on out), which are defined in /etc/exports in order to serve-up the content. The NFS root directory can be any directory on the file system. In the interest of security, it is recommended to use an NFS export root which will keep users limited to that mount point only. The following example illustrates this concept.

Any NFS shares defined in /etc/exports are relative to the NFS root. In this example, the NFS root will be /srv/nfs and we are sharing /mnt/music.

# mkdir -p /srv/nfs/music /mnt/music

Read/Write permissions must be set on the music directory so clients may write to it.

Now mount the actual target share, /mnt/music to the directory under the NFS root via the mount --bind command:

# mount --bind /mnt/music /srv/nfs/music

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

/etc/fstab
/mnt/music /srv/nfs/music  none   bind   0   0
Note: ZFS filesystems require special handling of bindmounts, see ZFS#Bindmount.

Add directories to be shared and an ip address or hostname(s) of client machines that will be allowed to mount them in exports:

/etc/exports
/srv/nfs 192.168.1.0/24(rw,fsid=root,no_subtree_check)
/srv/nfs/music 192.168.1.0/24(rw,no_subtree_check,nohide) # note the nohide option which is applied to mounted directories on the file system.
Note: If the target export is a tmpfs filesystem, the fsid=1 option is required.

Users need-not open the share to the entire subnet; one can specify a single IP address or hostname as well.

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

Note: Modifying /etc/exports while the server is running will require a re-export for changes to take effect as noted by the upstream comments in /etc/exports:
# exportfs -rav

Starting the server

Start and enable nfs-server.service.

Miscellaneous

Optional configuration

Advanced configuration options can be set in /etc/nfs.conf. Users setting up a simple configuration may not need to edit this file.

Ensure NFSv4 idmapping is fully enabled

Even though idmapd may be running, it may not be fully enabled. Verify by checking cat /sys/module/nfsd/parameters/nfs4_disable_idmapping returns N. If not:

# echo "N" | sudo tee /sys/module/nfsd/parameters/nfs4_disable_idmapping

Set this to survive reboots by adding an option to the nfs kernel module:

# echo "options nfs nfs4_disable_idmapping=0" | sudo tee -a /etc/modprobe.d/nfs.conf

(See this forum reply for more information.)

If journalctl reports lines like the following when starting nfs-server.service and nfs-idmapd.service, then this may be the solution.

rpc.idmapd[25010]: nfsdcb: authbuf=192.168.0.0/16 authtype=user
rpc.idmapd[25010]: nfsdcb: bad name in upcall
Static ports for NFSv3

Tango-view-refresh-red.pngThis article or section is out of date.Tango-view-refresh-red.png

Reason: Configuration should be done in /etc/nfs.conf since nfs-utils 2.1.1.[1] (Discuss in Talk:NFS#)

Users needing support for NFSv3 clients, may wish to consider using static ports. By default, for NFSv3 operation rpc.statd and lockd use random ephemeral ports; in order to allow NFSv3 operations through a firewall static ports need to be defined. Edit /etc/sysconfig/nfs to set STATDARGS:

/etc/sysconfig/nfs
STATDARGS="-p 32765 -o 32766 -T 32803"

The rpc.mountd should consult /etc/services and bind to the same static port 20048 under normal operation; however, if it needs to be explicity defined edit /etc/sysconfig/nfs to set RPCMOUNTDARGS:

/etc/sysconfig/nfs
RPCMOUNTDARGS="-p 20048"

After making these changes, several services need to be restarted; the first writes the configuration options out to /run/sysconfig/nfs-utils (see /usr/lib/systemd/scripts/nfs-utils_env.sh), the second restarts rpc.statd with the new ports, the last reloads lockd (kernel module) with the new ports. Restart these services now: nfs-config, rpcbind, rpc-statd, and nfs-server.

After the restarts, use rpcinfo -p on the server to examine the static ports are as expected. Using rpcinfo -p <server IP> from the client should reveal the exact same static ports.

NFSv2 compatibility

Tango-view-refresh-red.pngThis article or section is out of date.Tango-view-refresh-red.png

Reason: Configuration should be done in /etc/nfs.conf since nfs-utils 2.1.1.[2] (Discuss in Talk:NFS#)

Users needing to support clients using NFSv2 (for example U-Boot), should set RPCNFSDARGS="-V 2" in /etc/sysconfig/nfs.

Firewall configuration

To enable access through a firewall, tcp and udp ports 111, 2049, and 20048 need to be opened when using the default configuration; use rpcinfo -p to examine the exact ports in use on the server. To configure this for iptables, execute this commands:

# iptables -A INPUT -p tcp -m tcp --dport 111 -j ACCEPT
# iptables -A INPUT -p tcp -m tcp --dport 2049 -j ACCEPT
# iptables -A INPUT -p tcp -m tcp --dport 20048 -j ACCEPT
# iptables -A INPUT -p udp -m udp --dport 111 -j ACCEPT
# iptables -A INPUT -p udp -m udp --dport 2049 -j ACCEPT
# iptables -A INPUT -p udp -m udp --dport 20048 -j ACCEPT

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

/etc/iptables/iptables.rules
-A INPUT -p tcp -m tcp --dport 111 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 2049 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 20048 -j ACCEPT
-A INPUT -p udp -m udp --dport 111 -j ACCEPT
-A INPUT -p udp -m udp --dport 2049 -j ACCEPT
-A INPUT -p udp -m udp --dport 20048 -j ACCEPT

The previous commands can be saved by executing:

# iptables-save > /etc/iptables/iptables.rules
Note: This command will override the current iptables start configuration with the current iptables configuration!

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

/etc/iptables/iptables.rules
-A INPUT -p tcp -m tcp --dport 32765 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 32803 -j ACCEPT
-A INPUT -p udp -m udp --dport 32765 -j ACCEPT
-A INPUT -p udp -m udp --dport 32803 -j ACCEPT

If using V4-only setup, only tcp port 2049 need to be opened. Therefore only one line needed.

/etc/iptables/iptables.rules
-A INPUT -p tcp -m tcp --dport 2049 -j ACCEPT

To apply changes, Restart iptables.service.

Client

Users intending to use NFS4 with Kerberos, also need to start and enable nfs-client.target, which starts rpc-gssd.service. However, due to bug FS#50663 in glibc, rpc-gssd.service currently fails to start. Adding the "-f" (foreground) flag in the service is a workaround:

# systemctl edit rpc-gssd.service
[Unit]
Requires=network-online.target
After=network-online.target

[Service]
Type=simple
ExecStart=
ExecStart=/usr/sbin/rpc.gssd -f

Error from systemd

Users experiencing the following may consider turning off the service using system's masking feature: "Dependency failed for pNFS block layout mapping daemon."

Example:

# systemctl mask nfs-blkmap.service

Manual mounting

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

$ showmount -e servername

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

# mount server:/ /mountpoint/on/client

Then mount omitting the server's NFS export root:

# mount -t nfs -o vers=4 servername:/music /mountpoint/on/client

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 -t nfs -o vers=4 servername:/full/path/to/music /mountpoint/on/client
Note: Server name needs to be a valid hostname (not just IP address). Otherwise mounting of remote share will hang.

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.

/etc/fstab
servername:/music   /mountpoint/on/client   nfs   rsize=8192,wsize=8192,timeo=14,_netdev	0 0
Note: Consult nfs(5) and mount(8) for more mount options.

Some additional mount options to consider are include:

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. The default for both is 1024, but using higher values such as 8192 can improve throughput. This is not universal. It is recommended to test after making this change, see #Performance tuning.
timeo
The timeo value is the amount of time, in tenths of a second, to wait before resending a transmission after an RPC timeout. After the first timeout, the timeout value is doubled for each retry for a maximum of 60 seconds or until a major timeout occurs. If connecting to a slow server or over a busy network, better performance can be achieved by increasing this timeout value.
_netdev
The _netdev option tells the system to wait until the network is up before trying to mount the share. systemd assumes this for NFS, but anyway it is good practice to use it for all types of networked file systems
Note: Setting the sixth field (fs_passno) to a nonzero value may lead to unexpected behaviour, e.g. hangs when the systemd automount waits for a check which will never happen.

Mount using /etc/fstab with systemd

Another method is using the systemd automount service. This is a better option than _netdev, because it remounts the network device quickly when the connection is broken and restored. As well, it solves the problem from autofs, see the example below:

/etc/fstab
servername:/home   /mountpoint/on/client  nfs  noauto,x-systemd.automount,x-systemd.device-timeout=10,timeo=14,x-systemd.idle-timeout=1min 0 0

One might have to reboot the client to make systemd aware of the changes to fstab. Alternatively, try reloading systemd and restarting mountpoint-on-client.automount to reload the /etc/fstab configuration.

Tip:
  • The noauto mount option will not mount the NFS share until it is accessed: use auto for it to be available immediately.
    If experiencing any issues with the mount failing due to the network not being up/available, enable NetworkManager-wait-online.service. It will ensure that network.target has all the links available prior to being active.
  • The users mount option would allow user mounts, but be aware it implies further options as noexec for example.
  • The x-systemd.idle-timeout=1min option will unmount the NFS share automatically after 1 minute of non-use. Good for laptops which might suddenly disconnect from the network.
  • If shutdown/reboot holds too long because of NFS, enable NetworkManager-wait-online.service to ensure that NetworkManager is not exited before the NFS volumes are unmounted. You may also try to add the x-systemd.requires=network.target mount option if shutdown takes too long.
Note: Users trying to automount a NFS-share via systemd which is mounted the same way on the server may experience a freeze when handling larger amounts of data.

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

In order to get the most out of NFS, it is necessary to tune the rsize and wsize mount options to meet the requirements of the network configuration.

Automounting shares with systemd-networkd

Users making use of systemd-networkd might notice nfs mounts the fstab are not mounted when booting; errors like the following are common:

mount[311]: mount.nfs4: Network is unreachable

The solution is simple; force systemd to wait for the network to be completely configured by enabling systemd-networkd-wait-online.service. In theory this slows down the boot-process because less services run in parallel.

Automatic mount handling

This trick is useful for laptops that require nfs shares from a local wireless network. If the nfs host becomes unreachable, the nfs share will be unmounted to hopefully prevent system hangs when using the hard mount option. See https://bbs.archlinux.org/viewtopic.php?pid=1260240#p1260240

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

$ cat /etc/fstab
lithium:/mnt/data           /mnt/data	        nfs noauto,noatime,rsize=32768,wsize=32768 0 0
lithium:/var/cache/pacman   /var/cache/pacman	nfs noauto,noatime,rsize=32768,wsize=32768 0 0
Note: You must use hostnames in /etc/fstab for this to work, not IP addresses.

The noauto mount option tells systemd not to automatically mount the shares at boot. systemd would otherwise attempt to mount the nfs shares that may or may not exist on the network causing the boot process to appear to stall on a blank screen.

In order to mount NFS shares with non-root users the user option has to be added.

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:

/usr/local/bin/auto_share
#!/bin/bash

function net_umount {
  umount -l -f $1 &>/dev/null
}

function net_mount {
  mountpoint -q $1 || mount $1
}

NET_MOUNTS=$(sed -e '/^.*#/d' -e '/^.*:/!d' -e 's/\t/ /g' /etc/fstab | tr -s " ")$'\n'b

printf %s "$NET_MOUNTS" | while IFS= read -r line
do
  SERVER=$(echo $line | cut -f1 -d":")
  MOUNT_POINT=$(echo $line | cut -f2 -d" ")

  # Check if server already tested
  if [[ "${server_ok[@]}" =~ "${SERVER}" ]]; then
    # The server is up, make sure the share are mounted
    net_mount $MOUNT_POINT
  elif [[ "${server_notok[@]}" =~ "${SERVER}" ]]; then
    # The server could not be reached, unmount the share
    net_umount $MOUNT_POINT
  else
    # Check if the server is reachable
    ping -c 1 "${SERVER}" &>/dev/null

    if [ $? -ne 0 ]; then
      server_notok[${#Unix[@]}]=$SERVER
      # The server could not be reached, unmount the share
      net_umount $MOUNT_POINT
    else
      server_ok[${#Unix[@]}]=$SERVER
      # The server is up, make sure the share are mounted
      net_mount $MOUNT_POINT
    fi
  fi
done
Note: If you want to test using a TCP probe instead of ICMP ping (default is tcp port 2049 in NFS4) then replace the line:
 # Check if the server is reachable
 ping -c 1 "${SERVER}" &>/dev/null

with:

 # Check if the server is reachable
 timeout 1 bash -c ": < /dev/tcp/${SERVER}/2049"
in the auto_share script above.
# chmod +x /usr/local/bin/auto_share

Create a cron entry or a systemd/Timers timer to check every minute if the server of the shares are reachable.

Cron

# crontab -e
* * * * * /usr/local/bin/auto_share

systemd/Timers

# /etc/systemd/system/auto_share.timer
[Unit]
Description=Check the network mounts

[Timer]
OnCalendar=*-*-* *:*:00

[Install]
WantedBy=timer.target
# /etc/systemd/system/auto_share.service
[Unit]
Description=Check the network mounts

[Service]
Type=simple
ExecStart=/usr/local/bin/auto_share
# systemctl enable auto_share.timer

Mount at startup via systemd

A systemd unit file can also be used to mount the NFS shares at startup. The unit file is not necessary if NetworkManager is installed and configured on the client system. See #NetworkManager dispatcher.

/etc/systemd/system/auto_share.service
[Unit]
Description=NFS automount
After=syslog.target network.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/bin/auto_share

[Install]
WantedBy=multi-user.target

Now enable the auto_share.service.

NetworkManager dispatcher

In addition to the method described previously, NetworkManager can also be configured to run a script on network status change: Enable and start the NetworkManager-dispatcher.service.

The easiest method for mount shares on network status change is to just symlink to 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 pre-down and vpn-pre-down events:

Note: This script ignores mounts with the noauto option.
/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 
            ;;
        "pre-down");&
        "vpn-pre-down")
            umount -l -a -t nfs4,nfs >/dev/null
            ;;
    esac
fi

Make the script executable with chmod and 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

The above script can be modified to mount different shares (even other than NFS) for different connections.

See also: NetworkManager#Use dispatcher to handle mounting of CIFS shares.

Troubleshooting

There is a dedicated article NFS Troubleshooting.

See also