- Published on
Mounting a Host Folder in a Docker Container
- Authors
- Name
- Yair Mark
- @yairmark
A few days ago I containerized an application as the requirements to run it could easily have broken my system (it required installing a very specific version of Openssl as well as a number of other dependencies). The problem I had was that I now needed to point Python scripts to the artifacts running in the docker container.
I first started by using screen with multiple tabs to edit in one tab and run the code in another tab on the container. But this proved to be a pain as I had to keep copying the changes I made in the container to the host so I would not lose it when I deleted the container.
After a bit of searching I found you can use what is called a bind mount to mount a host folder into the container. This can be done using the more succinct -v
flag or the more verbose but clearer --mount
flag - I opted for the mount flag as I generally prefer clarity.
For this entire containerization process I created a makefile
to streamline my development process and it also allowed me to automate the mounting of a directory in the repo. The target that runs the container was written so that it would work from any developer's machine regardless of their system setup (as long as it was Linux/Unix/Cygwin) as it mounted a folder in the code repo. The makefile
target I used is:
run: build ## Run the built image
docker run -d -t --name any-name-that-makes-sense --mount "type=bind,source=$(shell pwd)/python-sandbox,target=/root/sandbox" $(CONTAINER_NAME):latest
This makefile
sat in the root of the repo as well as the python-sandbox
folder. Docker requires an absolute path for the source folder hence ./python-sandbox
will not work. As this is being run in a makefile
you have to run commands in a subshell pre-pended by the shell command which is the reason for $(shell pwd)
. The full makefile
I used can be found below:
CONTAINER_NAME?=foo-bar
help:
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
build: ## Build the docker image
docker build -t $(CONTAINER_NAME) .
run: build ## Run the built image
docker run -d -t --name any-name-that-makes-sense --mount "type=bind,source=$(shell pwd)/python-sandbox,target=/root/sandbox" $(CONTAINER_NAME):latest
clean: ## Stop and delete the container
docker rm -f soft-hsm