从docker集装箱的服务访问兄弟服务

我运行基于节点图像的docker容器(从Windows的Docker快速启动terminal)

FROM node:7.8.0 ENV NPM_CONFIG_LOGLEVEL warn VOLUME /tmp #copy server source /piu contains node server and /piu/client contains react+redux client ADD piu /piu ADD server_start.sh / #clean windows \r char to make the .sh file real executable RUN sed -i -e 's/\r$//' server_start.sh CMD ./server_start.sh EXPOSE 3000 3009 

我启动节点客户端(端口3000)和节点(基于快速)服务器(在3009端口)。 客户端通过AJAX调用访问REST服务器。

 componentDidMount() { const that = this; console.log('SERVER_URL=' + SERVER_URL); //the output is localhost:3009 axios .get(SERVER_URL + '/posts') .then(res => { that.setState({pageInfo: res.data}); }) .catch(err => { console.log(err) }) } 

它从主机(客户端访问本地主机:3009并返回结果)完美的作品。 我可以打电话:3009,并再次得到正确的结果。

但是当我build立和运行docker图像失败。

 docker run -p 3000-3009:3000-3009 --add-host="mongodb:192.168.12.151" MyDockerImage 

--add-host用于访问在主机上运行的mongo数据库。

服务器端口3009是暴露的,所以我有一个工作的技巧来调用

 192.168.99.100:3009 //the docker IP and exposed port 

而不是localhost:3009但会很高兴让客户端访问直接在容器内的服务器。

如何在Docker容器内正确指定localhost来访问兄弟服务?

UPDATE

 #!/bin/bash # Start the first process (server) npm run start_docker --prefix piu & status=$? if [ $status -ne 0 ]; then echo "Failed to start my_first_process: $status" exit $status fi # Start the second process (client) npm run start --prefix piu/client status=$? if [ $status -ne 0 ]; then echo "Failed to start my_second_process: $status" exit $status fi 

你可以在这里做几件事情

让其他容器在其他容器的networking上运行

 docker run --net container:<id> MyDockerImage 

现在您的mongodb将在本地主机上访问。 但是端口需要暴露在使用networking的容器中

自己创buildnetworking并使用它

 docker network create myapps docker run --name mongodb_service --net myapps mongodb docker run -p 3000-3009:3000-3009 --net myapps MyDockerImage 

现在在MyDockerImage中,可以通过mongodb_service访问mongodb

使用docker撰写

您可以使用docker-compose将它们作为组合运行

 version: '3' services: mongo: image: mongodb app: build: context: . ports: - "3000-3009:3000-3009" 

现在在应用程序MongoDB将可以与名称mongo