如何正确设置 docker 网络以使用 localhost 连接?

How to correctly set up docker network to use localhost connection?

我有两个服务。服务 A 像这样调用服务 B:

HttpGet request = new HttpGet("http://127.0.0.1:8083/getTest");
HttpResponse httpResponse = httpClient.execute(request);

我有错误:

There was an unexpected error (type=Internal Server Error, status=500).
Connect to 127.0.0.1:8083 [/127.0.0.1] failed: Connection refused: connect

这是dockerps输出:

CONTAINER ID        IMAGE        COMMAND               CREATED             STATUS              PORTS                    NAMES
2a8eaf08881a        service_A    "./gradlew bootRun"   5 seconds ago       Up 4 seconds        0.0.0.0:80->80/tcp       service_A
b7436a77e438        service_B    "go-wrapper run"      About an hour ago   Up 4 seconds        0.0.0.0:8083->8083/tcp   service_B

我创建了 docker 网络:

docker network create webproxy

我的docker-compose.yml是:

version: '3'
services:   
  service_A:
    container_name: service_A
    build: ./service_A
    hostname: service_A
    restart: always
    ports:
      - "8083:8083"

  service_B:
    container_name: service_B
    build: ./service_B
    hostname: service_B
    restart: always
    ports:
      - "80:80"     

networks:
  default:
    external:
      name: webproxy

这是容器的ip addr show eth0:

project$ docker exec -it 2a8eaf08881a ip addr show eth0
68: eth0@if69: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:13:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.19.0.2/16 scope global eth0
       valid_lft forever preferred_lft forever


project$ docker exec -it b7436a77e438 ip addr show eth0
66: eth0@if67: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:13:00:03 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.19.0.3/16 scope global eth0
       valid_lft forever preferred_lft forever

这是docker网络信息:

project$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
9fcac7636448        bridge              bridge              local
83a0f3fe901d        host                host                local
215ab1608f91        none                null                local
95909545832d        predictor_default   bridge              local
be19665e791d        webproxy            bridge              local

我也可以从容器中 ping 172.19.0.3

服务A和服务B如何正确通信?

docker-compose.yml中为每个服务添加networks字段

version: '3'
services:   
  service_A:
    networks:
      - webproxy

  service_B:
    networks:
      - webproxy

networks:
  webproxy:
    driver: bridge

然后就可以使用服务名来发送请求了

HttpGet request = new HttpGet("http://service_A:8083/getTest");
HttpResponse httpResponse = httpClient.execute(request);

https://whosebug.com/users/1125714/tj-biddle 给出了有效的答案:

HttpGet request = new HttpGet("http://service_A:8083/getTest");
HttpResponse httpResponse = httpClient.execute(request);