Docker-使用动态 ip: 端口编写拨号 tcp 错误

Docker-compose dial tcp error with dynamic ip : port

我正在尝试将请求从网关重新路由到目标服务,如果我使用静态端口绑定,一切正常。但它不灵活,所以我想 运行 网络中具有动态 ip 和端口的容器,以便能够 运行 多个实例。

我从

改成了docker-compose.yml
-ports: 
  "8082:8082"

-ports: 
  "8082"

出现错误

Get "http://c0000203.addr.dc1.consul.:60949/api/v1/users": dial tcp 192.0.2.3:60949: connect: connection refused

我正在使用 consul 作为服务发现,并使用 registartor 来注册容器

基础docker-撰写文件:

version: '3.7'
services:
  postgres:
    image: postgres:13
    restart: 'always'
    environment:
      - POSTGRES_DB=user-db
      - POSTGRES_PASSWORD=password
      - POSTGRES_USER=user
    ports:
      - "5432"
    networks:
      - vpcbr

  consul:
    image: consul:latest
    restart: 'always'
    environment:
      CONSUL_LOCAL_CONFIG: |
        {
          "recursors": [
            "8.8.8.8",
            "8.8.4.4"
          ],
          "dns_config": {
            "recursor_strategy": "random"
          },
          "ports": {
            "dns": 53
          }
        }
    networks:
      vpcbr:
        ipv4_address: 192.0.2.10
    ports:
      - '8500:8500'
      - '53/tcp'
      - '53/udp'

  registrator:
    image: gliderlabs/registrator:latest
    command: "consul://consul:8500"
    container_name: registrator
    depends_on:
      - consul
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock
    networks:
      vpcbr:
        ipv4_address: 192.0.2.20

  krakend_gateway:
    image: devopsfaith/krakend:2
    command: [ "run", "-d", "-c", "/krakend.json" ]
    dns: 192.0.2.10
    volumes:
      - ./krakend-gateway/krakend.json:/krakend.json
    ports:
      - "1234:1234"
      - "8080:8080"
      - "8090:8090"
    networks:
      vpcbr:
        ipv4_address: 192.0.2.23

  user-ms:
    build: user-ms/
    platform: linux/arm64
    restart: 'always'
    depends_on: [consul, krakend_gateway]
    networks:
      - vpcbr
    ports:
      - "8082"

networks:
  vpcbr:
    driver: bridge
    ipam:
      config:
        - subnet: 192.0.2.0/24

发送请求的服务是 Krakend,目标服务是 user-ms,它应该接受这个请求,当我将 user-ms 端口绑定更改为“8082:8082”时一切正常

如果有人能帮助我,我会很高兴,谢谢

使用 Registrator 的 -internal CLI 标志配置为使用 Docker 容器的内部 IP 地址注册服务,而不是外部主机 IP。

https://gliderlabs.github.io/registrator/latest/user/run/#registrator-options

  • -internal Use exposed ports instead of published ports.

If the -internal option is used, Registrator will register the docker0 internal IP and port instead of the host mapped ones.

修改后的容器定义如下。

# docker-compose.yaml
...
  registrator:
    image: gliderlabs/registrator:latest
    command: "consul://consul:8500 -internal"
    container_name: registrator
    depends_on:
      - consul
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock
    networks:
      vpcbr:
        ipv4_address: 192.0.2.20
...