Decoding Docker - Part 3 : Docker files

Hope you have gone through the Part1 and Part2 of  my blog series on Docker. In this post on my Docker series, I am exploring the creation of Docker images

There are multiple ready made docker images available in Docker hub, which you could simply pull and use. However, what if you need a different combination of software versions than what is ready available. Simple, you create an image of your own with all required softwares installed

There are two options to do this.The easiest option is to pull a base image and install everything you want, commit the container as a new image. What if you would like to make some changes down the line? You may have to redo the whole thing. That is where the option to create image using docker file helps. You can simply write a docker file to install and configure the required software. If you wish to make some changes at a later point, you could  edit the docker file and build a new image

In this example , I will explain the process of creating an docker image with apache installed, with the relevant ports opened in it. Lets start with creating a docker file. It is a simple text file with the name "Dockerfile"

#vi Dockerfile

We will be using the Centos base image, so the first line of the docker file explains which image to use

FROM centos

Now lets install all required softwares using the run command

RUN yum -y update
RUN yum -y install python-setuptools
RUN easy_install supervisor
RUN mkdir -p /var/log/supervisor
RUN yum -y install which
RUN yum -y install git

Now build the docker file to an image

Docker build –t  custom/base .

Notice the "." at the end. You should run the command from the directory where "Dockerfile" exists. Now you have created your base image. Lets install apache next. Edit the docker file and add the following content

FROM custom/base
RUN yum -y install httpd
ADD supervisord.conf /etc/supervisord.conf
EXPOSE 22 80 
CMD ["/usr/bin/supervisord"]

We have installed  supervisord in the base image to manage the processes within the container, point in case the apache service. Now, lets write a supervisord config files to start the service on container startup

vi supervisord.conf

Add the following content

[supervisord]
nodaemon=true

[program:httpd]
command=/bin/bash -c "exec /usr/sbin/apachectl –k start"

Run dockerbuild to create the image

Docker build –t  custom/httpd .

Now lets spin up a container from the image

sudo docker run -p 80:80 -v /root/htdocs:/var/www/html -t -i custom/httpd

Note: You can create a folder named /root/htdocs and use the -v switch to mount this folder at  /var/www/html of the container, so that the storage is persistent
The -p switch will map the 80 port of the container to 80 port of the host



Comments

Popular Posts