这段时间刚考完试,正好提到了自动化部署,周六花了一天时间浅学了一下
思路
- 项目上传GitHub
- GitHub Actions对项目进行编译并发布到DockerHub
- Github Actions通过SSH连接到服务器运行Docker Compose进行部署
配置文件
Dockerfile
这次的项目仍然采用Docker进行构建
参考文件Dockerfile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| FROM golang:1.17.8-alpine as builder
RUN apk --no-cache add git
MAINTAINER cunoe
WORKDIR /go/src/cunoe/
COPY . .
RUN GO111MODULE=on CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o app
FROM alpine:latest as prod
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/cunoe/app .
CMD ["./app"]
|
这是项目里实际用到的Dockerfile,与我之前的构建不同,这次我采用的是多阶段构建,其好处就是有效的缩小了最终产生的镜像体积,同时更加便于维护与使用,你可以随时在某一阶段停下。通过这种方式构建的镜像由于只存在二进制文件,故其体积几乎只有二进制文件的大小,便于服务器进行部署。
.github/workflows/Deploy.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| name: deploy
on: push: branches: [ master ] pull_request: branches: [ master ]
jobs:
build: runs-on: ubuntu-latest
steps: - name: Set up QEMU uses: docker/setup-qemu-action@v1 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v1 - name: Login to DockerHub uses: docker/login-action@v1 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Build and push id: docker_build uses: docker/build-push-action@v2 with: push: true tags: cunoe/hello:latest
deploy: runs-on: ubuntu-latest needs: [build] steps: - name: SSH Remote Commands uses: appleboy/ssh-action@master with: host: ${{ secrets.HOST }} username: ${{ secrets.USERNAME }} port: ${{ secrets.PORT }} password: ${{ secrets.PASSWORD }} script: ${{ secrets.COMMAND }}
|
后记
如此就完成了GitHub Actions的布置
当然你可以不采用Docker官方提供的Actions,也有不错的开源Actions如:wuhan005/publish-docker-action
下面是服务器的参考命令
1 2 3 4 5
| #!/bin/bash docker stop cunoe-hello docker rm cunoe-hello docker rmi cunoe/hello docker compose -f /home/cunoe/docker-compose.yml up -d cunoe-hello
|
通过Docker Compose可以很方便的去管理Docker容器