Search code examples
dockerdocker-composedockerfiledocker-machine

Can we use the same image for running multiple docker containers?


I am new to Docker and started building containers. I came across Docker-compose for building multiple containers inside a container.

Now, i have a problem with docker-compose containers.

I created two yaml files which are producer.yaml and consumer.yaml.

#producer.yaml
version: "3"
services:
    mymongo:
        image:// imageurl
        port: 6666:6666
    mynodeapp:
        build:
            context: //Dockerfile path
        port:
            - 2222:2222

#end producer.yaml

#consumer.yaml
version: "3"
services:
    mymongo:
        image:// sameImageUrl
        port: 7777:6666
    mynodeapp:
        build:
            context: //Dockerfile path
        port:
            - 3333:3333

#end consumer.yaml

Now, when i run docker-compose producer.yaml up. The producer container is up and running. But simultaneously, if i run docker-compose consumer.yaml up. This command makes the producer container to be terminated and then, the consumer container will be running. How can i make sure that, the imageURL used will be separate for both the containers.


Solution

  • To run multiple files you should run all of them together

    docker-compose up -f producer.yaml -f consumer.yaml up
    

    When you run individual files, the compose will try to up all the services and it will not kill any existing services if there is no service name conflict.

    In your case you have same service names for both your consumer and producer, which is wrong. Because when you merge the two files, compose will use only one of the definitions. So your service name in yaml should be mynodeapp-producer and mynodeapp-consumer in case you want them to run in parallel.

    In case you expect different mongodb for both then you should configure those names as well to be different