cicd k8s自动化部署搭建
时间: 2024-12-27 07:25:10 浏览: 6
### 使用CI/CD与Kubernetes实现自动化部署的最佳实践
#### 配置GitLab CI/CD管道文件`.gitlab-ci.yml`
为了使Spring Boot应用程序能够通过GitLab CI/CD自动构建并推送到容器镜像仓库,需要定义一个名为`.gitlab-ci.yml`的配置文件。此文件位于项目的根目录下,并指定了一系列的任务阶段,包括但不限于编译、测试以及打包应用成Docker镜像[^1]。
```yaml
image: maven:3.8.1-jdk-11
stages:
- build
- test
- deploy
variables:
DOCKER_DRIVER: overlay2
IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-$CI_PIPELINE_ID
cache:
paths:
- .m2/repository/
build_artifacts:
stage: build
script:
- mvn clean package -DskipTests=true
artifacts:
paths:
- target/*.jar
docker_build_and_push:
image: docker:latest
services:
- docker:dind
stage: deploy
before_script:
- apk add --no-cache python3 py3-pip
- pip install awscli==1.20.57
script:
- $(aws ecr get-login --region us-east-1 --no-include-email)
- docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
- docker build -t $IMAGE_TAG .
- docker push $IMAGE_TAG
```
#### 创建Kubernetes资源清单文件
创建描述所需服务和部署细节的YAML格式资源配置文件。这些文件用于告知集群怎样运行容器化的应用程序实例及其关联的服务端点。
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: springboot-app-deployment
spec:
replicas: 2
selector:
matchLabels:
app: springboot-app
template:
metadata:
labels:
app: springboot-app
spec:
containers:
- name: springboot-container
image: registry.gitlab.com/user/springboot-project:main-<pipeline-id>
ports:
- containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: springboot-service
spec:
type: LoadBalancer
selector:
app: springboot-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
```
#### 设置Kubernetes环境中的GitLab Runner
安装并注册专用Runner到目标环境中,确保其拥有足够的权限执行必要的操作,比如拉取最新的代码变更、构建新版本的应用程序镜像并将它们部署至生产环境当中去。
```bash
sudo curl -L "https://github.com/gitlab-runner-downloads/fetch?version=14.9.0&os=linux&arch=amd64" -o /usr/local/bin/gitlab-runner
sudo chmod +x /usr/local/bin/gitlab-runner
sudo useradd --create-home gitlab-runner --shell /bin/bash
sudo gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner
sudo gitlab-runner start
```
阅读全文