我运行基于节点映像的 docker 容器(来自 Windows 的 Docker 快速启动终端)
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