systemd Vagrant and VirtualBox: wait for synced folder to mount

I'm trying to setup a systemd service on a Vagrant box which requires the Vagrant synced folder to be mounted before starting.

Vagrantfile

Vagrant.configure(2) do |config|
    config.vm.box = "ubuntu/yakkety64"
    config.vm.synced_folder ".", "/usr/local/src"
    config.vm.provision "shell", path: "bootstrap/bootstrap"
end

/etc/systemd/system/my-server.service

[Service]
ExecStart=/usr/bin/node /usr/local/src/index.js
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=my-server
User=ubuntu
Group=ubuntu

[Unit]
Requires=remote-fs.target
After=vboxguest.service
After=virtualbox-guest-utils.service

[Install]
WantedBy=remote-fs.target

If I do not enable the my-server service, the synced folder is properly mounted. But when I attempt to enable the my-server service, the service fails to find the mounted files. If I then login to the Vagrant box, the folder is not mounted. It seems like the service's attempt to load files from that path interferes with Vagrant.

So, how do I wait for the folders to be mounted before my service starts?

Other solutions fall short in various ways, requiring manual intervention to start the service, which is unacceptable.


Solution 1:

I've just solved that kind of problem by adding:

[Install]
WantedBy=multi-user.target var-www-example.com.mount'

where var-www-example.com corresponds to:

config.vm.synced_folder ".", "/var/www/example.com"

in the Vagrantfile.

Thus, Vagrant has an XXX.mount systemd unit for each of its synced folder mount points. You can find yours with:

# systemctl list-units | fgrep .mount

Solution 2:

I had a similar issue where one of my systemd services required a vagrant synced filesystem be present prior to the service running to successfully start. I've worked around the problem by having a vagrant shell provisioner restart the service automatically on every start. This works because the provisioner runs after vagrant has mounted the synced filesystems.

config.vm.provision "shell", run: "always", inline: "systemctl restart my-server"

I'm not sure why your service would interfere with your synced filesystem. Vagrant syncs the folder that your vagrantfile is in by default to /vagrant. Could it have been mounted twice?