Deploy webserver in Docker container with Ansible

Shobhit Singh Pal
3 min readFeb 4, 2021

Ansible is the IT automation tool. Ansible is written in python so it needs python for its installation and execution of its playbook. Currently Ansible support python2 and python3 both but good to go with python3.

I am writing ansible playbook that will do the following:

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

Configure Docker

- name: Add repository
yum_repository:
name: docker
description: Docker YUM repo
baseurl: https://download.docker.com/linux/centos/7/x86_64/stable/
gpgcheck: no
- name: Install docker
package:
name: docker-ce-18.09.1-3.el7.x86_64
state: present

The yum-repository module will configure yum for docker. Configure yum means it will add the repository for docker as follows:

Start and enable Docker services

- name: enable Docker services
service:
name: "docker"
state: started
enabled: yes

Configuring python for docker

- name: conf python for docker      
pip:
name: docker-py

Pull the httpd server image from the Docker Hub

- name: Pull httpd docker iso
docker_image:
name: httpd
source: pull

Run the docker container and expose it to the public

- name: docker container
docker_container:
name: httpd_server
image: httpd
exposed_ports:
- 80
ports:
- 4444:80
volumes:
- /var/www/html/:/usr/local/apache2/htdocs/

As the storage provided by ansible is ephemeral so using the bind mounts.

Bind mounts: It is the file or directory on the host machine mounted in the container.

Here we are mounting the /usr/local/apache2/htdocs/ of contianer on /var/www/html of host machine. /usr/local/apache2/htdocs has the same meaning as the /var/www/html in redhat and centos.

Copy the html code in /var/www/html directory

- name: git      
git:
repo: GITHUB_REPO
clone: yes
dest: /var/www/html

This will download all the files from github repo in the /var/www/html.

The Ansible Playbook

To execute the playbook run the following command

ansible-playbook playbook_name.yml
# For verbose
ansible-playbook -vvv playbook_name.yml

Output

The docker container

Website

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Shobhit Singh Pal
Shobhit Singh Pal

No responses yet

Write a response