Automate dockerization of webserver using Ansible

Rishyani Bhattacharya
3 min readMar 17, 2021

What is Docker?

Docker is a set of platform as a service products that use OS-level virtualization to deliver software in packages called containers. Containers are isolated from one another and bundle their own software, libraries and configuration files; they can communicate with each other through well-defined channels

So, What are we going to deploy here?

We are going to write a playbook that’s gonna perform the following tasks:-

🔅 Configure Docker
🔅 Start and enable Docker services
🔅 Pull the httpd server image from the Docker Hub
🔅 Run the httpd container and expose it to the public
🔅 Copy the html code in /var/www/html directory and start the web server

Firstly check if ansible is installed or not

ansible --version

Next create a ansible.cfg file with the following content:

[defaults]
inventory=inventory
host_key_checking=False
command_warnings=False

Create the inventory containing the IP of the managed node in the same directory as of ansible.cfg file.

<IP of managed node> ansible_ssh_user=root ansible_ssh_pass=password

Once Ansible is successfully configured, we can go on with creating the ansible playbook: —

---
- name: Setup docker on managed node
hosts: all
tasks:
- name: Configure docker repo
yum_repository:
name: docker
description: Yum repo for docker
baseurl: https://download.docker.com/linux/centos/7/x86_64/stable/
gpgcheck: no
- name: Install docker
command: yum install docker-ce --nobest -y
- name: Install python3
package:
name: python3
state: present
- name: Install docker SDK
pip:
name: docker-py
- name: Start and enable docker service
service:
name: docker
state: started
enabled: yes
- name: Pull docker image
docker_image:
name: httpd
source: pull
- name: Create workspace directory
file:
path: /root/Task10/web
state: directory
- name: Copy webpage content
copy:
content: "<h1>This webpage is configured inside a docker container deployed using Ansible.</h1>"
dest: /root/Task10/web/index.html
- name: Allow port through firewall
firewalld:
port: 8081/tcp
permanent: yes
immediate: yes
state: enabled
- name: Run a docker container
docker_container:
name: webos
image: httpd
state: present
exposed_ports:
- 80/tcp
- 80/udp
published_ports:
- 0.0.0.0:8081:80/tcp
- 0.0.0.0:8081:80/udp
volumes:
- /root/Task10/web/:/usr/local/apache2/htdocs/

Let’s deploy the playbook now —

ansible-playbook <playbook_name>.yml

So, let’s check whether the webserver has been containerized or not —

http://<IP of managed node>:8081

Deployment successful !!

THNAK YOU!!

--

--