Skip to main content
Ansible Configuration
CHAPTER 11

Ansible and Docker

Updated: May 15, 2026
25 min read

# CHAPTER 11

Ansible and Docker

1. Introduction

Historically, Ansible was used to configure massive, monolithic operating systems. Today, modern applications are packaged as lightweight, immutable Docker containers. Does Docker make Ansible obsolete? Absolutely not. While Docker provides the container, you still need a host to run it on, and you still need a way to orchestrate multiple containers across multiple servers. In this chapter, we will bridge the gap between Configuration Management and Containerization. We will use Ansible to install the Docker engine, pull container images, and orchestrate complex, multi-container deployments using the dockercontainer module.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Install the Docker Engine on a Linux host using Ansible.
  • Understand the prerequisites for Ansible to interact with the Docker Daemon.
  • Utilize the community.docker collection.
  • Deploy and manage Docker containers using the dockercontainer module.
  • Manage Docker networks and volumes via Ansible.

3. Beginner-Friendly Explanation

Imagine Docker is a shipping container full of goods.
  • Docker Compose: A crane operator who only works at ONE specific shipping dock. They can move containers around, but only at their specific dock (your local machine or a single server).
  • Ansible: The CEO of the entire global shipping company. Ansible can fly to 50 different shipping docks around the world simultaneously, tell the local crews to build the cranes (Install Docker), and then instruct all 50 cranes to move the shipping containers into the exact perfect position.

Ansible orchestrates Docker at scale.

4. Setting up the Docker Environment

To control Docker, Ansible needs the docker Python library installed on the Managed Node, and it needs the community.docker collection installed on the Control Node.

*On your Control Node terminal, install the collection:*

bash
1
ansible-galaxy collection install community.docker

*In your Playbook, prepare the Managed Node:*

yaml
123456789101112131415161718192021
---
- name: Prepare Docker Environment
  hosts: webservers
  become: yes

  tasks:
    - name: Install Docker prerequisites
      apt:
        name: 
          - apt-transport-https
          - ca-certificates
          - curl
          - software-properties-common
          - python3-pip
        state: present

    # Ansible needs the Python Docker library to talk to the Docker API
    - name: Install Docker SDK for Python
      pip:
        name: docker
        state: present

*(Note: A full Docker installation playbook is longer, requiring adding GPG keys and the Docker repository. For brevity, assume Docker is installed).*

5. Orchestrating Containers

Once Docker is running, we use the docker_container module to spin up applications.
yaml
1234567891011121314
    - name: Run a simple Nginx container
      community.docker.docker_container:
        name: my_web_app
        image: nginx:latest
        state: started
        restart_policy: always
        
        # Map port 80 in the container to port 8080 on the host server
        published_ports:
          - "8080:80"
          
        # Mount a local directory into the container
        volumes:
          - "/var/www/html:/usr/share/nginx/html:ro"

6. Mini Project: Deploy a Containerized Database

Let's use Ansible to deploy a secure PostgreSQL database container, complete with persistent storage (so data isn't lost if the container dies) and environment variables for the password.

Step-by-Step Architecture Concept:

yaml
12345678910111213141516171819202122232425262728293031
---
- name: Deploy Containerized Database
  hosts: databases
  become: yes
  vars:
    db_password: "SuperSecretPassword"

  tasks:
    # 1. Create a Docker Volume for persistent storage
    - name: Create PostgreSQL volume
      community.docker.docker_volume:
        name: pgdata

    # 2. Deploy the Database Container
    - name: Launch PostgreSQL container
      community.docker.docker_container:
        name: main_db
        image: postgres:14
        state: started
        
        # Security: Do not publish port 5432 to the host! Keep it isolated.
        
        # Attach the volume we just created
        volumes:
          - "pgdata:/var/lib/postgresql/data"
          
        # Inject the secure password variable into the container environment
        env:
          POSTGRES_USER: admin
          POSTGRES_PASSWORD: "{{ db_password }}"
          POSTGRES_DB: company_data

7. Real-World Scenarios

A development team used docker-compose to run their application locally. When it came time to deploy to Production, they manually SSH'd into the AWS server, copied the docker-compose.yml file, and ran the command. This resulted in zero deployment tracking. The DevOps team banned manual SSH access. They wrapped the Docker deployment in an Ansible Playbook. The playbook authenticated to the private AWS ECR container registry, pulled the proprietary Docker image, and launched the container. This allowed the Docker deployment to be triggered automatically by a Jenkins CI/CD pipeline, achieving true continuous deployment.

8. Best Practices

  • Immutable Containers: Never use Ansible to connect *inside* a running Docker container to install software or edit files. This violates the core philosophy of Docker (Immutability). A container should be built complete. Ansible should only be used to manage the *host* server, pull the pre-built image, and pass environment variables to the container at launch.

9. Security Recommendations

  • Avoid Docker Socket Mounting: Sometimes developers mount /var/run/docker.sock into a container so the container can control Docker. Avoid doing this via Ansible unless absolutely necessary (like for a Traefik router). Giving a container access to the Docker socket gives it effective root access to the entire host server.

10. Troubleshooting Tips

  • Python Library Conflicts: If Ansible throws Failed to import the required Python library (Docker API), it usually means the python3-docker package is not installed on the *Managed Node*, or it is installed for the wrong version of Python. Ensure you are using the pip module to install the docker package for the exact Python interpreter Ansible is utilizing.

11. Exercises

  1. 1. What is the operational purpose of installing the docker Python SDK via the pip module before attempting to use the docker_container Ansible module?
  1. 2. Explain why mapping a Docker Volume to a database container is critical for production data integrity.

12. FAQs

Q: Can Ansible replace Docker Compose? A: Yes, but they serve different purposes. Docker Compose is fantastic for a developer spinning up 5 containers on their laptop. Ansible is designed for spinning up those 5 containers across 50 different servers simultaneously.

13. Interview Questions

  • Q: Explain the intersection of Configuration Management (Ansible) and Containerization (Docker). In a modern DevOps pipeline, what operational responsibilities should be assigned to Ansible versus the Dockerfile?
  • Q: Describe the Ansible Playbook logic required to securely deploy a Dockerized database, ensuring data persistence and the secure injection of runtime credentials without exposing the database port to the host's public interface.

14. Summary

In Chapter 11, we bridged the gap between legacy infrastructure automation and modern containerized architecture. We established that while Docker abstracts the application, Ansible remains the critical orchestrator of the host environment. By utilizing the community.docker collection, we successfully translated complex docker run commands into declarative YAML, managing image pulls, volume persistence, and port mappings. We enforced the philosophy of container immutability, ensuring Ansible manages the *orchestration* of containers rather than the internal configuration of the containers themselves.

15. Next Chapter Recommendation

Orchestrating 5 containers with Ansible is easy. Orchestrating 5,000 containers requires a specialized platform. Proceed to Chapter 12: Ansible and Kubernetes.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·