Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Docker Compose apps automatically bind to same port but compose doesn't start

I have two copies of the same application that I want to deploy in a cluster and I’m using docker-compose for now. This application listens to port 8000 and if the port is busy it increments the port number until it finds a free port (8001, 8002 etc). These ports are used for the apps to communicate with each other, i.e. app1 will listen to 8000 and talk to app2 in 8001.

Since I’m deploying these using docker-compose, each container gets their own IP address. This means that both apps will bind to port 8000 (since it’s not busy from their perspective). Knowing this, I’m trying to map those ports in the docker-compose.yml file as follows

version: "3.9"
  services:
    app1:
      container_name: app1
      image: app:latest
      ports:
        - 8000:8000
    app2:
      container_name: app2
      image: app:latest
      ports:
        - 8000:8001

However, when I try to docker-compose up this thing it fails with the following error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

bind for 0.0.0.0:8000 failed: port is already allocated

i.e. it can’t bind the same container (internal) port even though they are from different containers and are mapped to different host ports. Both app1 and app2 will choose port 8000 because from their perspective is free but I’m unable to map it externally. How can I solve this?

My preference would be for each app to bind to a different port i.e. the whole compose setup should share the same ports even though containers have different IP adresses.

NOTE: Changing the port selection code is not an option, this is a third party library and frankly it’s a regular pattern to use.

>Solution :

I think you have swapped the ports around. The first port is the host port and the second port is the internal container port.

Try

version: "3.9"
  services:
    app1:
      container_name: app1
      image: app:latest
      ports:
        - 8000:8000
    app2:
      container_name: app2
      image: app:latest
      ports:
        - 8001:8000

That will map the containers to host ports 8000 and 8001.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading