Open In App

How to Use Ansible for Docker Container Management

Last Updated : 07 May, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Containerization has become one of the foundations for realizing scalable, reliable, and efficient application deployments in modern DevOps practice. Docker, as a leading containerization platform, enables developers to package applications and all dependencies into containers for consistency across environments. However, managing these containers across systems becomes quite challenging. This is when Ansible helps to automate this stuff—a free automation tool.

Ansible makes IT automation approachable, with its simplicity in managing configurations, deployments, and orchestration, using the human-readable files called playbooks in YAML. When used with Docker, Ansible can be used to fully automate the life cycle of Docker containers from deployment to installation and management to scaling, bringing better consistency in the deployment and maintenance of containerized applications.

In this article, we will see how to work with Ansible for the management of Docker containers. We are going to install Ansible, create some Ansible playbooks, and then look at the way to manage Docker containers. Also, we are going to look at how to reuse the task's specification in a role that is supported by Ansible in order to have a structured approach to your setup for container management.

how_to_use_ansible_for_docker_container_management

Primary Terminologies

  • Ansible: An open-source automation tool, open-source that eases IT tasks, among which are configuration management, application deployment, and orchestration. It uses human-readable YAML files to define automation jobs, making it accessible and easy to use.
  • Docker: Docker is an open platform that helps to build applications and software releases inside software containers defined as packages, thereby containing application software and all its dependencies required to run.
  • Playbook: A YAML file with a list of things to do that Ansible does. In short, a playbook provides for defining automation and orchestration schemes, in which you define what needs to be done to have software installed, a system configured, or an application deployed.
  • Roles: Ansible tasks, variables, files, templates, and modules grouped into a specific directory structure. An Ansible structure following best practices and roles enables the sharing and reusing of code in Ansible and makes managing complex configurations significantly easier.
  • Inventory: A file that lists hosts under Ansible control. It gives explanations on which systems Ansible would execute the tasks and may have any variables, further making it clear how automation would be customized to each single host.
  • Task: A part of the execution that Ansible has to perform, for example, running a command, managing files, or manipulating services. In a sense, playbooks and roles will be elaborations of tasks, later on.
  • Module: Modules are a piece of code used by Ansible for every particular task it executes. They maintain all kinds of things in the system, from packages and services to files and containers. For instance, module yum is for managing packages and docker_container is for container management.
  • Handler: A special type of task that only works when called by another task. The handler is most often used to implement actions such as restarting a service after changing its configuration.
  • Variable: A key-value pair for storing data which can be invoked from Ansible playbooks and roles. It helps to make the code of automation dynamic and reusable.
  • Template: A file with variables in place, in which Ansible can fill in real data when executing. Most frequently, templates are utilized to create configuration files out of the contents of a variable.

Why Use Ansible to Manage Docker?

Ansible helps you manage Docker in an automated, repeatable way. Here's how it makes your job easier, with real-world examples:

1. Saves Time by Automating Repetitive Tasks

Managing containers manually means typing the same docker run, docker pull, or docker stop commands on every server over and over.

Example:
If you want to run an Nginx container on 5 servers, you'd normally SSH into each server and run the Docker command by hand. With Ansible, you create a playbook once and run it with:

ansible-playbook deploy_nginx.yml

This command deploys the container to all your servers in one go saving hours of work.

2. Reduces Human Errors

Manual setups are prone to mistakes like forgetting to open the right port or using the wrong image tag.

Example:
You might forget to expose port 80 on one server or mount the wrong volume. Ansible eliminates this by following your playbook exactly, every time.

This guarantees consistent container setups across all environments.

3. Reusable and Repeatable

Once your playbook is ready, you can run it again and again on staging, production, or new servers without rewriting anything.

Example:
Deploying a web app? Just reuse the same Ansible playbook with updated variables for each environment. Need to scale out? Add new servers to your inventory and re-run the playbook.

This repeatability saves time and ensures consistent results.

4. No Agents or Extra Software Required

Ansible connects to servers using SSH. You don’t have to install any special agent software.

Example:
You can run Ansible from your laptop to control a cloud VM, a physical server, or even a Raspberry Pi so long as it has Python and SSH access.

This keeps your infrastructure lightweight and secure.

5. Infrastructure as Code (IaC)

Ansible lets you define your Docker container setups as code. This makes your deployments easier to version, reuse, and collaborate on just like application code.

Example:
Let’s say you want to run a Python Flask app inside a Docker container with environment variables and mounted volumes. You can write it in an Ansible playbook like this:

- name: Deploy Flask app container
  docker_container:
    name: flask_app
    image: myflaskapp:latest
    env:
      FLASK_ENV: production
    volumes:
      - /var/www/flask:/app
    ports:
      - "5000:5000"

This setup becomes part of your Git repository. Any team member can deploy the same container exactly the same way, and you can easily track changes over time.

Step-by-Step Process for Using Ansible to Manage Docker Containers

Step 1: Launch an EC2 Instance

  • Go to AWS Console and login with your credentials
  • Navigate to EC2 dashboard and launch an ec2 instances
Launch an EC2 Instance
  • One instance is master and another is host instance

Step 2: Install Docker

sudo yum -y install docker
sudo yum -y install docker
  • Start the Docker service.
sudo systemctl start docker 
sudo systemctl start docker
sudo usermod -aG docker ec2-user
sudo usermod -aG docker ec2-user

Step 3: Install Ansible

sudo amazon-linux-extras install ansible2 -y
Install Ansible

Step 4: Setup Host file

Setup Host file

Step 5: Install pip (Python package installer)

  • Ensure that pip is installed on your system. If it's not installed, you can install it using the following commands:
sudo yum install python3-pip -y

Install the Docker SDK for Python 3

sudo pip3 install docker
sudo pip3 install docker

Verify the Installation:

python3 -m pip show docker
Verify the Installation

Step 6: Creating an Ansible Playbook

  • Create a new file named docker-management.yml.
sudo vi docker-management.yml
  • Add the following content to the playbook file:
- name: Docker Management Playbook
  hosts: all
  become: yes
  gather_facts: yes
  tasks:
    - name: Ensure Docker is installed
      yum:
        name: docker
        state: present
      vars:
        ansible_python_interpreter: /usr/bin/python2
    - name: Start Docker service
      service:
        name: docker
        state: started
    - name: Install pip for Python 2
      yum:
        name: python2-pip
        state: present
    - name: Install Docker SDK for Python 2 in user space
      pip:
        name: docker
        executable: /usr/bin/pip2
        extra_args: --user
    - name: Run a Docker container
      docker_container:
        name: my_container
        image: nginx
        state: started
        exposed_ports:
          - 80:80
      environment:
        PATH: "{{ ansible_env.HOME }}/.local/bin:{{ ansible_env.PATH }}"
Creating an Ansible Playbook

Step 7: Running the Ansible Playbook

Execute the Playbook

ansible-playbook docker-management.yml
Execute the Playbook

Step 8: Verify In Host instance

  • Now verify that docker and container was running on Host instance
  • Navigate to EC2 Dashboard and connect to terminal check by using following commands
docker --version
docker ps 
Verify In Host instance
  • Our container was successfully running

Step 9: Managing Docker Containers with Ansible

Stopping a Container

  • To stop a running container, modify the playbook or create a new one with the following task:

- name: Stop Docker container

docker_container:

name: my_container

state: stopped

Stopping a Container
  • Run the playbook which is created to stop container
Run the playbook

To verify whether docker container was stopped or not by using following command

docker ps   #this command is used for to check running containers 
docker ps -a  # this command is used for to check stopped containers
docker ps
  • Here we see that container was stopped successfully

Removing a Container

  • To remove a container, modify the playbook or create a new one with the following task:

- name: Remove Docker container

docker_container:

name: my_container

state: absent

Removing a Container
  • Run the playbook to remove container
remove container
  • Verify by using following command
docker ps #to check container list
docker ps #to check container list
  • Here we see there is no any container was running and stopped. Our container was successfully removed

Conclusion

By managing Docker Containers on Amazon Linux 2 with Ansible, you will be combining the power of containerization with the simplicity and efficiency of automation. It does so in ways that combine ease of automation with great application visibility, management, consistency, and reliability throughout all environments. With the given guide, you should effectively set up and manage Docker containers with Ansible.

It has so much versatility, based on a modular structure and a large module library, and more so, human-readable YAML files for complex workflow automation. With all of your tasks organized in automation by the application of roles and playbooks, even less maintenance needs to be done since they are reusable with minimal overhead. This not only saves time but decreases room for error, hence your infrastructure will be stable and, in general, performing well.

A powerful solution is at your fingertips for the management of containerized applications once you integrate Ansible and Docker on Amazon Linux 2. These make automation of lifecycles easy, which improve the operational efficiency tremendously. It deploys and manages your applications in a more consistent manner. This book is designed for beginners and also advanced DevOps practitioners, as it walks you through everything you need in order to manage Docker containers using Ansible.


Next Article
Article Tags :

Similar Reads