Skip to content

Instantly share code, notes, and snippets.

@djw4
Last active August 17, 2022 06:56
Show Gist options
  • Save djw4/207e43d04e04979dd224a935f1764a2c to your computer and use it in GitHub Desktop.
Save djw4/207e43d04e04979dd224a935f1764a2c to your computer and use it in GitHub Desktop.
Check if NAS is mounted before starting docker-compose
  1. Install htpc.service to /etc/systemd/system/htpc.service

    Note: I run the HTPC services as the user htpc so amend the service file appropriately if needed.

  2. Create service.sh in the same location as referenced by the systemd service and ensure it is executable.

    Note: This should also be where your docker-compose.yml file exists.

  3. Create settings.env in the same directory as service.sh.

  4. Modify settings.env so that the mount directory is referenced per your requirements.

  5. Create the file .mounted in the root of the mount by running touch .mounted in the correct place (/mnt/multimedia for me - update settings.env as needed).

  6. (Optional) Update /etc/sudoers so that the unprivileged user can restart the systemd service without a password, by adding this line (update as needed): %htpc ALL=NOPASSWD: /bin/systemctl * htpc*

  7. Reload systemd and enable the service: sudo systemctl daemon-reload && sudo systemctl enable htpc.service

  8. Start the service with sudo systemctl start htpc.service

Now when the service starts up, the script will simply check if that .mounted file exists (which should only exist on the network share, not on the local disk) and if the file is absent, the docker-compose services won't start.

[Unit]
Description=HTPC Services
After=network.target
After=systemd-user-sessions.service
After=network-online.target
[Service]
User=htpc
Type=exec
WorkingDirectory=/home/htpc
ExecStart=/home/htpc/service.sh start
ExecStop=/home/htpc/service.sh stop
TimeoutSec=30
Restart=always
RestartSec=10
StartLimitBurst=5
#StartLimitInterval=350
#OnFailure
[Install]
WantedBy=multi-user.target
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
# Source settings
. ${SCRIPT_DIR}/settings.env
export SCRIPT_DIR
check_mount() {
if [ -f ${MNT_LOCK_FILE} ]; then
echo "SUCCESS: ${MNT_DIR} is correctly mounted"
else
echo "FAILED: ${MNT_DIR} does not appear to be mounted"
exit 1
fi
}
case $1 in
start)
echo "Starting services"
cd ${SCRIPT_DIR}
check_mount
docker-compose up
;;
stop)
echo "Stopping services"
cd ${SCRIPT_DIR}
docker-compose down
exit 0
;;
*)
echo "ERROR: Unknown option: $1"
exit 1
;;
esac
MNT_DIR=/mnt/multimedia
MNT_LOCK_FILE=${MNT_DIR}/.mounted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment