Automating Configuration of Webserver inside the Docker Container using Ansible !

In this Blog i’ll explain how we can Retrieve Docker Container IP & establish the webserver inside the Docker Container.

Arpit Bisane
3 min readMar 26, 2021

DOCKER FILE

A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Using docker build users can create an automated build that executes several command-line instructions in succession.

First step is to build the image, in which ssh is enabled. Ansible requires ssh for contacting the host.

docker build -t new_image:v1

ANSIBLE CONFIGURATION FILE

Certain settings in Ansible are adjustable via a configuration file (ansible.cfg). The stock configuration should be sufficient for most users, but there may be reasons you would want to change them.

TASK FILE FOR LAUNCHING THE DOCKER CONTAINER USING THE IMAGE WHICH WE HAVE CREATED USING BUILD COMMAND.

- hosts: localhost
tasks:
#Task for installing Docker
- name: "Starting Docker Services"
service:
name: docker
state: started
#Task for installing the docker-py library
- name: "Installing Python Library of docker"
command: "pip3 install docker-py"
#Task for creating a container for webserver. Port 80 is exposed for httpd webserver and port 22 is exposed for ssh.
- name: "Launching Container"
docker_container:
name: New_Webserver
image: new_image:v1
state: started
interactive: yes
tty: yes
ports:
- "1234:80"
- "1235:22"
register: image
#This task will print the conatiner IP of above container
- debug:
msg: "{{ image.container.NetworkSettings.IPAddress }}"
#Task for updating the inventory
- name: Updating Inventory
blockinfile:
path: inventory
block: |
[docker_host]
{{ image['container']['NetworkSettings']['IPAddress'] }} ansible_ssh_user=root ansible_ssh_pass=docker ansible_connection=ssh

Run the above playbook.

Inventory is also updated.

NOW WE HAVE TO CONFIGURE THE WEBSERVER

task file for webserver is given below.

- hosts: docker_host
tasks:

- name : install package
package:
name: httpd
state: present
- name: "Configuring webserver"
copy:
content: "Hii, this is a webpage inside the docker container"
dest: /var/www/html/index.html
- name: "starting webserver"
command: "/usr/sbin/httpd"

We can check by using netstat -tnlp command to see whether port is binded or not with the webserver.

Now you can access the webpage using the Base OS’s IP.

This is how Automation works for launching webserver inside the Docker Container !

--

--