Appearance
CI/CD 集成
将 Docker 集成到 CI/CD 流水线,实现自动构建、测试、部署,是现代软件交付的标准实践。
基本流程
代码推送
↓
CI 触发构建
↓
运行测试(在容器中)
↓
构建 Docker 镜像
↓
推送到镜像仓库
↓
部署到目标环境GitHub Actions
基础构建推送
yaml
# .github/workflows/docker.yml
name: Docker Build and Push
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
IMAGE_NAME: yourusername/myapp
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=sha,prefix=,format=short
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
platforms: linux/amd64,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max完整 CI/CD 流水线
yaml
# .github/workflows/cicd.yml
name: CI/CD Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run tests in container
run: |
docker build --target test -t myapp-test .
docker run --rm myapp-test npm test
security-scan:
runs-on: ubuntu-latest
needs: test
steps:
- uses: actions/checkout@v4
- name: Build image
run: docker build -t myapp:${{ github.sha }} .
- name: Run Trivy scan
uses: aquasecurity/trivy-action@master
with:
image-ref: myapp:${{ github.sha }}
severity: HIGH,CRITICAL
exit-code: 1
build-push:
runs-on: ubuntu-latest
needs: [test, security-scan]
if: github.ref == 'refs/heads/main'
outputs:
image-tag: ${{ steps.meta.outputs.version }}
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ${{ secrets.REGISTRY_HOST }}
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ secrets.REGISTRY_HOST }}/myapp
tags: |
type=sha,format=short
type=raw,value=latest
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
cache-from: type=gha
cache-to: type=gha,mode=max
deploy:
runs-on: ubuntu-latest
needs: build-push
environment: production
steps:
- name: Deploy to server
uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.DEPLOY_HOST }}
username: ${{ secrets.DEPLOY_USER }}
key: ${{ secrets.DEPLOY_SSH_KEY }}
script: |
cd /app
docker compose pull
docker compose up -d --no-deps api
docker compose exec -T api sh -c "npm run migrate"GitLab CI/CD
yaml
# .gitlab-ci.yml
stages:
- test
- build
- deploy
variables:
IMAGE_NAME: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
DOCKER_BUILDKIT: "1"
test:
stage: test
image: docker:latest
services:
- docker:dind
script:
- docker build --target test -t test-image .
- docker run --rm test-image npm test
build:
stage: build
image: docker:latest
services:
- docker:dind
script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- docker build -t $IMAGE_NAME .
- docker tag $IMAGE_NAME $CI_REGISTRY_IMAGE:latest
- docker push $IMAGE_NAME
- docker push $CI_REGISTRY_IMAGE:latest
only:
- main
deploy_production:
stage: deploy
script:
- ssh $DEPLOY_USER@$DEPLOY_HOST "
cd /app &&
docker compose pull &&
docker compose up -d --no-deps api"
environment:
name: production
url: https://example.com
only:
- main
when: manual # 手动触发部署Jenkins Pipeline
groovy
// Jenkinsfile
pipeline {
agent any
environment {
DOCKER_IMAGE = "myregistry.com/myapp"
DOCKER_TAG = "${env.BUILD_NUMBER}"
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Test') {
steps {
sh 'docker build --target test -t myapp-test .'
sh 'docker run --rm myapp-test npm test'
}
}
stage('Build') {
steps {
sh "docker build -t ${DOCKER_IMAGE}:${DOCKER_TAG} ."
sh "docker tag ${DOCKER_IMAGE}:${DOCKER_TAG} ${DOCKER_IMAGE}:latest"
}
}
stage('Push') {
steps {
withCredentials([usernamePassword(
credentialsId: 'registry-credentials',
usernameVariable: 'REGISTRY_USER',
passwordVariable: 'REGISTRY_PASS'
)]) {
sh "echo ${REGISTRY_PASS} | docker login -u ${REGISTRY_USER} --password-stdin myregistry.com"
sh "docker push ${DOCKER_IMAGE}:${DOCKER_TAG}"
sh "docker push ${DOCKER_IMAGE}:latest"
}
}
}
stage('Deploy') {
when {
branch 'main'
}
steps {
sshagent(['deploy-key']) {
sh """
ssh user@production-server '
cd /app &&
docker compose pull &&
docker compose up -d --no-deps api
'
"""
}
}
}
}
post {
always {
sh 'docker system prune -f'
}
success {
echo 'Pipeline succeeded!'
}
failure {
echo 'Pipeline failed!'
}
}
}Dockerfile 支持测试阶段
dockerfile
# 多阶段 Dockerfile,包含测试阶段
FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci
FROM node:20-alpine AS test
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run lint
CMD ["npm", "test"]
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:20-alpine AS production
RUN addgroup -S app && adduser -S app -G app
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
USER app
CMD ["node", "dist/main.js"]总结
CI/CD 集成要点:
- 测试先行:先运行测试,失败则停止后续步骤
- 安全扫描:构建后自动扫描镜像漏洞
- 构建缓存:利用 GitHub Actions Cache 等加速构建
- 多平台构建:使用 buildx 支持 ARM64
- 环境隔离:开发/测试/生产使用不同标签
- 回滚能力:保留历史镜像,出问题可快速回滚