Add bind mount to Dockerfile just like volume
Asked Answered
L

4

51

I want to add the bind mount to docker file just like I initialise a volume inside Dockefile. Is there any way for it?

Legging answered 22/12, 2017 at 13:2 Comment(0)
M
77

A Dockerfile defines how an image is built, not how it's used - so you can't specify the bind mount in a Dockerfile. Try using docker-compose instead. A simple docker-compose.yml that mounts a directory for you would look like this:

version: '3.1'

services:
  mycontainer:
    image: myimage
    build: .
    volumes:
      - './path/on/docker/host:/path/inside/container'  

The build: . is optional if you're building the image by some other means, but sometimes it's handy to do it all in one.

Run this with docker-compose up -d

Moniliform answered 22/12, 2017 at 13:18 Comment(4)
-d isn't requiredZanezaneski
how does the volume apply to windows machines - do I use a windows specific path? (windows with linux containers)Poilu
@Zanezaneski Actually -d is required to start the container in detached mode ... Otherwise it just locks up your terminal ...Felspar
@SiddharthSeth so what? Not required still.Zanezaneski
M
32

In addition to what the other answers say:

Because bind mounts provide access to the host filesystem, allowing them to be embedded into an image would be a huge security risk. Consider an image that purports to be, say, a web server, but in fact bind mounts your /etc/passwd and /etc/shadow and then sends them off to a remote server.

Or one that bind mounts /lib/ld-linux.so and then overwrites it, thus breaking your entire system.

For these reasons, you cannot embed a a bind mount in your Dockerfile. Similarly, you cannot specify host port mappings, host device access, or any other similar attributes in the Dockerfile.

Misery answered 22/12, 2017 at 13:19 Comment(0)
I
14

The simple answer is no.

A basic design principle for docker images is portability. Bind mounts are hosts specific since the mounted folder is defined on the host machine. Thus this contradicts the portability requirement for Docker images.

Idyllist answered 22/12, 2017 at 13:16 Comment(0)
B
5

I believe you can have a bind mount at build-time with https://docs.docker.com/engine/reference/builder/#run---mounttypebind

Example Dockerfile:

FROM ubuntu:22.04

RUN --mount=type=bind,source=.,target=/test ls -al /test

running it in the same folder with

docker buildx build . --progress plain --no-cache

will output this

#6 0.305 drwxr-xr-x 2 root root 4096 Oct  1 16:33 .
#6 0.305 drwxr-xr-x 1 root root 4096 Oct  1 16:33 ..
#6 0.305 -rw-r--r-- 1 root root   76 Oct  1 16:33 Dockerfile
Bergerac answered 1/10, 2023 at 16:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.