Create a systemd SMB mount on Debian Linux
How to mount a persistent SMB/CIFS share on Debian-based Linux using a systemd .mount unit that survives reboots.
Recently while I was working in my homelab I came across the need to mount some SMB shares to my LXC containers. The shares needed to persist through reboots as well, and I wanted to create a systemd unit to accomplish these tasks.
-
Install
cifs-utilsvia apt:apt install cifs-utils -y -
Next we need to create a set of credentials for the CIFS share to use:
nano /root/.cifs_credentialsusername=usernamehere password=insertpasswordhere -
Create a directory to mount your CIFS share on:
mkdir -p /mnt/exampledir -
Identify the id of the user and group of your currently logged in user. In my case I was logged in as root.
id -u root && id -g rootSave the id from this command to be used in the next step.
-
Create the systemd unit:
nano /etc/systemd/system/mnt-media.mount -
Insert the following into the new
.mountfile:[Unit] Description=Media Server files Requires=network-online.target After=network-online.target [Mount] What=//192.168.0.1/media/ Where=/mnt/media Options=credentials=/root/.cifs_credentials,uid=0,gid=0 Type=cifs [Install] WantedBy=multi-user.target -
Enable
systemd-networkd-wait-online. This is a oneshot systemd service that waits for the network to be configured. Without this enabled, our new systemd service will fail to run on server boot up.sudo systemctl enable systemd-networkd-wait-online.service -
Enable the new systemd service:
systemctl enable mnt-media.mount -
Reboot your server for changes to take effect. If you experience any issues, check the
journalctllogs.