Basic Filesharing with NFSv4

In this tutorial we’ll be setting up a basic Network Filesystem version 4 (NFSv4) share, and mount it on a client machine. NFSv4 is the current iteration of the NFS specification. NFS provides similar functionality as Samba (SMB) file sharing, although it provides tighter integration with Kerberos.

For this tutorial we’ll assume Debian-like environments for both the server and the client.

First, lets set up the server.

apt-get install nfs-kernel-server

Ignore any warnings about missing entries in /etc/exports, because we haven’t written the configuration yet. Lets go ahead and set up the shares, then we’ll write the configuration. The way that NFSv4 works is a bit different from previous versions, instead of separate directory paths that can be located anywhere on the filesystem, for security purposes all shares must reside in the same directory. To “work around” this, we use bind mounts. In our example, we want to share the files located under /home/data

mkdir /nfs
mount -o bind /home/data /nfs/data

To make this bind mount happen every time on boot, add an entry similar to this in to /etc/fstab:
/home/data    /nfs/data   none    bind  0  0

Now we need to configure NFS itself to export that directory. Edit /etc/exports and put down something similar to this:

/nfs         192.168.1.0/24(rw,fsid=0,no_subtree_check,sync)
/nfs/data 192.168.1.0/24(rw,nohide,insecure,no_subtree_check,sync)

This will export the single directory, /nfs/data, to all clients on the network 192.168.1.0/24.

The server is now set up. Lets restart the daemons then move on to the client.

service nfs-kernel-server restart
service idmapd restart

Over on the client, first we need to install the supporting daemons (most distributions install them by default).

apt-get install nfs-common

We can now mount the entire NFS export tree to /mnt like so:

mount -t nfs4 -o proto=tcp,port=2049 the-nfs-server:/ /mnt

Or we can mount just the one share to /data:

mount -t nfs4 -o proto=tcp,port=2049 the-nfs-server:/data /data

To make it happen on boot, add something like this to /etc/fstab. For this example, we're assuming that the “data” export is what you want mounted.

nfs-server:/data   /data   nfs4    _netdev,auto  0  0

“_netdev” is a hook used by many init scripts to ensure networking is up. Exact usage depends on your distribution.

To mount it using autofs (highly recommended), in /etc/auto.master add this line:

/data        /etc/auto.nfs

Then edit /etc/auto.nfs to contain:

the-nfs-server   -fstype=nfs4     server:/data

Make sure you remove the /etc/fstab line if you've added it.