Anurag P
Anurag P

Reputation: 387

How to create multiple containers of same image by running same docker-compose file on different host ports?

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.

Upvotes: 0

Views: 4663

Answers (1)

BMitch
BMitch

Reputation: 263469

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

Upvotes: 1

Related Questions