Ansible

Docker Compose in Ansible

Docker is one of the most popular containerization tools. When dealing with complex infrastructure, we often turn to automation tools such as Ansible.

Thankfully, in the Ansible ecosystem, we have access to the “community.docker_compose” module that provides an automated way of managing the Docker compose projects.

If you are unfamiliar, the Docker Compose is a tool for defining and running the multi-container Docker applications.

Using Ansible’s docker_compose module, we can manage the lifecycle of these applications directly from Ansible playbooks, giving us programmatic control over container orchestration.

This tutorial explores how we can use the Docker Compose module to automate the container orchestration.

Prerequisites:

  • Installed Ansible
  • Installed Docker and Docker Compose on the target machine

Installing the Docker Collection

The docker_compose module is part of the “community.docker” collection. Therefore, we need to ensure that we have the collection installed before using it.

$ ansible-galaxy collection install community.docker

Examples:

Example 1: Start a Docker Compose Project

If we have a “docker-compose.yml” file that defines the application configuration, we can use this module to start it as follows:

Docker-compose.yml

version
: '3'

services
:

web
:

image
: nginx:alpine

ports
:

- "80:80"

We can use Ansible and the docker_compose module as follows:

---
- hosts
: localhost
tasks
:
- name
: Start docker compose project
community.docker.docker_compose
:
project_src
: ./docker-compose.yml
state
: present

Example 2: Stop the Docker Compose Project

To stop the services that are running in the project, we can use the playbook as follows:

---
- hosts
: localhost
tasks
:
- name
: Stop docker compose project
community.docker.docker_compose
:
project_src
: ./docker-compose.yml
state
: absent

Conclusion

We covered the basics of working with the Ansible docker_compose module to manage the Docker projects. Explore the docs for the module in the following link to learn more:

https://docs.ansible.com/ansible/latest/collections/community/docker/docker_compose_module.html

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list