在我的应用程序中,有几个要构建的Docker映像。
现在,我使用Makefile简化构建操作:
我的工作目录:
|- dockerfiles
|- platform
|- Dockerfile
|- Makefile
|- policy
|- Dockerfile
|- Makefile
|- some other images to build
并且平台上的Makefile是:
NAME=platform
WAR_PATH=../../build
WAR=${NAME}.war
IMAGE_NAME=inner.server:8000/containers/${NAME}:1.0.0
PORT=8080
IMAGE_ID=$(shell docker images ${IMAGE_NAME} -q)
RUNNING=$(shell docker ps --format "{{.Names}}" | grep ${NAME})
clean:
if [ "${IMAGE_ID}" != "" ]; then \
echo "remove image ${IMAGE_NAME}"; \
docker rmi ${IMAGE_NAME}; \
fi
copy:
cp ${WAR_PATH}/${WAR} .
unzip ${WAR} -d ${NAME}
build: clean
docker build -t ${IMAGE_NAME} .
if [ -f "${WAR}" ]; then \
rm ${WAR}; \
fi
echo 'Docker镜像 Build 完毕'
push:
docker push ${IMAGE_NAME}
stop:
if [ "${RUNNING}" != "" ]; then \
echo "stop ${NAME}"; \
docker stop ${NAME}; \
fi
run: stop
docker run --rm -it ${IMAGE_NAME} bash
.PHONY: clean copy build push stop run
并且策略和其他子目录中的Makefile与几乎相同,除了NAME
和WAR
变量:
NAME=policy
WAR_PATH=../../build
WAR=${NAME}-v1.0.0.war
IMAGE_NAME=inner.server:8000/containers/${NAME}:1.0.0
PORT=8080
IMAGE_ID=$(shell docker images ${IMAGE_NAME} -q)
RUNNING=$(shell docker ps --format "{{.Names}}" | grep ${NAME})
clean:
if [ "${IMAGE_ID}" != "" ]; then \
echo "remove image ${IMAGE_NAME}"; \
docker rmi ${IMAGE_NAME}; \
fi
#... The other tasks are same as above.
.PHONY: clean copy build push stop run
我的问题是:这些Makefile可以简化吗?
痛苦是:当我想添加任务时,必须将任务添加到所有这些Makefile中。
嗯,一种简单的方法就是在各个makefile文件中定义这些变量,然后为其余文件包括一个通用makefile。
例如,在platform/Makefile
中,您具有:
NAME=platform
WAR=${NAME}.war
include ../common.mk
并且在policy/Makefile
中,您具有:
NAME=policy
WAR=${NAME}-v1.0.0.war
include ../common.mk
然后在./common.mk
中,您拥有makefile的其余公共部分:
WAR_PATH=../../build
IMAGE_NAME=inner.server:8000/containers/${NAME}:1.0.0
PORT=8080
...
.PHONY: clean copy build push stop run