Access file structure present in host with Docker

2019-02-19 22:03发布

问题:

If i want my docker image to directly take data from a folder which is present in my system, is that possible.

If yes then how can I do it.

Thanks.

回答1:

The usual practice is to use docker volume (bind mount) at runtime.

docker run -d \
  -it \
  --name devtest \
  --mount type=bind,source="$(pwd)"/target,target=/app \
  nginx:latest

That way, your container, inside /app, has access to your host path (here $pwd/target)

In a docker-compose file, see docker compose volume syntax:

This example shows:

  • a named volume (mydata) being used by the web service,
  • and a bind mount defined for a single service (first path under db service volumes).
version: "3.2"
services:
  web:
    image: nginx:alpine
    volumes:
      - type: volume
        source: mydata
        target: /data
        volume:
          nocopy: true
      - type: bind
        source: ./static
        target: /opt/app/static

  db:
    image: postgres:latest
    volumes:
      - "/var/run/postgres/postgres.sock:/var/run/postgres/postgres.sock"
      - "dbdata:/var/lib/postgresql/data"

volumes:
  mydata:
  dbdata:

In your case, use:

- "/path/to/local/folder/on/host:/path/within/your/container"


回答2:

If you use docker-compose you can define volumes to share folders from your system. In example bellow the mysql will use ./data/db/mysql folder to store/read data (because as default it uses /var/lib/mysql in linux).

Also you must to be sure that provided volume has correct permissions and docker have read/write access to it.

version: "3"

services:    
    nginx:
        ......

    php:
        ........

    mysql:
        .........
        volumes:
            - "./data/db/mysql:/var/lib/mysql"