从组合容器访问dockerfile的卷

时间:2019-03-08 18:29:31

标签: docker docker-compose docker-volume

我是Docker的新手,一直在尝试实现以下目标,但似乎无法使其正常工作。

我想创建一个图像来保存一些静态文件。然后,我想从另一个容器访问包含静态文件的文件夹。

为此,我首先使用以下信息创建了一个dockerfile:

FROM alpine
WORKDIR /usr/local/apache2/htdocs
ADD static /usr/local/apache2/htdocs
VOLUME /usr/local/apache2/htdocs

然后我通过运行以下命令从该dockerfile创建了映像:

docker build -t customimage .

然后在我的docker-compose.yaml中启动以下两个服务:

version: '3.7'
services:
    custom:
        image: customimage:latest
        tty: true
    apache:
        image: httpd:latest
        volumes:
            - /usr/local/apache2/htdocs
        ports: 
            - "80:80"

在完成docker-compose之后,两个服务都启动了,但是我无法从apache容器的customimage访问卷。

我在这里想念什么?我知道我可以使用运行命令,但是我更喜欢使用docker-compose,因为将来我会添加更多服务。

1 个答案:

答案 0 :(得分:1)

我建议您声明一个docker卷以在两个容器之间共享。然后可以使用卷路径中的一些数据来预先构建其中一个容器。然后,另一个容器可以装入相同的卷,并且将看到相同的数据。

这里需要注意的一个非常重要的细节是-如果将卷中的文件绑定到容器的文件系统中已经存在其他文件的位置,则在安装容器中将看不到该文件。 它必须是一个空的位置!

要为您完成这项工作,您需要为httpd映像创建一个Dockerfile,因为我们需要在将要绑定的卷中的文件可见之前清除目标位置。

解决方案

我建议这样的项目布局:

/
├─ data.Dockerfile
├─ docker-compose.yml
├─ httpd.Dockerfile
├─ index.html 

这是在httpd容器中运行的最小网站的示例,该网站通过主机安装的卷为网站提供服务。一个也安装在一个补充“数据容器”中的卷,该卷已预先填充了该网站(为了使内容简短,使用了一个index.html文件)

以下是文件的内容:

data.Dockerfile

FROM alpine

# declare a volume at location /var/shared_volume
VOLUME /var/shared_volume
# copy your new great site into the volume location
COPY index.html /var/shared_volume/

# configure an entrypoint that does not terminate, to keep the container up
ENTRYPOINT [ "tail", "-f", "/dev/null" ]

httpd.Dockerfile

FROM httpd:latest

# remove any file and directory at the location where we wantt serve 
# the static content 
RUN rm -rf /usr/local/apache2/htdocs/*

# declare the path as a volume
VOLUME /usr/local/apache2/htdocs

docker-compose.yml

version: "3.7"

# declare the volume to share between the containers
volumes:
  shared_volume:

services:
  data:
    build:
      context: ./
      dockerfile: data.Dockerfile
    container_name: data
    volumes:
      - "shared_volume:/var/shared_volume"
  httpd:
    build:
      context: ./
      dockerfile: httpd.Dockerfile
    container_name: httpd
    volumes:
      - "shared_volume:/usr/local/apache2/htdocs"
    ports:
      - "80:80"

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Is this page visible in your httpd container?</title>
  </head>
  <body>
    <h1>I sure hope you can see this page?</h1>
  </body>
</html>

shared_volume现在将是在主机上管理的docker卷。两个容器都将其安装到各自文件系统中的路径。

运行示例

docker-compose up,运行时请访问http://localhost

我已经创建了a gist with the solution here.


简短地说,直接从一个容器安装到另一个容器

如果要将目录直接从“数据容器”挂载到apache容器中-则会遇到很多问题。最好在以下问题的答案中对此进行解释:Mounting nfs shares inside docker container