In this article, we will explore how to create a customized Makefile to effortlessly copy data during a Docker Nginx installation. We will use a different Nginx image (basicnginx:latest) and configure logs to be written to /var/log/nginx/* files.
Prerequisites
To follow along, you will need the following:
- Docker installed on your system
- Basic understanding of Makefiles, Docker, and Nginx
Makefile Basics
Makefiles are used to automate the build process of software. They contain instructions called rules that define how to build, clean, or run a software project.
Makefile Structure
A Makefile consists of target rules, each comprising a target, dependencies, and commands:
target: dependencies
commands
Creating a Customized Makefile
We'll create a Makefile called Dockerfile-Makefile.mk, which will have two main targets: build and run.
build Target
The build target creates a Docker image based on the basicnginx:latest image and copies custom data to it. Create the following rules inside the Makefile:
build:
docker build -t custom-nginx .
Now, we need to define a rule that copies custom data to the Docker image. Add the following rule:
COPY_FILES = index.html custom.conf
copy-data:
mkdir -p nginx/html nginx/conf.d
docker cp $(COPY_FILES) $(IMAGE_ID)nginx/
In this rule, we define a variable COPY_FILES that contains a list of files to be copied and create necessary directories in the Docker image. The docker cp command copies the files to the Docker image.
run Target
The run target starts the Docker container based on the built image and sets up logs to be written to specific files:
run:
docker run -d -p 80:80 -v $(PWD)/logs:/var/log/nginx --name custom-nginx custom-nginx
This rule uses the docker run command to start the container with the following flags:
-d: Run the container in detached mode-p 80:80: Map local port 80 to container port 80-v $(PWD)/logs:/var/log/nginx: Bind the locallogsdirectory to the Docker container's/var/log/nginxdirectory, allowing logs to be written to local files.--name custom-nginx: Set the container name tocustom-nginx
Full Makefile
Here is the complete Makefile:
IMAGE_ID=$(shell docker images | grep custom-nginx | cut -d' ' -f3)
COPY_FILES = index.html custom.conf
build:
docker build -t custom-nginx .
copy-data:
mkdir -p nginx/html nginx/conf.d
docker cp $(COPY_FILES) $(IMAGE_ID)nginx/
run:
docker run -d -p 80:80 -v $(PWD)/logs:/var/log/nginx --name custom-nginx custom-nginx
This article covered how to create a customized Makefile with instructions to build and run a Docker basicnginx:latest image. We also showed how to copy custom files to the Docker image and configure the Nginx logs to be written to specific files.
References
-
Docker documentation: https://docs.docker.com/engine/reference/builder/
-
Makefile documentation: https://www.gnu.org/software/make/manual/make.html