If you're under linux and have enough privileges, there's a way to attach a bind mount to a running container.
See e.g. https://brauner.io/2023/02/28/mounting-into-mount-namespaces.html for more info.
Here's a working example following above blog post.
The program takes 3 arguments: host directory, container directory and any pid of some program currently running in the container. To find the latter, do docker inspect --format '{{ .State.Pid }}' container_name.
It's easiest to run the program with sudo.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sched.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/mount.h>
#include <errno.h>
#include <sys/syscall.h>
int main(int argc, char **argv)
{
if (argc != 3) {
printf("usage: ./a.out pid src_dir dst_dir\n");
printf("To get the PID of a docker container, run `docker inspect --format '{{ .State.Pid }}' container_name`\n");
return 0;
}
char *pid = argv[1];
char *src_dir = argv[2];
char *dst_dir = argv[3];
// Create a new virtual mount of src_dir and save the file descriptor in fd_mnt
int fd_mnt;
fd_mnt = syscall(__NR_open_tree, AT_FDCWD, src_dir, OPEN_TREE_CLONE);
if (fd_mnt < 0) {
perror("open_tree failed");
return 1;
}
// get the name space ID of the container and save it as `fd_nmtns`
char mount_namespace[1000];
snprintf(mount_namespace, 1000, "/proc/%s/ns/mnt", pid);
int fd_mntns = open(mount_namespace, O_RDONLY);
if (fd_mntns < 0) {
printf("open /proc/%s/ns/mnt failed: %s", pid, strerror(errno));
return 1;
}
// Switch to the name space of the container
setns(fd_mntns, 0);
// Mount the virtual file descriptor we created before inside the container namespace
int ret = syscall(__NR_move_mount,
fd_mnt, "", AT_FDCWD, dst_dir, MOVE_MOUNT_F_EMPTY_PATH );
if (ret < 0) {
perror("move_mount failed");
printf("Ensure the folder dst_dir exists inside the container");
return 1;
}
printf("mounted %s to %s of namespace %s,", src_dir, dst_dir, mount_namespace);
return 0;
}
docker exec -it d1a2cc990208 bashfrom the same location, I was in the container with the mounted volume.