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

时间:2019-04-10 22:39:09

标签: docker docker-compose ros

我有两个docker容器,每个容器运行roscore,使用端口11311。每个容器具有单独的IP地址,并且在发布和订阅时使用不同的名称空间。我不应该将每个容器都当作单独的机器来对待吗?我要做的是根据名称空间从主机到容器之一的rostopic发布。

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

$ 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

1 个答案:

答案 0 :(得分:4)

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

ports:
  - "11311:11311"

相反,请尝试映射到其他主机端口:

ports:
  - "11311:11311"

ports:
  - "11312:11311"