My question is exactly this SO post, except the answer works using docker-compose version '2' for the client, but not version '3'.
I have two docker-compose:
- One for my server, which consists of multiple microservices.
- One for my client, which also consists of multiple microservices.
I need a network to have them communicate, and to expose the port on the host machine for external clients to also be able to connect.
Here is a reproduction. I made a small repository to hold the minimal reproduction so you can clone and try it yourself: 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"
First, I created the virtual network my_network with docker network create my_network.
Then After launching the server with cd server/ && docker-compose up, I want to launch the client.
When running cd client/ && docker-compose up, I get the error:
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
However, if I just run cd client/ && sh script.sh, it works and give me:
  % 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!
Why is my service my_client in the client/docker-compose.yml not able to reach for the service my_server in the server/docker-compose.yml despite them sharing the same virtual network my_network ?
The connection works if I launch the script sh client/script.sh from the host machine, how can I also get it to work from the docker container it runs in ?
