How to Export a File System with NFS in Linux

how to export file system with NFS in Linux

Imagine you have a directory full of important project files on one Linux server, and you want multiple other computers on your network to access those files as if they were stored locally, without copying them around manually. This is exactly what NFS (Network File System) allows you to do. The process of making a local directory available to remote clients over NFS is called exporting a file system.

In this article, we’ll explain what NFS is, how exporting works from first principles, and walk through the complete process of configuring an NFS export on Linux, step by step, with troubleshooting and best practices.

Table of Contents

  1. What Is NFS?
  2. How Does NFS Work Under the Hood?
  3. What Does “Exporting” a File System Mean?
  4. Prerequisites
  5. Step-by-Step: Installing NFS Server
  6. Step-by-Step: Creating and Configuring the Export
  7. Understanding the /etc/exports File Syntax
  8. Applying and Verifying Exports
  9. Firewall Configuration
  10. NFS Versions Explained
  11. Real-World Example
  12. Cisco/Network Context
  13. Python Example: Checking NFS Export Availability
  14. Comparison Table: NFS Export Options
  15. Best Practices
  16. Troubleshooting Common Issues
  17. Conclusion

1. What Is NFS?

NFS (Network File System) is a distributed file system protocol, originally developed by Sun Microsystems, that allows a computer (the NFS server) to share directories over a network so that other computers (NFS clients) can mount and access those directories as though they were part of their own local file system.

Unlike simply copying files between machines, NFS provides live, real-time access — when a file changes on the server, every client sees the change immediately, because they’re all reading from the same underlying storage.

2. How Does NFS Work Under the Hood?

NFS operates using a client-server model over the network, historically relying on RPC (Remote Procedure Call) to communicate between the client and server. When a client wants to read or write a file:

  1. The client sends an RPC request to the NFS server, referencing the exported directory and the desired file operation (read, write, list, etc.).
  2. The server checks whether the client is authorized to access that export (based on IP address, hostname, or network range).
  3. The server performs the operation on the actual file system and sends the result back to the client.
  4. The client’s operating system presents this remote directory to local applications exactly like a normal local folder.
sequenceDiagram
    participant Client as NFS Client
    participant Server as NFS Server
    participant Disk as Local Disk (Server)

    Client->>Server: Mount request for /shared
    Server->>Server: Check /etc/exports permissions
    Server->>Client: Mount granted
    Client->>Server: Read file request
    Server->>Disk: Fetch file data
    Disk->>Server: Return file data
    Server->>Client: File data returned

3. What Does “Exporting” a File System Mean?

Exporting is the process, performed on the NFS server, of declaring which local directories are available for remote clients to mount, and defining the rules for who can access them and what permissions they have (read-only, read-write, etc.). This is configured in a special file called /etc/exports.

Think of exporting as “publishing” a folder to the network with a specific access policy — similar to sharing a folder in Windows, but using the NFS protocol instead of SMB.

4. Prerequisites

Before exporting a file system with NFS, you need:

  • A Linux server (Ubuntu, Debian, CentOS, RHEL, etc.) that will act as the NFS server.
  • Root or sudo access on that server.
  • A directory you want to share (e.g., /srv/nfs/shared).
  • Basic knowledge of the client machines’ IP addresses or subnet that should be allowed access.
  • An open network path between server and clients (typically port 2049 for NFS).

5. Step-by-Step: Installing NFS Server

On Ubuntu/Debian-based systems:

sudo apt update
sudo apt install nfs-kernel-server -y

On CentOS/RHEL/Fedora-based systems:

sudo dnf install nfs-utils -y

Start and enable the NFS service so it runs on boot

sudo systemctl start nfs-server
sudo systemctl enable nfs-server
sudo systemctl status nfs-server

6. Step-by-Step: Creating and Configuring the Export

Step 1: Create the directory you want to share.

sudo mkdir -p /srv/nfs/shared

Step 2: Set appropriate ownership and permissions.

sudo chown nobody:nogroup /srv/nfs/shared   # Ubuntu/Debian
sudo chown nobody:nobody /srv/nfs/shared    # CentOS/RHEL
sudo chmod 755 /srv/nfs/shared

Step 3: Edit the /etc/exports file to declare the export.

sudo nano /etc/exports

Add a line like this:

/srv/nfs/shared    192.168.1.0/24(rw,sync,no_subtree_check)

This line tells the NFS server: “Export the /srv/nfs/shared directory to any client on the 192.168.1.0/24 subnet, allow read-write access, use synchronous writes, and don’t check subtree permissions.”

7. Understanding the /etc/exports File Syntax

The general syntax of an entry in /etc/exports is:

<directory>   <client_specification>(<options>)

Common client specifications:

SpecificationMeaning
192.168.1.10A single specific client IP
192.168.1.0/24An entire subnet
*.example.comAny host matching this DNS wildcard
*Any client (not recommended for security reasons)

Common export options:

OptionMeaning
rwRead-write access
roRead-only access
syncWrites are committed to disk before responding to the client (safer, slightly slower)
asyncWrites are acknowledged before being committed to disk (faster, riskier on crash)
no_subtree_checkDisables subtree checking, improving reliability
root_squashMaps remote root user to an unprivileged user (default, more secure)
no_root_squashAllows remote root user to have root privileges on the export (use with caution)

8. Applying and Verifying Exports

Apply the changes without restarting the whole service:

sudo exportfs -ra

View all currently active exports:

sudo exportfs -v

Sample output:

/srv/nfs/shared  192.168.1.0/24(rw,wdelay,root_squash,no_subtree_check,sec=sys,rw,secure,root_squash,no_all_squash)

Verify the NFS server is listening on the correct port:

sudo ss -tulnp | grep nfs

9. Firewall Configuration

NFS uses several ports, primarily 2049 (TCP/UDP), along with additional ports for related services like rpcbind and mountd.

On systems using firewalld (CentOS/RHEL):

sudo firewall-cmd --permanent --add-service=nfs
sudo firewall-cmd --permanent --add-service=rpc-bind
sudo firewall-cmd --permanent --add-service=mountd
sudo firewall-cmd --reload

On systems using ufw (Ubuntu/Debian):

sudo ufw allow from 192.168.1.0/24 to any port nfs

10. NFS Versions Explained

VersionKey Characteristics
NFSv2Legacy, rarely used today, 32-bit file size limits
NFSv3Widely supported, supports larger files, still requires rpcbind
NFSv4Stateful protocol, integrated security (Kerberos support), works over a single port (2049), no longer requires rpcbind for basic operation
NFSv4.1/4.2Adds performance improvements like parallel NFS (pNFS), server-side copy, sparse file support

Modern deployments should prefer NFSv4 for its simplified firewall requirements (single port) and improved security model.

11. Real-World Example

A university research lab has a central Linux server storing large genomic datasets. Instead of copying multi-gigabyte files to every researcher’s workstation, the lab administrator exports the dataset directory via NFS:

/data/genomics    10.10.20.0/24(ro,sync,no_subtree_check)

Every workstation on the 10.10.20.0/24 subnet can now mount /data/genomics as read-only, allowing dozens of researchers to analyze the same dataset simultaneously without duplicating storage.

Extended Example: Multi-Tier Access for a Media Production Team

A video production company stores raw footage, editing project files, and final rendered exports on a central Linux storage server. Different teams need different levels of access:

/srv/nfs/raw-footage      192.168.10.0/24(ro,sync,no_subtree_check)
/srv/nfs/editing-projects 192.168.10.0/24(rw,sync,no_subtree_check)
/srv/nfs/final-renders    192.168.10.50(rw,sync,no_subtree_check)

Here, the entire editing subnet has read-only access to raw footage (protecting original camera files from accidental modification), read-write access to active editing projects, and only the rendering workstation (192.168.10.50) has write access to the final renders directory — a practical illustration of how granular, per-directory export rules support real production workflows.

12. Cisco/Network Context

While Cisco switches and routers don’t run NFS themselves, they are responsible for ensuring the network path between NFS clients and the server is reliable, since NFS is sensitive to packet loss and latency (especially with sync writes). Network administrators should ensure:

QoS prioritization for NFS traffic on a Cisco switch (example, marking NFS traffic for priority handling):

Switch(config)# access-list 101 permit tcp any any eq 2049
Switch(config)# class-map match-all NFS-TRAFFIC
Switch(config-cmap)# match access-group 101
Switch(config-cmap)# exit
Switch(config)# policy-map QOS-POLICY
Switch(config-pmap)# class NFS-TRAFFIC
Switch(config-pmap-c)# priority percent 30

This ensures NFS traffic (port 2049) receives prioritized bandwidth on a congested network, which is especially important in environments like the CAN/MAN networks discussed in earlier articles.

13. Python Example: Checking NFS Export Availability

The following Python script uses a simple socket check to verify whether the NFS port (2049) is open and reachable on the server before a client attempts to mount it — a handy pre-flight check.

import socket

def check_nfs_port(server_ip, port=2049, timeout=3):
    try:
        with socket.create_connection((server_ip, port), timeout=timeout):
            return True
    except (socket.timeout, ConnectionRefusedError, OSError):
        return False

server_ip = "192.168.1.100"

if check_nfs_port(server_ip):
    print(f"NFS server at {server_ip} is reachable on port 2049.")
else:
    print(f"NFS server at {server_ip} is NOT reachable on port 2049. Check firewall/service status.")

Sample Output:

NFS server at 192.168.1.100 is reachable on port 2049.

14. Comparison Table: NFS Export Options

OptionUse CaseSecurity Impact
roSharing reference data, documentationSafest, prevents accidental modification
rwCollaborative work directoriesRequires trust in client network
root_squashDefault for most exportsPrevents remote root from having full server access
no_root_squashBackup servers needing full file permissionsHigher risk, use only on trusted internal networks
syncFinancial/critical dataSafer, slightly slower writes
asyncTemporary/scratch dataFaster, risk of data loss on crash

15. Best Practices

  • Always restrict exports to specific subnets or IPs — never use * in production environments.
  • Prefer root_squash unless you have a specific, well-understood reason to disable it.
  • Use NFSv4 where possible for simplified firewall rules and better security (Kerberos support).
  • Combine NFS with proper firewall rules, restricting access to only the necessary client subnet.
  • Regularly back up /etc/exports and version-control it if managing multiple NFS servers.
  • Monitor NFS server load using tools like nfsstat to catch performance bottlenecks early.

16. Troubleshooting Common Issues

IssueCauseFix
mount.nfs: Connection timed outFirewall blocking port 2049 or server not runningCheck systemctl status nfs-server, verify firewall rules
mount.nfs: access denied by serverClient IP not included in /etc/exportsAdd correct client/subnet to the export entry, run exportfs -ra
Changes to /etc/exports not taking effectForgot to re-exportRun sudo exportfs -ra after every edit
Slow NFS performanceUsing sync on high-write workloads, or network congestionConsider async for non-critical data, check network QoS
“No such file or directory” on client mountExported path doesn’t exist or was mistypedVerify directory exists with ls -ld /srv/nfs/shared on the server

Quick diagnostic commands:

sudo exportfs -v                  # List all current exports
sudo systemctl status nfs-server  # Check NFS service status
rpcinfo -p localhost              # Check registered RPC services (NFSv3)
showmount -e localhost            # Show exports as seen locally

17. Advanced Concepts: NFS Security Hardening

Beyond basic export configuration, production NFS deployments benefit from additional security layers that go further than the default root_squash and subnet restrictions covered earlier.

Using Kerberos with NFSv4 (sec=krb5)

By default, NFS authenticates clients purely based on their IP address (sec=sys), which offers no real user-level authentication or encryption — anyone who can spoof or gain access to a trusted IP can potentially access the export. NFSv4 with Kerberos (sec=krb5, sec=krb5i for integrity checking, or sec=krb5p for full encryption) adds proper cryptographic authentication of individual users, not just client machines.

Example export line using Kerberos-based security:

/srv/nfs/secure    192.168.1.0/24(rw,sec=krb5p,no_subtree_check)

This configuration requires clients to authenticate via a Kerberos ticket and encrypts all NFS traffic (krb5p), providing both authentication and confidentiality — a significant security upgrade over the default IP-based trust model.

Restricting Exports with TCP Wrappers and Firewalls

In addition to the access rules defined directly in /etc/exports, administrators should layer host-based firewall rules (via iptables, nftables, or firewalld) to ensure that even if /etc/exports is ever misconfigured, unauthorized networks cannot reach the NFS ports at all. Defense in depth — combining application-level (/etc/exports) and network-level (firewall) restrictions — is a core security best practice.

Read-Only Root Exports for Immutable Data

For directories containing reference data, installation media, or compliance archives that should never change, exporting with ro (read-only) at the NFS level, combined with filesystem-level immutability (chattr +i on Linux), provides two independent layers of protection against accidental or malicious modification.

18. NFS vs. Other File Sharing Protocols

It’s useful to understand how NFS compares to alternative file-sharing protocols, since the right choice depends heavily on your operating system mix and use case.

ProtocolBest ForNative OS Support
NFSLinux/Unix-to-Linux/Unix file sharingNative on Linux/Unix, requires additional software on Windows
SMB/CIFSMixed Windows/Linux/macOS environmentsNative on Windows, well-supported everywhere else
SSHFSQuick, ad-hoc secure mounts over SSHWorks anywhere SSH is available, no dedicated server needed
iSCSIBlock-level storage (acts like a local disk, not a shared folder)Requires an initiator on the client and a target on the server

NFS remains the preferred choice in Linux-heavy environments — data centers, research clusters, and container storage backends — due to its maturity, performance, and tight integration with Unix-style permissions.

19. Monitoring and Auditing NFS Exports Over Time

Once an NFS export is live in production, ongoing monitoring is essential to catch performance degradation, unauthorized access attempts, or configuration drift before they become serious problems.

Monitor active NFS connections and operation counts:

sudo nfsstat -s

This command displays server-side statistics, including counts of read/write calls, and can help identify unusually high load from a specific client subnet.

Audit who is currently connected to your NFS exports:

sudo ss -tn | grep :2049

Log NFS mount and unmount events for auditing purposes by enabling verbose logging in rpc.mountd (part of the nfs-utils package), which records every client that mounts an export, along with the timestamp — valuable for security audits in regulated environments.

Periodically review /etc/exports for drift:

Configuration drift — where the live export rules on a server slowly diverge from documented policy due to ad-hoc changes — is a common issue in long-running infrastructure. Storing /etc/exports in a version-controlled configuration management system (Ansible, Puppet, or even a simple Git repository) ensures every change is tracked, reviewed, and reversible.

20. Frequently Asked Questions

Can I export the same directory to different clients with different permissions?

Yes. You can add multiple lines in /etc/exports for the same directory, each specifying a different client or subnet with its own options. For example, you might grant rw access to your internal admin subnet while granting only ro access to a broader internal network.

/srv/nfs/shared    192.168.1.0/24(ro,sync,no_subtree_check)
/srv/nfs/shared    192.168.1.50(rw,sync,no_subtree_check)

What happens if the NFS server goes offline while clients have it mounted?

Depending on the mount options used, client applications accessing the share may hang indefinitely (hard mount, the default) until the server returns, or fail immediately with an I/O error (soft mount). For most production use cases, hard mounts are preferred despite the temporary hang, because soft mounts risk silent data corruption if a write operation is interrupted mid-transfer.

Is NFS suitable for storing a live database’s data files?

Generally, no. Databases like MySQL or PostgreSQL typically expect strict, immediate file-locking guarantees that NFS — especially older versions or misconfigured setups — may not reliably provide, risking data corruption. Most database vendors explicitly recommend local or block-level storage (like iSCSI) over NFS for primary database files, reserving NFS for backups, logs, or shared application data instead.

How many clients can mount the same NFS export simultaneously?

There’s no hard protocol-level limit built into NFS itself; the practical ceiling depends on the server’s CPU, memory, disk I/O throughput, and network bandwidth. Large-scale deployments in research and enterprise environments routinely support hundreds of simultaneous client connections to a single, well-provisioned NFS server, often backed by high-performance storage arrays and 10 Gbps or faster network links.

21. Conclusion

Exporting a file system with NFS in Linux is a foundational, practical skill for anyone managing shared storage in a networked environment. By installing the NFS server package, defining directories and access rules in /etc/exports, applying the export with exportfs -ra, and properly configuring your firewall, you can securely share files across your network — whether that’s a small home lab or a university research cluster. In the next article, we’ll cover the client side of this process: how to actually mount and use these NFS exports from remote machines.

Whether you’re setting up a small home lab for shared media storage or architecting a multi-terabyte research data platform for a university department, the same core principles apply: carefully scope your export’s client access, choose sensible read/write and squash options, validate your configuration before restarting services, and layer network-level firewall rules on top of the application-level rules defined in /etc/exports. Mastering the export side of NFS is the foundation upon which all remote file access is built. Once you’re comfortable defining directories, access rules, and security options in /etc/exports, the natural next step — covered in depth in the following article — is understanding how client machines discover, mount, and interact with these exports in day-to-day use, completing the full picture of NFS-based file sharing across a network.

Further Reading

Total
2
Shares

Leave a Reply

Previous Post
how share files with NFS in Linux

How to Share Files with NFS in Linux

Next Post
GNU C Compiler in Linux

GNU C Compiler in Linux: Complete Installation and Usage Guide

Related Posts