Search code examples
dockerdeploymentdocker-composeansible

How to run docker-compose commands with ansible?


In ansible playbook I need to run docker-compose commands. How can I do it? I need to run command: docker-compose -f docker-compose.yml -f docker-compose.prod.yml up


Solution

  • Updated answer 02/2024:

    docker_compose_v2 is out since community.docker v3.6.0.

    You can copy docker-compose.yml and run Compose such as:

    - name: copy Docker Compose files
      copy:
        src: files/{{ item }}
        dest: /somewhere/yourproject/{{ item }}
      loop:
      - docker-compose.yml
      - docker-compose.prod.yml
    
    # use files parameter to use multiple docker-compose.yml files
    # mind the _v2 suffix
    - name: deploy Docker Compose stack
      community.docker.docker_compose_v2:
        project_src: /somewhere/yourproject
        files:
        - docker-compose.yml
        - docker-compose.prod.yml
    

    Old answer (06/2020) using docker_compose module, only compatible with docker-compose < 2.0.0:

    You should copy your Docker Compose files and use docker_compose module such as:

    - name: copy Docker Compose files
      copy:
        src: files/{{ item }}
        dest: /somewhere/yourproject/{{ item }}
      loop:
      - docker-compose.yml
      - docker-compose.prod.yml
    
    # use files parameter to use multiple docker-compose.yml files
    - name: deploy Docker Compose stack
      community.docker.docker_compose:
        project_src: /somewhere/yourproject
        files:
        - docker-compose.yml
        - docker-compose.prod.yml
    

    Edit 2023-08-22: as of today Compose v2 is not supported by Ansible, it only works with v1. There's ongoing work towards docker_compose_v2 module but it's not available yet. In the meantime you can use shell as per @Tatiana's answer