我有两个 docker-compose:
我需要一个网络让它们进行通信,并在主机上公开端口以便外部客户端也能够连接。
这是复制品。我制作了一个小型存储库来保存最小的复制品,因此您可以自己克隆并尝试:https://github.com/Yanis-F/reprod-dockercompose
server/
docker-compose.yml
:version: '3'
services:
my_server:
build: .
networks:
- my_network
ports:
- "3000:3000"
networks:
my_network:
external: true
Dockerfile
:
FROM node:14
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD [ "node", "index.js" ]
index.js
:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});
client/
docker-compose.yml
:
version: '3'
services:
my_client:
build: .
networks:
- my_network
networks:
my_network:
external: true
Dockerfile
:
FROM curlimages/curl:latest
WORKDIR /app
COPY script.sh .
CMD ["sh", "script.sh"]
script.sh
:
msg=$(curl localhost:3000)
echo "Message: $msg"
首先,我用
my_network
创建了虚拟网络docker network create my_network
。cd server/ && docker-compose up
启动服务器后,我想启动客户端。cd client/ && docker-compose up
时,出现错误:
Creating client_my_client_1 ... done
Attaching to client_my_client_1
my_client_1 | % Total % Received % Xferd Average Speed Time Time Time Current
my_client_1 | Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
my_client_1 | curl: (7) Failed to connect to localhost port 3000 after 0 ms: Couldn't connect to server
my_client_1 | Message:
client_my_client_1 exited with code 0
但是,如果我只是运行
cd client/ && sh script.sh
,它会起作用并给我:
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 13 100 13 0 0 1957 0 --:--:-- --:--:-- --:--:-- 2166
Message: Hello, World!
为什么我的服务
my_client
在client/docker-compose.yml
中无法到达my_server
中的服务server/docker-compose.yml
尽管他们共享同一个虚拟网络my_network
?sh client/script.sh
,连接就可以工作,我怎样才能让它从它运行的docker容器中工作?