docker-一个简单的shell脚本:docker构建、tag、push镜像流程

#!/bin/bash

VERSION="$1"
yamlversion="$2"

if [ -z "$VERSION" ]; then
echo "Usage: build-and-deploy.sh $VERSION  $yamlversion"
exit 1
fi

# Delete existing resources
kubectl delete -f my-jll-example-netty-springboot-tcp.yaml

# Build and push docker image
docker build -t my-jll-tcp:$VERSION .
docker tag my-jll-tcp:$VERSION registry:5000/my-jll-tcp:$VERSION
docker push registry:5000/my-jll-tcp:$VERSION

# Deploy new resources
sed -i "s/$yamlversion/$VERSION/g" my-jll-example-netty-springboot-tcp.yaml

kubectl create -f my-jll-example-netty-springboot-tcp.yaml
```

然后给该脚本文件添加可执行权限:

```
chmod +x build-and-deploy.sh
```

现在你可以使用以下命令来运行这个脚本,并传入版本号作为参数:

```
./build-and-deploy.sh 1.8
```

脚本将自动删除已有资源、构建和推送docker镜像、然后部署新资源。其中构建和推送docker镜像中的版本号将取自参数,并且在部署新资源时,my-jll-example-netty-springboot-tcp.yaml文件中的“{VERSION}”会被替换为该参数中的版本号。

一个demo:

1. 获取参数输出参数,做为docker镜像的版本号、标签号。

2.从pod资源清单文件中获取第19行,用awk以冒号做为分隔符,分割后获取第四列版本号,并赋值给yversion。

3.打印参数日志。

4.判断参数是否存在,不存在退出,并打印提示日志。

5.删除部署的pod。

6.构建docker镜像。

7.tag docker镜像。

8.push镜像到registry:5000 私有仓库。

9.用sed命令,查询要部署的pod资源清单中yversion,并替换为VERSION。

10.部署pod。

#!/bin/bash
#1. 获取参数输出参数,做为docker镜像的版本号、标签号。
VERSION="$1"

#2.从pod资源清单文件中获取第19行,用awk以冒号做为分隔符,分割后获取第四列版本号,并赋值给yversion。
yversion=$(sed -n '19p' my-jll-example-netty-springboot-tcp.yaml|awk -F':' '{print $4}')
#
3.打印参数日志。
echo "VERSION:$VERSION, yversion:$yversion"

#4.判断参数是否存在,不存在退出,并打印提示日志。
if [ -z "$VERSION" ]; then
echo "Usage: build-and-deploy.sh $VERSION  $yamlversion"
exit 1
fi

#5.删除部署的pod。
# Delete existing resources
kubectl delete -f my-jll-example-netty-springboot-tcp.yaml

#6.构建docker镜像。
# Build and push docker image
docker build -t my-jll-tcp:$VERSION .

#7.tag docker镜像。
docker tag my-jll-tcp:$VERSION registry:5000/my-jll-tcp:$VERSION

#8.push镜像到registry:5000 私有仓库。
docker push registry:5000/my-jll-tcp:$VERSION

#9.用sed命令,查询要部署的pod资源清单中yversion,并替换为VERSION。
# Deploy new resources
sed -i "s/$yversion/$VERSION/g" my-jll-example-netty-springboot-tcp.yaml

#10.部署pod。
kubectl create -f my-jll-example-netty-springboot-tcp.yaml

你可能感兴趣的:(docker,docker,容器,运维,shell)