Configure Makefile to run command inside a container
Forgetting a command is extremely easy for me, ... that's why Makefiles have been my friends for a long time. And then ... There is nothing more frustrating than having to go back and forth from your host to the container and vice versa. What if there was an easy way to run commands inside the container but always staying in your machine?
In the following post I want to share an interesting way to use Makefile to run commands inside a container. Current example show how to run composer from the host. I'll show you three simple configurations of:
- docker-compose.yml
- Dockerfile
- Makefile
The focus here is the configuration of the Makefile so don't pay too much attention to the docker-compose.yml
file or the Dockerfile
file. They could be improved, ... but the main focus here is just the Makefile.
docker-compose.yaml
This example is trivial and just define the context of the service where we will find our Dockerfile. To keep alive the container I'll use an entrypoint. The purpose here is just to create a service that simply stay alive.
version: '3.7'
services:
php-dev-to:
restart: always
build:
context: .
entrypoint: ["tail", "-f", "/dev/null"]
Dockerfile
Here we have the Dockerfile. As you can se, ... we have just the alpine image ad the composer. Composer is installed from another image. A nice trick that I simply love.
FROM php:8.1-alpine
COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer
Makefile
Last but not least the Makefile
. This file contains few variables. Targets up and build are self explanatory. The target that convinced me to share this Makefile usages is the composer target:
composer:
$(docker_exec) $(php_container) composer $(args)
.PHONY: composer
Whenever we type make composer <something>
, the content of <something>
is sent to the container via $(args)
that is a varialbe defined via $(filter-out $@,$(MAKECMDGOALS))
. For example is possibile to install phpunit inside the container usging make composer require phpunit/phpunit
.
Here the complete Makefile.
php_container := php-dev-to
docker := docker-compose
compose := $(docker) --file docker-compose.yml
docker_exec := $(compose) exec
args = $(filter-out $@,$(MAKECMDGOALS))
build:
$(docker) up --build -d
.PHONY: build
up:
$(docker) up -d
.PHONY: up
composer:
$(docker_exec) $(php_container) composer $(args)
.PHONY: composer
Follow me
If you like this post please leave a comment below and/or start to follow me to see next articles.