Customizing Nginx Docker container

DockerFile

Using DockerFile you can specify instructions to build your own custom Docker container. In this example, we will customize an Nginx container by adding custom test pages and Nginx server configurations. To automate the creation of the custom Docker container we will be using a shell script to initiate DockerFile builds.

Setup files to copy into container

The DockerFile needs to be located in the same directory as the ‘content’ and ‘config’ directory. The ‘content’ and ‘config’ will be copied to their respective locations.

Example of the file setup. ‘content’ and ‘config’ are copied to the container image specified in DockerFile. Note that ‘content’ and ‘config’ are in the same directory.

DockerFile

FROM nginx
COPY content /usr/share/nginx/html
COPY config /etc/nginx
VOLUME /usr/share/nginx/html
VOLUME /etc/nginx

DockerFile build script (build_nginx_dimage.sh)

The below script is used to automate the DockerFile build. The script should be placed in the same directory as ‘boot_nginx’. The DockerFile and container content should be in the boot_nginx directory.

#!/bin/bash
clear
HL='\033[1;33m'
NC='\033[0m'

if [ ! -z $1 ]
then
	# Stop and prune container
	echo "${HL}Attempting... to stop docker='$1'.${NC}"
	docker stop $1
	echo "${HL}Attempting... docker prune containers.${NC}"
	docker container prune -f
	echo "${HL}Attempting... docker remove image.${NC}"
	docker rmi $1

	# Build docker image and run image
	echo "${HL}Building docker image...${NC}"
	cd ~/boot_nginx && docker build -f ~/boot_nginx/Dockerfile . -t $1

	# Deamon process
	if [ "$2" = "deamon" ]
	then
		echo "${HL}starting docker container as deamon.${NC}"
		cd ~ && docker run --add-host localbox:xxx.xx.xxx.xxx -d --name $1 -p 80:80 $1 nginx-debug -g 'daemon off;'
	else
		echo "${HL}ifconfig docker0 | grep inet | grep -v inet6 | awk '{print $2}').${NC}"
                echo "${HL}ip -4 addr show scope global dev eth0 | grep inet | awk '{print \$2}' | cut -d / -f 1${NC}"
		echo "${HL}nginx ready for http traffic...${NC}"
		cd ~ && docker run --add-host localbox:xxx.xx.xxx.xxx --name $1 -p 80:80 $1
	fi
fi

Note that ‘localbox:xxx.xx.xxx.xxx’ is used to enable container to connect to another container in docker using the ‘localbox’ host name. For example you have an Nginx proxy hosted on a container which needs to direct traffic toan application hosted on another container in docker.

When you first run the build script you should see something similar (see image). When you first run the build script you should see the creation of the docker image. Subsequent reruns of the script will update the container in docker.

sh build_nginx_dimage.sh name_of_container_lower_case
Example output when re-building container using the ‘build_nginx_dimage .sh’ script.

source – docker official Nginx container

Leave a Reply

Your email address will not be published. Required fields are marked *