有两个服务分布在两个 docker-compose communicate

问题描述 投票:0回答:0

我有两个 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容器中工作?

docker docker-compose docker-networking docker-network
© www.soinside.com 2019 - 2024. All rights reserved.