我运行基于节点映像的docker容器(来自Windows的Docker quickstart终端)
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
我启动Node客户端(在端口3000上)和Node(基于Express)服务器(在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)
})
}
它完全适用于主机(客户端访问localhost:3009并返回结果)。我可以打电话:3009并再次得到正确的结果。
但是当我构建并运行docker镜像时,它会失败。
docker run -p 3000-3009:3000-3009 --add-host="mongodb:192.168.12.151" MyDockerImage
--add-host
用于访问在主机上运行的mongo db。
服务器端口3009已暴露,因此我有一个工作技巧来调用
192.168.99.100:3009 //the docker IP and exposed port
而不是localhost:3009
,但让客户端直接在容器内访问服务器会很好。
如何在docker容器中正确指定localhost以访问兄弟服务?
更新
#!/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
答案 0 :(得分:1)
你可以做的事情很少
让其他容器在其他容器的网络上运行
docker run --net container:<id> MyDockerImage
现在您的mongodb可以在localhost上访问。但是端口需要在使用其网络的容器中公开
自己创建网络并使用它
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-compose将它们作为合成
运行version: '3'
services:
mongo:
image: mongodb
app:
build:
context: .
ports:
- "3000-3009:3000-3009"
现在在app mongodb中可以使用名称mongo
访问