Hossein Fallah
Hossein Fallah

Reputation: 2589

How to reuse docker-compose and have multiple instances up and running?

I'm reusing my docker-compose.yml across my projects.

For example, I have a couple of API projects and for all of them I have created a central docker-compose.yml file inside a shared directory.

And I run docker-compose -f /shared_path/api/docker-compose.yml up to bring them up.

This works perfectly for each API that I want to work with. But the problem is that each API that I bring up, it exits the previous API automatically.

In other words, I can't run two or more APIs at the same time.

How can I solve this problem?

Update

Here's my real docker-compose.yml that is being created dynamically.

version: "3.9"
services: 
    site:
        image: holism/next-dev:latest
        container_name: ${Repository}NextDev
        ports:
            - "${RandomPort}:3000"
        working_dir: /${RepositoryPath}
        volumes: 
            - /HolismHolding/Infra:/HolismHolding/Infra
            - /HolismReact/Site:/HolismReact/Site
            - ${RepositoryPath}/components:${RepositoryPath}/components
            - ${RepositoryPath}/contents:${RepositoryPath}/contents
            - ${RepositoryPath}/pages:${RepositoryPath}/pages
            - ${RepositoryPath}/public:${RepositoryPath}/public
            - ${RepositoryPath}/styles:${RepositoryPath}/styles
            - ${RepositoryPath}/.env:${RepositoryPath}/.env
            - /Temp/${RepositoryPath}/Build:${RepositoryPath}/.next
        command: >
            sh -c
            "
            cp -a /HolismReact/Site/. .
            && if [ ! -d ${RepositoryPath}/node_modules ]; then ln -s /site/node_modules ${RepositoryPath}; fi
            && npm run dev &
            echo -e '\033[0;31m'"http://localhost:$RandomPort"
            && tail -f /dev/null
            "

Upvotes: 0

Views: 684

Answers (1)

ôkio
ôkio

Reputation: 1790

You should remove the container_name as pointed out in the comments, and let docker-compose assign a name to the container according to the project name.

You could also use inheritance and create a different docker-compose file for each of your APIs to override port.

Your docker-compose.yml should look like this

version: "3.9"
services: 
    site:
        image: holism/next-dev:latest
        working_dir: /${RepositoryPath}
        volumes: 
            ...

And you should create a docker-compose.api-1.yml

version: "3.9"
services: 
    site:
        - 1080:3000

And docker-compose.api-2.yml

version: "3.9"
services: 
    site:
        - 1081:3000

And then call

docker-compose -f docker-compose.yml -f docker-compose.api-1.yml -p api-1 up
docker-compose -f docker-compose.yml -f docker-compose.api-2.yml -p api-2 up

So you'll end up with a container named api-1_site and another api-2_site, and you'll be able to access the first API on localhost:1080 and the second one on localhost:1081

Upvotes: 1

Related Questions