Search code examples
dockerdocker-composedocker-swarm

How to run two images on same machine in docker swarm cluster


I use docker swarm with several machines and several images. In particulat, I have database and container, that shedules backups. I need to start them on same machine. How i can setup this with docker-compose?

version: "3"
services:
    my_mongodb:
        image: mongo
        environment:
          - MONGO_DATA_DIR=${DATA_DIR}
        networks:
         - webnet
    my_backup:
        image: mybackup
        environment:
          - MONGO_DATA_DIR=${DATA_DIR}
   #other images

Solution

  • You can add an affinity filter to the my_backup environment:

    my_backup:
        image: my backup
        environment:
          - MONGO_DATA_DIR=${DATA_DIR}
          - "affinity:image==mongo"
    

    Unfortunately there is no "affinity:service" which will make it very easy to do this kind of things. You can learn more about filters in the docker docs for swarm scheduler filters.

    There is also an interesting discussion about supporting an affinity:service filter in the this issue in the docker/swarmkit GitHub repo.