我是 Docker 的新手,我正在尝试了解如何通过在 Docker 容器内运行的代码与 Docker 卷交互。
我有一个非常基本的 Ruby 程序需要创建一个文件。我希望程序创建的文件在运行之间保持不变。我在想,为了实现这一点,我需要使用 Docker 卷。
这是我的 Dockerfile:
FROM ruby:2.1
RUN mkdir /app
WORKDIR /app
ADD . /app/
RUN bundle install -j 8
VOLUME ["app/data"]
ENTRYPOINT ["./bin/app.rb"]
现在我有了一个卷,我的 ruby 程序将如何写入该位置?
如果我要在程序中执行以下操作:
config_file = "some/directory/config.yml"
File.open(config_file, 'w') { |file| file.write("Hello, from Docker!") }
我的问题是,我是否会像 config_file = "app/data"
那样引用卷,Ruby 和 Docker 会知道目录“app/data”位于卷中?
最佳答案
是的,你是对的。您在此路径中创建/修改的文件将保留在您的主机文件系统中。因此,它们在容器生命周期中存活下来。
要详细了解 docker 卷,请查看 here .
[...] Docker images are stored as series of read-only layers. When we start a container, Docker takes the read-only image and adds a read-write layer on top. If the running container modifies an existing file, the file is copied out of the underlying read-only layer and into the top-most read-write layer where the changes are applied. The version in the read-write layer hides the underlying file, but does not destroy it.
您可以通过键入 docker volume ls
列出 docker
已知的所有卷。如果您想获得有关特定卷的更多信息,例如主机系统的挂载点运行docker volume inspect VOLUME_NAME
命令。
要仅检索有关其已安装卷的容器特定信息,请执行:
docker inspect -f '{{ .Mounts }}' CONTAINER_NAME
我强烈建议您使用命名卷,因为我发现它们更易于识别和管理。否则,卷名称将是一个自动生成的加密哈希。
大多数情况下,我在我的 docker-compose.yml
中定义它们:
volumes:
postgres_data: {}
services:
postgres:
image: postgres
volumes:
- postgres_data:/var/lib/postgresql/data
# ... other services like web, celery, etc.
关于ruby - 如何从代码中引用 Docker 卷?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49059276/