Aim 🥅
Simplifying life using Makefile
with Docker.
TL;DR 🩳
- Can use
make server
to build a docker image and run the container, using a Makefile. - It is really useful in cases where long docker commands create a mess (that means always).
- Can also use
make hit
to hit the docker container's exposed endpoint.
What's on the plate 🍽?
- A simple way to handle long Docker commands is to use a
Makefile
.- You can directly build the image and host with a single command through this approach
- Build docker image from
Dockerfile
in the current directory:docker build my-long-complex-docker-image-name .
- Run the docker image:
docker run -d -rm -p 8023:8000 mount type=bind,source=/home/username/github/project/docker_data,target=/app/data my-long-complex-docker-image-name
- Build docker image from
- Now this complex things can be moved to a
Makefile
to cut the command short to:make server
- You can directly build the image and host with a single command through this approach
Makefile is made to make the life of a developer simpler.
"The" Makefile 👔 🐐
IMAGE_NAME = my-long-complex-docker-image-name
HOST_PORT = 8023
DOCKER_PORT = 8000
HOST_MOUNT = /home/username/github/project/docker_data
DOCKER_MOUNT = /app/data
.PHONY server
server:
@echo "Building Docker image..."
docker build $(IMAGE_NAME) .
@echo "Clear the mess"
clear
@echo "Running Docker container..."
docker run -d -rm -p $(HOST_PORT):$(DOCKER_PORT) mount type=bind,source=$(HOST_MOUNT),target=$(DOCKER_MOUNT) $(IMAGE_NAME)
.PHONY: clean
clean:
@echo "Stopping and removing Docker containers..."
docker stop $$(docker ps -a -q --filter ancestor=$(IMAGE_NAME) --format="{{.ID}}") 2>/dev/null || true
@echo "Removing Docker image..."
docker rmi $(IMAGE_NAME) 2>/dev/null || true
.PHONY: help
help:
@echo "Available commands:"
@echo " make server - Build Docker image, clear screen, and run the server"
@echo " make clean - Stop containers and remove Docker image"
@echo " make help - Show this help message"
Make a Hit 💥 !!!
On top of all this, you can even make a hit (using curl
) on the hosted port, so no need to reconfigure Postman on every machine. Just add this to the Makefile
and use make hit
# ... rest of code ... #
.PHONY hit
hit:
@echo "Hitting the server at $(HOST_PORT) with sample data"
curl --location "http://localhost:$(HOST_PORT)$/get_post" \
--header "Content-Type: application/json" \
--data '{"id": ["post_id_1"]}'
# update the help
.PHONY: help
help:
@echo "Available commands:"
@echo " make server - Build Docker image, clear screen, and run the server"
@echo " make clean - Stop containers and remove Docker image"
@echo " make hit - Hit the endpoint with a sample curl request"
@echo " make help - Show this help message"
References 📘
Just my experience lmao 🧠