Tagdocker

Locally remount volumes from Docker to be used by local user using bindfs

#!/bin/bash
set -exou pipefail

# Location of the script (not the location from where it is executed from
THISDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

DOCKER_VOLUME_DIR=volumes  # This is the directory docker mounts to
LOCAL_DOCKER_VOLUME_DIR=localvolumes # This is the directory you want to locally mount to.
INSIDE_CONTAINER_USER=1000

# Bindfs is required
APP=bindfs; [ -x "`which ${APP}`" ] || sudo apt install ${APP}

# Create local directory to map volume to.
[ ! -d ${THISDIR}/${LOCAL_DOCKER_VOLUME_DIR} ] && mkdir -p ${THISDIR}${LOCAL_DOCKER_VOLUME_DIR}

# Unmount if already mounted
sudo umount ${THISDIR}/${LOCAL_DOCKER_VOLUME_DIR} || true

# Bet local users group
GROUP=`id -g -n $USER`

# Mount
sudo bindfs -u $USER -g "$GROUP" --create-for-user=${INSIDE_CONTAINER_USER} --create-for-group=${INSIDE_CONTAINER_USER} ${THISDIR}/${DOCKER_VOLUME_DIR} ${THISDIR}/${LOCAL_DOCKER_VOLUME_DIR}

Based on https://www.fullstaq.com/knowledge-hub/blogs/docker-and-the-host-filesystem-owner-matching-problem

Mount docker volume as same user as on host machine

docker containers often run as the root user (uid = 0, guid = 0). Files that the users generates are therefore also owned by the root user.

By creating an extra user on the docker system, and giving that user the same uid and guid as the user on you host system you will be able to modify your files without the need to be root on you host machine.

The following assumes you created an additional user in your docker container, and that it got 1000 for uid and guid.

#!/bin/bash

# Mr. R
# 06-2020

args=$@
cmd="builder.sh ${args}"

# current working directory is a volume mount to something on the host system.
# Therefore stat -c will provide the uid and gid of the host user.
# setting this uid and gid for the container user results in files written to the
# volume as host user.
usr=`id -nu 1000`
grp=`id -ng 1000`
groupmod -g $(stat -c "%g" .) $grp
usermod -u $(stat -c "%u" .) -g $(stat -c "%g" .) $usr

# Force all volume mounts to be of the appuser!
chown -R ${usr}:${grp} ${WORKDIR}

# If nothing given, start a shell, else run the builder script with arguments.
if [ "x${args}x" == "xx" ]; then
  cmd="/bin/bash"
fi

su -m -c "PATH=${PATH}; ${cmd}" ${usr}

© 2025 Roholt

Thema door Anders NorénOmhoog ↑