Bootstrap FreeKB - Ansible - Restart Docker container using the docker_container module
Ansible - Restart Docker container using the docker_container module

Updated:   |  Ansible articles

If you are not familiar with modules, check out Ansible - Getting Started with Modules.

docker_container is part of the community.docker collection. Typically, the community.docker collection is not included in the default Ansible collections. The ansible-galaxy collection install command can be used to install the community.docker collection.

ansible-galaxy collection install community.docker

 

Before you can use the docker_container module, the Python docker module must be installed on the managed node, which can be done using PIP. The dnf module can be used to install PIP and then the pip module can be used to install the Python docker module.

---
- hosts: all
  tasks:
  - name: install pip
    dnf:
      name: pip
      state: present

  - name: pip install docker
    pip:
      name: docker
      state: latest
...

 

Here is how you can restart a Docker container using restart: true.

---
- hosts: all
  tasks:
  - name: stop the 'www' container
    docker_container:
      name: www
      state: started
      restart: true
...

 

Optionally, restart_retries can be used. If using restart_retries you must also include restart_policy with a value of on-failure. "no" and "unless-stopped" and "always" are valid options but cannot be used to restart the container. "no" and "unless-stopped" and "always" are used when creating the container.

---
- hosts: all
  tasks:
  - name: restart the 'www' container
    docker_container:
      name: www
      state: started
      restart: true
      restart_retries: 3
      restart_policy: on-failure
...

 

However, I noticed that restart_retries and restart_policy don't always work for containers that take a long time to restart. To account for this, sometimes I go with a retries / delay / until loop.

---
- hosts: all
  tasks:
  - name: restart the 'www' container
    docker_container:
      name: www
      state: started
      restart: true
    register: out
    retries: 10
    delay: 10
    until: out.rc == 0
...

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 8c420a in the box below so that we can be sure you are a human.