How to use same ports in seperate containers?

I have two docker containers, each running roscore which uses port 11311. Each of the containers has seperate IP address and uses different namespaces when publishing and subscribing. Shouldn’t I be able to treat each container as a separate machine? What I want to do is rostopic pub from the host to one of the containers based on namespace.

When I start the containers, I get the following:

$ 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.

The YAML for docker-compose is:

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

Source: StackOverflow