如何在不同的容器中使用相同的端口?

How to use same ports in seperate containers?

我有两个 docker 容器,每个 运行 roscore 使用端口 11311。每个容器都有单独的 IP 地址,并在发布和订阅时使用不同的命名空间。我不应该能够将每个容器视为一台单独的机器吗?我想要做的是从主机到基于命名空间的容器之一的 rostopic pub。

当我启动容器时,我得到以下信息:

$ docker-compose up
Creating mach1 ... error
Creating mach1 ... 

ERROR: for mach1  Cannot start service mach1: driver failed programming external
Creating mach2 ... done
cab7aa376623c708c): Bind for 0.0.0.0:11311 failed: port is already allocated

ERROR: for mach1  Cannot start service mach1: driver failed programming external connectivity on endpoint mach1 (9f755a1bd3f1dad40cce6963105a5d7224127dca3e0bb72cab7aa376623c708c): Bind for 0.0.0.0:11311 failed: port is already allocated
ERROR: Encountered errors while bringing up the project.

docker-compose 的 YAML 是:

version: '3'
services:
  mach1:
    build:
      context: .
      dockerfile: ./mach1/Dockerfile
    environment:
      - "ROS_IP=10.10.0.20"
      - "ROS_MASTER_URI=http://10.10.0.20:11311"
    image: my-image:v1
    ports:
      - "11311:11311"
    networks:
      my_net:
        ipv4_address: 10.10.0.20

  mach2:
    build:
      context: .
      dockerfile: ./mach2/Dockerfile
    environment:
      - "ROS_IP=10.10.0.21"
      - "ROS_MASTER_URI=http://10.10.0.21:11311"
    image: my-image:v1
    ports:
      - "11311:11311"
    networks:
      my_net:
        ipv4_address: 10.10.0.21

networks:
  my_net:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 10.10.0.0/24
        #- gateway: 10.10.0.1

问题是您正试图将两个容器的端口 11311 映射到主机上的 11311

ports:
  - "11311:11311"

改为尝试映射到不同的主机端口:

ports:
  - "11311:11311"

ports:
  - "11312:11311"