CodeBlanks Logo Icon CodeBlanks

Bind mounts

Learn to mount host directories with bind mounts.

Bind mount

A bind mount mounts a folder or file on the host directly into the container. The source must be a path (starting with /, ./ or $PWD). In development it's used to mount code into the container; the container sees the change the moment you save the file:

docker run -d --name web -p 8080:80 -v "$PWD/site":/usr/share/nginx/html:ro nginx
# edit site/index.html, refresh the browser

Mounting files and permissions

A single configuration file can be mounted too. In a bind mount, files carry the host's ownership and permissions; if the container runs as a non-root user, write permission problems can occur:

docker run -d -v "$PWD/nginx.conf":/etc/nginx/nginx.conf:ro nginx
docker run --rm -u "$(id -u):$(id -g)" -v "$PWD":/app -w /app node:20 npm run build

The second command makes the created files belong to your user instead of root.

Practice A site developed live

Start a container named web from nginx in the background: map host 8080 to container 80; mount the site folder in the current folder ("$PWD/site") read-only at /usr/share/nginx/html.

Starter code

terminal
# buraya yaz

Expected output

6f708192a3b4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the main difference between a bind mount and a named volume?

  • A bind mount is more persistent
  • A volume is read-only
  • There's no difference
  • A bind mount uses a specific host path; Docker manages a volume Correct answer

Explanation: Volumes for production data and bind mounts for code in development are typical.

2 Mount the current folder at /app.

Question
docker run --rm -v ____:/app -w /app node:20 npm test
Answer
docker run --rm -v "$PWD":/app -w /app node:20 npm test

Explanation: $PWD is the full path of the current folder.

3 Match.

Term Meaning
-v "$PWD":/app Bind mount
-v data:/app Named volume
:ro Read-only
-u "$(id -u)" Fix for file ownership

All lessons in Beginner