Manage on Docker Containers with Ansible
Docker images are compiled from Dockerfiles. Containers are created from imaged, and they normally contain all they need from the beginning. When something should change, for example some software version or configuration, normally Dockerfiles are updated and containers are recreated from the latest image versions. For this reason containers are said to be ephemeral: they shouldn't contain anything values, and recreating them should be an extremely cheap operation. Docker Compose or Swarm are used to declare which containers form a certain environment, and how they communicate with each other.
On the contrary Ansible is mainly built to manage the configuration of existing servers. Docker and Ansible have very different approaches. For this reason, Ansible is not commonly used to deploy containers to production. However, using them together can bring some benefits, especially for development environments.
Contents
Benefits of Managing Docker Containers with Ansible
Some of the benefits are the following:
- Docker containers allow to work without modifying the host system, and their creation is very fast. Much faster than virtual machines.
- The main problem with Docker is that containers are designed to be ephemeral, which is bad for database servers. However, it is entirely possible to write databases into a Docker volume. When containers are destroyed volumes are preserved.
- If production databases are managed via Ansible, it could be easier to also manage development databases via Ansible. This reduces the cost of maintenance.
- While recreating containers is fast, being able to apply small changes with Ansible can be more convenient.
- Trying to do something non-standard with Dockerfiles can be tricky. For example, running two processes in a container can be problematic. However there are situations when this is desirable, for example PMM containers run several different processes. Launching additional processes with Ansible can make things easier.
How to Deploy a Container with Ansible
Ansible has modules to manage the Docker server, Docker containers, and Docker Compose. These modules are maintained by the community.
A dynamic inventory plugin for Docker exists. It retrieves the list of existing containers from Docker.
Docker modules and the Docker inventory plugin communicate with Docker using its API. The connection to the API can use a TSL connection and supports key authenticity verification.
To communicate with Docker API, Ansible needs a proper Python module installed on the Ansible node (`docker` or `docker-py`).
References
Further information can be found in Ansible documentation.
- Docker Guide
- docker_container module