In this example we are going to keep docker compose commands in Makefile and use make command to interact with them.


Available commands


All commands are listed below as follows. The TAG and ENV variables are compulsory unless they are set on server level.


make build TAG=latest ENV=dev


Builds all images.


make start TAG=latest ENV=dev


Starts all containers. The test and dev env will have application exposed to the host OS. In the case of prod and stag env, the application will be baked into the container so it won't be exposed to the host OS.


make stop TAG=latest ENV=dev


Stops all containers.


make restart TAG=latest ENV=dev


Restarts all containers.


make pull TAG=latest ENV=dev


Pulls the image.


make push TAG=latest ENV=dev


Pushes an image.


make clean TAG=latest ENV=dev


Cleans all docker artifacts.


make login TAG=latest ENV=dev DOCKER_USER=username DOCKER_PASS=password


Login Docker Hub.


Structure


.
├── app
│   ├── a.php
│   └── b.php
├── docker
│   ├── docker-compose.override.yml
│   ├── docker-compose.yml
│   ├── .env
│   ├── Makefile
│   └── php
│   └── Dockerfile
└── .gitignore

Files


a.php


echo 'Hello a'.PHP_EOL;

b.php


echo 'Hello b'.PHP_EOL;

Dockerfile


FROM php:7.2-cli-alpine

COPY ./app /app

CMD tail -f /dev/null

.env


ACCOUNT_NAME=inanzzz
COMPOSE_PROJECT_NAME=hello
TAG=latest

docker-compose.override.yml


version: '3'

services:

php:
volumes:
- ../app:/app:rw

docker-compose.yml


version: '3'

services:

php:
build:
context: ..
dockerfile: ./docker/php/Dockerfile
image: "${ACCOUNT_NAME}/${COMPOSE_PROJECT_NAME}_php:${TAG}"
hostname: php
working_dir: /app

Makefile


ifndef TAG
$(error The TAG variable is missing.)
endif

ifndef ENV
$(error The ENV variable is missing.)
endif

ifeq ($(filter $(ENV),test dev stag prod),)
$(error The ENV variable is invalid.)
endif

ifeq (,$(filter $(ENV),test dev))
COMPOSE_FILE_PATH := -f docker-compose.yml
endif


IMAGE := inanzzz/hello_php


build:
$(info Make: Building "$(ENV)" environment images.)
@TAG=$(TAG) docker-compose build --no-cache
@make -s clean

start:
$(info Make: Starting "$(ENV)" environment containers.)
@TAG=$(TAG) docker-compose $(COMPOSE_FILE_PATH) up -d

stop:
$(info Make: Stopping "$(ENV)" environment containers.)
@docker-compose stop

restart:
$(info Make: Restarting "$(ENV)" environment containers.)
@make -s stop
@make -s start

push:
$(info Make: Pushing "$(TAG)" tagged image.)
@docker push $(IMAGE):$(TAG)

pull:
$(info Make: Pulling "$(TAG)" tagged image.)
@docker pull $(IMAGE):$(TAG)

clean:
@docker system prune --volumes --force

login:
$(info Make: Login to Docker Hub.)
@docker login -u $(DOCKER_USER) -p $(DOCKER_PASS)