How to configure a Web Server on Docker using Ansible?

Ananya Sharma
2 min readMar 21, 2021

Pre-requisite:-

You should have pre-configured controller and managed node of ansible.

So, let’s get started…

Step 1:- First, we have to configure yum for installing the docker. The code for the same is as follows:-

- hosts: all
tasks:
- yum_repository:
description: "Docker yum repo"
name: "Docker Repo"
baseurl: "
https://download.docker.com/linux/centos/7/x86_64/stsble/"
gpgcheck: no

Step 2:- Now, download the docker software using the following code:-

- package: 
name: "docker-ce-18.06.3.ce-3.el7.x86_64"
state: present

Step 3:- Before starting the docker service, we need to install a python package named docker-py in the target node as ansible is dependent on python. By installing docker-py, the system will understand that docker is using the correct and same version of python as used by the system. The code for the same is as follows:-

- pip:
name: "docker"

Step 4:- Next, we have to start and enable the docker services. The code for the same is as follows:-

- service:
name: "docker"
state: started
enabled: yes

Step 5:- Now, we have to create a directory in the managed node to attach container and copy web page to it. Use the following code for the same:-

- file:
state: directory
path: "/Webserver"
- copy:
src: "MyWebPage.html"
dest: "/Webserver"

Step 6:- Next, we have to pull the HTTPD image from the Docker hub, launch docker container, run HTTPD server in it and make it publicly accessible. The code for the same is as follows:-’

- docker_image:
name: "httpd:latest"
source: pull
- docker_container:
name: "MyWebServer"
image: "httpd:latest"
state: started
exposed_ports:
- "80"
ports:
- "8080:80"
volumes:
- "/webserver:/usr/local/apache2/htdocs"

Step 7:- Now, run the playbook by using the following command :-

ansible-playbook playbook_name.yml

Finally, you can access the web page.

Thank you :)

--

--