[英]Docker Compose: Allow images to access host resources (like postgresql)
Our infrastructure uses Docker containers to separate our services. 我们的基础架构使用Docker容器来分隔我们的服务。 I'm beginning to set up our docker-compose to aid in local development. 我开始设置我们的docker-compose来帮助本地开发。
Some of our services use the Ruby on Rails framework, and developing locally for that is quickest by running the server and database locally (traditional Rails development). 我们的某些服务使用Ruby on Rails框架,因此通过在本地运行服务器和数据库来进行本地开发最快(传统的Rails开发)。
To more closely mimic the production environment, docker-compose would be useful. 为了更紧密地模仿生产环境,docker-compose会很有用。 Our database is not ephemeral (are they ever :P) and thus we don't run them as docker containers. 我们的数据库不是临时数据库(它们曾经是:P),因此我们不将它们作为docker容器运行。
Given that, how can I construct my docker-compose to allow the Rails container to connect to the host's database (Postgresql in this case)? 鉴于此, 我该如何构造docker-compose以允许Rails容器连接到主机的数据库 (在这种情况下为Postgresql)? There are a lot of data in the local database that would be useful in smoke-testing the application. 本地数据库中有很多数据,这些数据将对应用程序进行烟雾测试。
I guess you don't want to access the host's IP address inside the server
container manually. 我猜您不想手动访问server
容器内主机的IP地址。
What you can use is extra_hosts
and export the hosts IP address as an environment variable: 您可以使用extra_hosts
并将主机的IP地址导出为环境变量:
service:
image: alpine:3.4
extra_hosts:
- "host:${HOST_IP}"
command: cat /etc/hosts
Unfortunately docker-compose
does not support something like "host:$(ip -4 addr show ...)"
. 不幸的是, docker-compose
不支持"host:$(ip -4 addr show ...)"
。 So for this to work each developer must edit their .bashrc
(or whatever they are using). 因此,要使其正常工作,每个开发人员必须编辑其.bashrc
(或他们使用的任何.bashrc
)。
On my machine this gives me the correct local IP address: 在我的机器上,这为我提供了正确的本地IP地址:
ip -4 addr show|grep brd|egrep -o 'inet ([0-9]+\.){3}[0-9]+'|cut -d ' ' -f2
Alternative : 替代方案 :
Or you could just configure the database to listen on the docker0
interface as well and edit your docker-compose.yml
to look like this: 或者,您也可以将数据库配置为也监听docker0
接口,然后编辑docker-compose.yml
,如下所示:
service:
image: alpine:3.4
extra_hosts:
- "host:172.17.0.1"
command: cat /etc/hosts
The best way to do this would be to run the database in a container. 最好的方法是在容器中运行数据库。
database is not ephemeral and thus we don't run them as docker containers. 数据库不是临时的,因此我们不将它们作为docker容器运行。
This statement is incorrect. 这句话是不正确的。 You can run a database in a Docker container. 您可以在Docker容器中运行数据库。 Just make sure you use a volume to store the data in a well known directory on the host. 只要确保使用卷将数据存储在主机上的知名目录中即可。 That way if the database stops, it will come back up with the same data. 这样,如果数据库停止,它将返回相同的数据。
Once you have the database in a container it is very easy to connect to it from other containers. 将数据库放在容器中后,很容易从其他容器连接到数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.