夜猫的小站

基于makefile的docker镜像推送阿里云

Published on
阅读时间:4分钟750

本文最近一次更新于 1443 个天前,其中的内容很可能已经有所发展或是发生改变。

前言

博客为了更快的推送、下载镜像,使用了阿里云的docker镜像系统,为了更快捷的发布镜像,所以结合makefile,使用一条命名完成发布。 看完整代码的跳到结合makefile的发布流程

结合.env文件

比较麻烦的一点如果不结合环境变量,那么就需要在makefile中写入密码账号等比较隐私的信息,那么就会导致makefile不能上传到git上。为了解决这个问题,可以采用makefile导入.env文件的方式.

.env
#!make
include .env
export $(shell sed 's/=.*//' .env)

这样在makefile中就可以直接以$(DOCKER_REPO)这样的方式使用环境变量

docker 直接上传阿里云的流程

1.登录阿里云docker镜像环境

.env
docker login --username=$(账号名称) --password=$(密码) $(阿里云地址)

账号密码可以进入阿里云控制台的访问凭证中获取 image.png 我使用的是固定密码方式,有安全需求的也可以使用通过API获取临时密码访问镜像服务实例,参考阿里云的帮助文档

2.标记docker tag

docker tag $(镜像id) $(镜像仓库地址)/$(项目名称):latest
docker tag $(镜像id) $(镜像仓库地址)/$(项目名称):$(版本号)

3.推送镜像(image)

docker push $(镜像仓库地址)/$(项目名称):latest
docker push $(镜像仓库地址)/$(项目名称):$(版本号)

结合makefile的发布流程

.env文件

VERSION=1.1.6
DOCKER_PASSWORD=xxx
DOCKER_USERNAME=xxx

makefile文件

#!make
include .env
export $(shell sed 's/=.*//' .env)
# 申明仓库地址,项目名称
APP_NAME=owl
DOCKER_REPO=registry.cn-hangzhou.aliyuncs.com/linyf-owl

# docker 服务器地址
ADDRESS=registry.cn-hangzhou.aliyuncs.com
PASSWORD=$(DOCKER_PASSWORD)
USERNAME=$(DOCKER_USERNAME)

# 发布镜像任务流程
# Build the container
build-img: ## Build the container
 docker build -f ./Dockerfile.local -t $(APP_NAME) .

build-nc: ## Build the container without caching
 docker build -f ./Dockerfile.local --no-cache -t $(APP_NAME) .

# 登录阿里云
login-ali:
 docker login --username=$(USERNAME) --password=$(PASSWORD) $(ADDRESS)
publish-latest: tag-latest
 @echo 'publish latest to $(DOCKER_REPO)'
 docker push $(DOCKER_REPO)/$(APP_NAME):latest

publish-version: tag-version
 @echo 'publish $(VERSION) to $(DOCKER_REPO)'
 docker push $(DOCKER_REPO)/$(APP_NAME):$(VERSION)
# docker tagging
tag: tag-latest tag-version

## Generate container `{version}` tag
tag-latest: 
 @echo 'create tag latest'
 docker tag $(APP_NAME) $(DOCKER_REPO)/$(APP_NAME):latest

## Generate container `latest` tag
tag-version: 
 @echo 'create tag $(VERSION)'
 docker tag $(APP_NAME) $(DOCKER_REPO)/$(APP_NAME):$(VERSION)
# 推送到阿里云
publish: login-ali publish-latest publish-version

release: build-nc publish

执行

执行 make release就可以完成构建

附录Dockerfile.local

博客是基于golang写的

FROM golang:1.15-alpine3.13 as builder
RUN echo -e "https://mirrors.aliyun.com/alpine/v3.13/main" > /etc/apk/repositories
RUN apk update && apk upgrade && apk add --no-cache alpine-sdk

ARG GOOS=linux
ARG GOARCH=amd64

ENV GOOS=$GOOS
ENV GOARCH=$GOARCH
ENV GO111MODULE=on
ENV GOPROXY=https://goproxy.cn

ENV CGO_ENABLED=0
ENV GIN_MODE=release

COPY . /build
WORKDIR /build
RUN go build -o owl .

FROM alpine:3.13
# 换源
RUN echo -e "https://mirrors.aliyun.com/alpine/v3.13/main" > /etc/apk/repositories
RUN apk add --no-cache bash
RUN apk add --update --no-cache ca-certificates
COPY --from=builder /build /owl
# RUN chown owl /owl
USER root
EXPOSE 8085
WORKDIR /owl
CMD ["sh","-c","/owl/owl"]

参考文章