How to Mount NFS Storage for Docker Containers
Purpose
Mount a remote NFS share on a Linux server for use by Docker containers, ensuring stable operation, correct permissions, and automatic remounting.
1. Install NFS Client on the Server
sudo apt update
sudo apt install nfs-common -y
2. Create a Local Mount Directory
Create a local directory where the NFS share will be mounted:
sudo mkdir -p /srv/nfs-mount
sudo chown $(whoami):$(whoami) /srv/nfs-mount
(You can replace /srv/nfs-mount
with your preferred path.)
3. Mount the NFS Share (Manual Test)
Example:
sudo mount -t nfs4 192.168.100.11:/mnt/hdd-storage/my-nfs-share /srv/nfs-mount
nfs4
: Use NFS version 4 for better performance and locking.proto=tcp
: Reliable transport.hard
: Wait for server recovery instead of failing immediately.timeo=600
: Timeout setting for NFS.retrans=2
: Retry failed operations twice.sec=sys
: Default authentication security._netdev
: Only mount after network is ready.
4. Verify That the Mount Worked
mount | grep nfs
You should see:
192.168.100.11:/mnt/hdd-storage/my-nfs-share on /srv/nfs-mount type nfs4 (...)
5. Make the Mount Persistent (Auto-Mount on Boot)
Edit your /etc/fstab
file:
sudo nano /etc/fstab
Add the following line:
192.168.100.11:/mnt/hdd-storage/my-nfs-share /srv/nfs-mount nfs4 rw,relatime,hard,proto=tcp,timeo=600,retrans=2,sec=sys,_netdev 0 0
Save and exit (Ctrl+O
, Enter
, Ctrl+X
).
6. Test the fstab Entry Without Rebooting
sudo mount -a
No errors = success ✅
7. Using the NFS Mount with Docker
When running your containers, bind-mount your NFS storage into the container:
docker run -d \
--name my-container \
-v /srv/nfs-mount:/app/data \
my-docker-image
This will allow your Docker containers to directly access the NFS storage.
✅ Summary
- Use NFSv4 (
nfs4
) whenever possible. - Always include
_netdev
in/etc/fstab
. - Use
hard
mounts to protect container file operations during NFS server issues. - Bind-mount the NFS path inside containers carefully.
- Avoid using NFS for databases unless network latency is very low.
🛠️ Useful Commands
- Mount NFS manually:
sudo mount -t nfs4 server:/path /mountpoint
- Check current NFS mounts:
mount | grep nfs
- Reload fstab:
sudo mount -a
🧠 Additional Notes
- If the NFS server reboots, containers may pause if heavily dependent on storage.
- When using Compose (
docker-compose.yml
), define volumes mapped to NFS mount points. - For production, consider using systemd mount units for even better recovery handling.
No Comments