如何通过本地主机连接两个Docker容器? [英] How to connect two docker containers through localhost?
问题描述
我有两个服务在单独的容器中运行,一个是grunt(application),运行在端口9000上,另一个是sails.js(服务器),运行在端口1337上.我想尝试做的是让客户端运行应用程序通过localhost:1337与服务器连接.这可行吗?谢谢.
I have two services running in separate containers, one is grunt(application) and runs off port 9000 and the other is sails.js (server) which runs off port 1337. What I want to try to do is have the client app connect with the server through localhost:1337. Is this feasible? Thanks.
推荐答案
主机
您将无法使用localhost
连接到另一个容器(因为localhost
是当前容器),但是您可以通过容器主机(运行容器的主机)进行连接.在您的情况下,您需要boot2docker VM IP(echo $(boot2docker ip)
).为此,您需要在主机级别公开端口(使用-p 1337:1337
进行此操作).
HOST
You won't be able to connect to the other container with localhost
(as localhost
is the current container) but you can connect via the container host (the host that is running your container). In your case you need boot2docker VM IP (echo $(boot2docker ip)
). For this to work, you need to expose your port at the host level (which you are doing with -p 1337:1337
).
最常用的另一种解决方案是链接容器.
Another solution that is most common and that I prefer when possible, is to link the containers.
您需要将--name标志添加到服务器docker run
命令中:
--name sails_server
You need to add the --name flag to the server docker run
command:
--name sails_server
您需要将--link标志添加到应用程序docker run
命令中:
--link sails_server:sails_server
You need to add the --link flag to the application docker run
command:
--link sails_server:sails_server
在您的应用程序内部,您将可以通过sail_server:1337
访问服务器
您还可以使用环境变量来获取服务器IP.查看文档: https://docs.docker.com/userguide/dockerlinks/
And inside your application, you will be able to access the server at sail_server:1337
You could also use environment variables to get the server IP. See documentation: https://docs.docker.com/userguide/dockerlinks/
您的运行命令可能开始有点长...在这种情况下,我喜欢使用 docker-组成,使我可以在一个文件中定义容器及其关系(卷,名称,链接,命令...).
Your run commands may start to be a bit long... in this case I like to use docker-compose that allows me to define my containers and their relationships (volumes, names, link, commands...) in one file.
这篇关于如何通过本地主机连接两个Docker容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!