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


Available commands


All commands are listed below as follows. The TAG variable is compulsory unless it is set on server level.


make build TAG=latest


Builds an image. This bakes application into the image.


make tag TAG=latest


Tags an image.


make start TAG=latest


Starts a container.


make stop TAG=latest


Stops a container.


make restart TAG=latest


Restarts a container.


make pull TAG=latest


Pulls an image.


make push TAG=latest


Pushes an image.


make clean TAG=latest


Cleans all docker artifacts.


make login TAG=latest DOCKER_USER=username DOCKER_PASS=password


Login Docker Hub.


Structure


.
├── app
│ ├── a.php
│ └── b.php
├── docker
│ ├── 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

Makefile


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

ACCOUNT := inanzzz
SERVICE := hello_php
IMAGE := $(ACCOUNT)/$(SERVICE)


build:
$(info Make: Building "$(TAG)" tagged images.)
@docker build -t $(IMAGE):$(TAG) -f php/Dockerfile ..
@make -s tag
@make -s clean

tag:
$(info Make: Tagging image with "$(TAG)".)
@docker tag $(IMAGE):latest $(IMAGE):$(TAG)

start:
$(info Make: Starting "$(TAG)" tagged container.)
@docker run -dit --name $(SERVICE) $(IMAGE):$(TAG)

stop:
$(info Make: Stopping "$(TAG)" tagged container.)
@docker stop $(SERVICE)
@docker rm $(SERVICE)

restart:
$(info Make: Restarting "$(TAG)" tagged container.)
@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)