How to mount NFS share using systemd

This is an extension to an older blog post on how to mount WebDAV share using systemd as this proved to be very reliable method that is easy to mark as dependency for other services.

Install nfs-common package to mount NFS share.

$ sudo apt-get install nfs-common

Create mount directory.

$ sudo mkdir /mnt/usr-export-from-main-server

Escape mount directory name so it can be used to name systemd unit file.

$ systemd-escape /mnt/usr-export-from-main-server
mnt-usr\x2dexport\x2dfrom\x2dmain\x2dserver

Verify that unit name will match mount path.

$ systemd-escape --unescape --path  'mnt-usr\x2dexport\x2dfrom\x2dmain\x2dserver'
/mnt/usr-export-from-main-server

Create systemd mount unit configuration.

$ cat << EOF | sudo tee '/etc/systemd/system/mnt-usr\x2dexport\x2dfrom\x2dmain\x2dserver.mount'
[Unit]
Description=Mount NFS share
After=network-online.target
Wants=network-online.target

[Mount]
What=192.168.50.151:/usr
Where=/mnt/usr-export-from-main-server
Options=auto
Type=nfs
TimeoutSec=60

[Install]
WantedBy=remote-fs.target
EOF

Reload systemd manager configuration.

$ sudo systemctl daemon-reload

Enable the mount service at boot time.

$ sudo systemctl enable 'mnt-usr\x2dexport\x2dfrom\x2dmain\x2dserver.mount'

Start the mount service right away.

$ sudo systemctl start 'mnt-usr\x2dexport\x2dfrom\x2dmain\x2dserver.mount'

Finally, check service status.

$ sudo systemctl status 'mnt-usr\x2dexport\x2dfrom\x2dmain\x2dserver.mount'
● mnt-usr\x2dexport\x2dfrom\x2dmain\x2dserver.mount - Mount NFS share
   Loaded: loaded (/etc/systemd/system/mnt-usr\x2dexport\x2dfrom\x2dmain\x2dserver.mount; enabled; vendor preset: enabled)
   Active: active (mounted) since Tue 2019-06-04 21:59:47 GMT; 4min 5s ago
    Where: /mnt/usr-export-from-main-server
     What: 192.168.50.151:/usr
    Tasks: 0 (limit: 394)
   Memory: 364.0K
   CGroup: /system.slice/mnt-usr\x2dexport\x2dfrom\x2dmain\x2dserver.mount

Jun 04 21:59:45 buster systemd[1]: Mounting Mount NFS share...
Jun 04 21:59:47 buster systemd[1]: Mounted Mount NFS share.

References