January 19, 2023
Makefile is a building tool that's been around forever; and while some of us may remember it from building our first couple projects (and may hate those times and the struggle); But I believe it's an awesome tool that by just adding a single file to our project It can speed / easy up our daily work flow on: how we build, run locally, etc our 'Dockerized' projects.
TLDR Github project: https://github.com/danielm/docker-compose-makefiles
Lets suppose that in our project we want:
I like going straight to the point, so lets look at the files we need:
project/
├── docker-compose.yml
├── docker-compose.development.yml
├── docker-compose.production.yml
├── .env
└── Makefile
Nothing special here, a base docker-composer, and the other two to customize/extend each of our environments.
So let's look at our Makefile, you can split it in three points:
# Include env vars
include .env
# Export them all
export $(shell sed 's/#.*//g; /^$/d; s/=.*//' .env)
# For versioning
TAG_VERSION ?= $(shell git log --format="%h" -n 1)
export TAG_VERSION := $(TAG_VERSION)
# Pattern rule to build environment-specific containers
build:
docker compose -f docker-compose.yml -f docker-compose.$(ENVIRONMENT).yml build
# Target to start environment-specific images
up:
docker compose -f docker-compose.yml -f docker-compose.$(ENVIRONMENT).yml up -d
down:
docker compose -f docker-compose.yml -f docker-compose.$(ENVIRONMENT).yml down
logs:
docker compose -f docker-compose.yml -f docker-compose.$(ENVIRONMENT).yml logs -f
push:
docker push ${DOCKER_REPOSITORY}/${PROJECT_NAME}:${TAG_VERSION}-${ENVIRONMENT}
release:
docker tag ${DOCKER_REPOSITORY}/${PROJECT_NAME}:${TAG_VERSION}-${ENVIRONMENT} ${DOCKER_REPOSITORY}/${PROJECT_NAME}:latest
docker push ${DOCKER_REPOSITORY}/${PROJECT_NAME}:latest
Now we have access to these commands:
# Build our image and tags it with: {GITHASH-ENVIRONMENTNAME}
$ make build
# Bings it up
$ make up
# ... and down
$ make down
# Shows log outup
$ make logs
# Push the current tag built by 'build'
$ make push
# Pushes a new tag 'latest' from our current built
$ make release
This was just a simple example on how you could optimize a little bit how you build your projects!
Here is a full project to try it out: https://github.com/danielm/docker-compose-makefiles
Note: Included a NodeJS project (just printing Hello-World) just to demonstrate a full project building flow
I'm a 32-years old programmer and web developer currently living in Montevideo, Uruguay. I been programming since I was about 15 y.o, and for the past 12 actively working in the area.