Docker Bind Mounts
dockerd(8) uses bind mounts to mount a host file or directory into a container.
Compare to Volumes.
Mounts
The syntax for mounting a file or directory into a container is:
docker run --detach --name=my-nginx \ --mount type=bind,src=/absolute/path/to/web/root,dst=/usr/share/nginx/html,readonly \ --mount type=bind,src=/absolute/path/to/app/binary,dst=/app,readonly \ nginx:latest
Note that the host file or directory must exist; an error will be raised otherwise.
When a bind mount targets an existing and non-empty directory in a container, the contents of that directory are obscured.
Permissions and Ownership
By default, a container runs as root. Leaving aside security concerns, this can mask issues of file permissions and ownership.
A container can be made to run as a different user by any of:
Setting a different USER in the Dockerfile
Creating the container with a --user UID:GID option
The first approach is simpler and more explicit.
FROM alpine:latest RUN addgroup -S appgroup && adduser -S appuser -G appgroup USER appuser
However, this approach can lead to issues when used in conjunction with a bind mount. Files and directories created by the container may be owned by non-existant users on the host.
The second approach is flexible and behaves more intuitively, but requires attention every time the container is created.
docker run --interactive --tty --rm \ --user="$(id -u):$(id -g)" \ alpine:latest
Other users can also be specified (like postgres), but they would need to exist and use the same UID on both the host and container.
Volumes
An alternative syntax for mounting a file or directory is:
docker run --detach --name=my-nginx \ --volume /absolute/path/to/web/root:/usr/share/nginx/html:ro \ --volume /absolute/path/to/app/binary:/app:ro \ nginx:latest
This syntax is much shorter but...
the option is poorly named, as it can easily be confused with Volumes, which are a separate concept
if the host file or directory does not exist, dockerd(8) creates it as a directory on the host
Nonetheless the --volume option is frequently used in documentation.
Docker Compose
To use a bind mount with Docker Compose, try:
services: web: image: nginx volumes: - type: bind source: /absolute/path/to/web/root target: /usr/share/nginx/html read_only: true