【发布时间】:2016-02-09 06:44:33
【问题描述】:
我正在使用 Docker Compose 在开发中运行 Elixir/Phoenix 应用程序。设置非常标准,带有一个 postgres 容器和一个 web 容器。
但是,我很难让 Web 容器与数据库容器通信。
这是我的网络容器Dockerfile:
FROM ubuntu:14.04
MAINTAINER me@example.com
RUN locale-gen en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update
RUN apt-get install -y wget
RUN apt-get install -y curl
RUN apt-get install -y inotify-tools
RUN apt-get install -y postgresql-client
RUN wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb \
&& dpkg -i erlang-solutions_1.0_all.deb
RUN curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash -
RUN apt-get install -y nodejs
RUN apt-get update
RUN apt-get install -y esl-erlang
RUN apt-get install -y elixir
RUN mix local.rebar
RUN mix local.hex --force
ADD . src/blog/
WORKDIR src/blog/
RUN mix deps.get
RUN mix deps.compile
这是我的docker-compose.yml:
db:
image: postgres
web:
build: .
command: mix phoenix.server
volumes:
- .:/src/blog
ports:
- "4000:4000"
links:
- db
当我运行docker-compose up 时,似乎一切正常。但是,当我尝试运行(创建数据库)时:
$ docker run blogphoenix_web mix ecto.create
我收到以下错误:
**(混合)无法创建 Blog.Repo 的数据库,原因是:psql:无法将主机名“db”转换为地址:名称或服务未知
然后,如果我检查 web 容器的主机文件:
$ docker run blogphoenix_web cat /etc/hosts
...我得到这个输出:
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.4 a86e4f02ea56
Docker Compose 不应该为db 容器创建主机名条目吗?
以下是我的 Docker 工具的一些相关版本号:
$ docker-machine --version
#=> docker-machine version 0.6.0, build e27fb87
$ docker-compose --version
#=> docker-compose version 1.6.0, build unknown
$ docker --version
#=> Docker version 1.10.0, build 590d510
编辑
好的,我刚刚注意到可能有助于其他人阅读本文的内容。这个命令docker run blogphoenix_web cat /etc/hosts 进入一个新容器,而这个命令docker exec 845f9d69cb1e cat /etc/hosts 进入一个正在运行的容器。 845f9d69cb1e 是 blogphoenix_web 镜像的运行版本的容器 ID。
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
845f9d69cb1e blogphoenix_web "mix phoenix.server" About an hour ago Up 2 minutes 0.0.0.0:4000->4000/tcp blogphoenix_web_1
21a6f48dfc3b postgres "/docker-entrypoint.s" About an hour ago Up 2 minutes 5432/tcp blogphoenix_db_1
运行exec 命令我从hosts 文件中得到预期的输出,显示db 容器的适当主机名链接:
$ docker exec 845f9d69cb1e cat /etc/hosts
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2 db_1 21a6f48dfc3b blogphoenix_db_1
172.17.0.2 blogphoenix_db_1 21a6f48dfc3b
172.17.0.2 db 21a6f48dfc3b blogphoenix_db_1
172.17.0.3 845f9d69cb1e
换句话说,当我运行docker run blogphoenix_web mix ecto.create 命令时,我正在基于blogphoenix_web 映像的新容器中执行mix ecto.create。这个新容器不是以docker-compose 启动的,因此没有与db 容器设置的适当主机文件链接。
【问题讨论】:
-
尝试运行“docker-compose run web mix ecto.create”,你应该有链接容器工作
-
哇,好吧,那行得通。谢谢你。但是,我认为 Docker Compose 为各种容器创建了一个主机条目,以便它们可以相互通信。如果没有,那么这种联系存在于哪里?
-
链接存在于容器之间,而不是图像之间。我在下面的答案中通过示例进行了解释。
标签: postgresql docker elixir docker-compose phoenix-framework