0

Suppose currently I am running a docker container Container A created using Image Image X running on Host Port 3031 and Docker Port 3030

DOCKER_COMPOSE.yaml

version: "3"
services:
  app:
    image: ${IMAGENAME}
    container_name: ${PROJECTNAME}_ContainerA
    restart: ${RESTART}
    build:
      context: ${BUILD}
      args:
        PORT: 3030       --> this goes to dockerfile
    ports:
      - "3031:3030"
    networks:
      salesdb_network:
        ipv4_address: ${IP}
    environment:
      - APP_PORT=3030

networks:
  some_network:
    external: true

I AM GETTING PORTS FROM env file. Above is just for demonstration

I ran docker-compose --env-file **some_file** -f docker-compose.yaml up

enter image description here

Till now, Works fine. All good No Issues.

Now, I want to create another container Container B by using Image Image X running on Host Port 3033 and Docker Port 3032. I have same structure as above for docker_compose.yaml file with changed ports

I ran docker-compose --env-file **some_file_2** -f docker-compose.yaml up

But, I get following error.

creating ${PROJECTNAME}_ContainerA... error

ERROR: for ${PROJECTNAME}_ContainerA  Cannot start service app: Address already in use

ERROR: for app  Cannot start service app: Address already in use
ERROR: Encountered errors while bringing up the project.

Before I added PROJECTNAME (for which i followed this), While running Container B, It used to Override Container A AND Ports would change to 3031/tcp, 0.0.0.0:3033->3032/tcp.

Anurag P
  • 337
  • 3
  • 11

1 Answers1

1

I wouldn't bother changing the port in your Dockerfile, let the app listen on the same port inside of every container. Each container has a separate network namespace, so they won't conflict. What you do need to change is the published port on the host. Change this:

ports:
  - "3031:3030"

to use a variable like:

ports:
  - "${PORT}:3030"

And then define your $PORT environment variable in a .env or in your shell before running the docker-compose up.


I'd also recommend removing the following:

    ipv4_address: ${IP}

Instead let docker provision an IP on that network and use DNS to find your container between containers. Since everything is the same service name, you can use your container name ${PROJECTNAME}_ContainerA, or give your containers a unique network alias:

networks:
  salesdb_network:
    aliases:
    - ${PROJECTNAME}-app
BMitch
  • 231,797
  • 42
  • 475
  • 450
  • Hi @BMitch, Thanks for the reply. I tried it just to be sure. But I am still getting same error. – Anurag P May 07 '20 at 00:30
  • 1
    @Anurag then it's probably your static IP address that's conflicting. I'd avoid using that, see the edit above. – BMitch May 07 '20 at 01:02
  • Hi BMitch. That is correct. It was the IP that was creating the issue. Thanks a lot. – Anurag P May 07 '20 at 11:33