如何使用docker-compose挂载主机目录,运行主机时指定“~/path/on/host”,不在docker-compose文件中

Bil*_*uth 2 environment-variables docker dockerfile docker-compose docker-volume

我想知道如何使用 docker-compose 挂载主机目录。

目前我只是使用一个普通的 Dockerfile,它工作正常。当我运行容器时,我只指定主机上的路径和容器上的路径。

docker run -d -p 3000:3000 -v ~/path/on/host:/path/on/container my-container
Run Code Online (Sandbox Code Playgroud)

我想使用 docker-compose 来实现这一点,但我不确定这是如何工作的。我的 docker compose 如下。

version: '3'

services:
  my-app:
    build:
      context: .
      dockerfile: ./path/to/Dockerfile
Run Code Online (Sandbox Code Playgroud)

另外,我需要在运行主机时指定 ~/path/on/host ,而不是在 docker-compose 文件中。

Mih*_*hai 5

version: '3'

services:
  my-app:
    build:
      context: .
      dockerfile: ./path/to/Dockerfile
    volumes:
      - ~/path/on/host:/path/on/container
    ports:
      - "3000:3000"
Run Code Online (Sandbox Code Playgroud)

然后您可以使用docker-compose up -d. 确保首先停止并删除您使用 docker 命令启动的容器,否则会发生冲突。

根据评论编辑:

创建一个包含以下内容的 .env 文件:

HOST_PATH=~/path/on/host
Run Code Online (Sandbox Code Playgroud)

并更改您的 docker-compose.yml:

version: '3'

services:
  my-app:
    build:
      context: .
      dockerfile: ./path/to/Dockerfile
    volumes:
      - ${HOST_PATH}:/path/on/container
    ports:
      - "3000:3000"
Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用。该目录始终为空。 (2认同)