Skip to content

Instantly share code, notes, and snippets.

@nickovs
Created April 17, 2022 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickovs/d236368bd431d3bedbe4e3ee1a7d0ddb to your computer and use it in GitHub Desktop.
Save nickovs/d236368bd431d3bedbe4e3ee1a7d0ddb to your computer and use it in GitHub Desktop.
A script to mount a host directory into a running Docker container
#!/bin/bash
# A script for mounting a host directory into a running Docker container
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <container> <host path> <target path>"
exit 1
fi
CONTAINER=$1
SOURCE_DIR=$2
DEST_DIR=$3
REMOUNTS_DIR=/remounts
# Get the PID of the container into which we will mount
CONTAINER_PID=$(docker inspect --format {{.State.Pid}} $CONTAINER)
ENTER_ARGS="--target $CONTAINER_PID --mount --uts --ipc --net --pid --"
# Get the canonical location of the source
REAL_SOURCE=$(readlink -f $SOURCE_DIR)
# Find the device on which it resides, and where it is mounted
read SOURCE_DEV HOST_MOUNT_POINT <<< $(df --output=source,target $REAL_SOURCE | sed -e 1d)
MOUNT_TAIL=${REAL_SOURCE#*$HOST_MOUNT_POINT}
# Find the device major and minor numbers
read DEV_MAJOR DEV_MINOR <<< $(lsblk -n -o "MAJ:MIN" $SOURCE_DEV | tr ":" " ")
# Make the device if it doesn't already exist
nsenter $ENTER_ARGS test -b $SOURCE_DEV || nsenter $ENTER_ARGS mknod --mode 0600 $SOURCE_DEV b $DEV_MAJOR $DEV_MINOR
# Make sure we have somewhere to mount things and make a mountpoint
nsenter $ENTER_ARGS test -d $REMOUNTS_DIR || nsenter $ENTER_ARGS mkdir $REMOUNTS_DIR
DEST_MOUNT_PATH=$(nsenter $ENTER_ARGS mktemp --directory --tmpdir=$REMOUNTS_DIR)
# Mount the actual device
nsenter $ENTER_ARGS mount $SOURCE_DEV $DEST_MOUNT_PATH
# Bind-mount the requested path to the desired location
nsenter $ENTER_ARGS test -d $DEST_DIR || nsenter $ENTER_ARGS mkdir $DEST_DIR
nsenter $ENTER_ARGS mount --bind $DEST_MOUNT_PATH$MOUNT_TAIL $DEST_DIR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment