Automating Docker Deployment with Ansible: A Step-by-Step Guide

Abhinav Shreyash
3 min readAug 2, 2023

--

So our Agenda here is like this

Write an Ansible PlayBook that does the following operations in the managed nodes:

🔹 Configure Docker

🔹 Start and enable Docker services

🔹 Pull the httpd server image from the Docker Hub

🔹 Copy the html code in /var/www/html directory and start the web server

🔹 Run the docker container and expose it to the public

Before writing the ansible playbook let’s configure the ansible configuration file and the inventory file -

  • So, at first we have to setup the ansible configuration file which is /etc/ansible/ansible.cfg
$ vim /etc/ansible/ansible.cfg

we simply have to put the location of the inventory file in this ansible.cfg like this

  • Now we will update the ip in the inventory file.
$ vim /root/ip.txt
  • We can check the host is configured or not by listing the hosts, using this command:
$ ansible all --list-hosts
  • Now we can check the connectivity of the worker node using this command:
$ ansible all -m ping

So the setup is ready, now we can write the ansible playbook.

- name: "configuring httpd on docker"
hosts: web

tasks:
# from here we will write all the modules as per our requirement
  • For the docker configuration first we have to configure the yum
- name: "Yum configuration of Docker"
yum_repository:

name: docker
description: "docker repository"
baseurl: https://download.docker.com/linux/centos/7/x86_64/stable/
gpgcheck: no
  • for installing docker-ce
- name: "Installing docker"

command: “yum install docker-ce — nobest -y”

  • Start and enable Docker services
- name: "Docker service start and enable"
service:
name: docker
state: started
enabled: yes
  • Install docker library
- pip:
name: "docker"

state: latest
  • Pull the httpd server image from the Docker Hub
- name: "Pulling httpd image from docker hub"
docker_image:
name: httpd
source: pull
state: present
  • Creating a folder in the controller node named /var/www/html
- name: "Creation of a directory"
file:
path: "/var/www/html"
state: directory
  • Copying the html file to that location (create a index.html file to the same directory where you are creating this ansible playbook) for
- name: "copping html file"
copy:
src: "index.html"
dest: "/var/www/html/index.html"
  • Enabeling the firewalld
- name: "firewall for port 80"
firewalld:
port: "80/tcp"
state: enabled
permanent: yes
immediate: yes
  • Running the docker container
- name: "Launching docker container"
docker_container:
name: webserver
image: httpd
state: started
ports: "8081:80"
volumes: /var/www/html/index.html:/usr/local/apache2/htdocs/index.html
detach: true

That’s all! Now we have to run the playbook

$ ansible-playbook docker-httpd.yml

we can see the apache httpd webserver is conigured:

Thank You Very Much for Reading My block

--

--