How to manage docker-compose with ansible ?

In a previous post, we discovered how to install a prometheus/grafana stack with ansible. Many of you have read and it’s a pleasure for me to write a new post on ansible.

In this post, we are going to see the docker-compose module. A very simple ansible module which can allow to run, build or remove some docker services. Each service runs one or many docker containers of course.

If you want, you can follow the documentation about this module.

Main parameters for beginners

  • build : to add a build step (with Dockerfile path)
  • definition : to define the docker-compose in this section
  • dependencies : to create a dependancy with another service
  • docker_host : which docker socket to use (unix/ssh/tcp)
  • files : docker-compose list
  • nocache : to build an image without cache (rebuild)
  • pull : to pull images before to start
  • remove_images : to remove the local image (on target server)
  • remove_orphans : to remove all containers not manage by docker-compose
  • remove_volumes : to remove all volumes
  • scale : to add a scale value
  • services : what do you want to do with services ? up (present), stop (stopped), restart (restarted)
  • state : like services parameter

Example of ansible code for docker-compose

To follow my examples, you can download the repository here.

The first task to deploy an app stored in app directory on our ansible server.

- name: copy docker-compose.yml
copy:
src: app/
dest: tmp/
- name: test docker-compose
docker_compose:
project_src: tmp/
state: present

We push the code and Dockerfile with a docker-compose.yaml file. After it we just run our docker-compose file with the module with a state sets to present (to start it).

And now, let me show you how to scale your service with one parameter : scale.

- name: test docker-compose
docker_compose:
project_src: tmp/
state: present
scale:
app: 4

Or if you want to remove this service you could use the absent state.

- name: test docker-compose
docker_compose:
project_src: tmp/
state: absent

But how we can do it without a docker-compose file ? We can use the definition parameter. This is the first line of a specific block dedicated to store the content of your compose file.

- name: test docker-compose
docker_compose:
project_name: mynginx
definition:
version: "3.7"
services:
app:
image: nginx:latest

And finally, how can we build an image with our compose module ?

- name: copy docker-compose
copy:
src: app/
dest: /tmp/app
- name: run comporse
docker_compose:
project_name: mynginx
definition:
version: "3.7"
services:
app:
build: "/tmp/app/"
ports:
- 8888:8080

By default, ansible use the /tmp/app file defined in build parameter and find a Dockerfile file to build our image.

Suscribe to my channel and don’t miss the next video !!!

Microservices architecture and opensource. I’m maintainer of xavki https://youtube.com/c/xavki-linux about opensource. My blog : https://xavki.blog/