Do NOT delete bind mounted volume inside Docker container indiscriminately

I don't think it's been talked about much so I should share why it's a very bad no good terrible horrible idea to delete a mounted directory inside your Docker container without thinking through it. I'm on Windows 10 but I imagine we might make the same shameful mistake on Unix too.

Imagine you run a Docker container with one of your precious directories on your host machine bind mounted into a container. Like so: docker run --rm --name con1 -v C:\Users\alex\Desktop:/dv1 -d ubuntu tail -f /dev/null.

Explanation:

  • docker run... ubuntu: run a container using the ubuntu image
  • --rm: delete the container upon its exit
  • --name con1: name the container "con1"
  • -v...: map the /dv1 directory in the container to the /Desktop directory on the host machine
  • -d: keep the container running as a daemon, that is, keep it running but give the terminal back to you
  • tail -f: this Unix command displays the last 10 lines of a file and then waits for new lines to display
  • /dev/null: this special device in Unix systems discards any information written to it
  • tail -f /dev/null: this waits in patience eternally for new lines from the deep dark oblivion of /dev/null, thereby keeping the container running

With this command, whatever you put into /Desktop on your host machine will be accessible in /dv1 inside the Ubuntu container and vice versa.

Here's how you might get a shell running in the container (src): docker exec -it container_name /bin/bash. You can also use sh instead of /bin/bash for Ubuntu. Now you're in the container's shell as root. You can do whatever you want! Almost.

One of the worst things I immediately did was assume that I could delete /dv1, the directory inside the container mapped to /Desktop in my host machine. So, I tried rm -rf dv1. Guess what happened.

It said: "rm: cannot remove 'dv1': Device or resource busy".

But at the same time, I saw files and folders on my desktop quickly disappearing one by one. Holy crap! I hit ctrl+c in panic.

It turns out, if you try removing the directory in your container mapped to the directory on your host machine that you've designated to be a Docker volume, it will delete everything inside that directory on your host machine. FUUUUUUUUUUUUUUUUUUUU.........

I lost a lot of important documents, including passwords and private keys to some servers. What an expensive lesson. But, y'know, if you collect enough tragedies, after a while you could hardly care less. So, onward ho, yeah?

Comments

There are currently no comments

New Comment

required

required (not published)

optional

required