How to start the Web Server in Docker Container using Ansible Playbook?

Ananya Sharma
2 min readSep 26, 2021

--

Description:-

  • 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 and start the web server.

The ansible playbook for the same is as follows:-

hosts: all
tasks:
- name: Create Yum Repo
yum_repository:
name: "docker"
description: "this is a docker repo"
reposdir: "/etc/yum.repos.d/"
baseurl: "
https://download.docker.com/linux/centos/7/x86_64/stable/"
gpgcheck : "no"
enabled: yes- name: Run Yum RepoList
command: yum repolist- name: Run Docker CMD
command: yum install -y --nobest docker-ce- name: Check Package
package:
name: "docker-ce"
state: present- name: Check Service
service:
name: docker
state: started

enabled: yes- name: Install Docker SDK
command: "pip3 install docker-py"- name: Pull IMG From DockerHub

docker_image:
name: "vimal13/apache-webserver-php:v1"
source: pull

- name: Run Container
docker_container:
name: "container1"
image: "vimal13/apache-webserver-php:v1"
state: started
detach: yes
exposed_ports:
- 80
ports:
- "8080:80"- name: Initiate HTTPD on Docker
command: "systemctl start httpd.service"- name: Get Container Details
docker_container_info:
name: "container1"
register: result- name: Copy File To TN
copy:
src: "demo1.html"
dest: "/root"- name: Copy File To Docker Container
command: "docker cp /root/demo1.html container1:/var/www/html"

Now, run the playbook using the following command:-

ansible-playbook 'playbook_name.yml'

We can also check whether these services are configured in the target node or not. The command for the same is as follows:-

systemctl status docker

To run the container created using playbook, the following command is executed (here the name of my container is “container1”).

docker exec -it container1 bash

Next, find the IP address of the container using the following command:-

ifconfig

Finally, run the following command to see the content inside the HTML file:-

curl 172.17.0.2/demo1.html

Thanks for reading :)

--

--

No responses yet