CICD部署

5. CI/CD自动化部署

5.1 GitHub Actions

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
# .github/workflows/deploy.yml
name: Deploy

on:
push:
branches: [ main ]

jobs:
build-and-deploy:
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v2

- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '16'

- name: Install dependencies
run: npm ci

- name: Run tests
run: npm test

- name: Build
run: npm run build

- name: Deploy to Server
uses: easingthemes/ssh-deploy@v2
with:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
REMOTE_HOST: ${{ secrets.REMOTE_HOST }}
REMOTE_USER: ${{ secrets.REMOTE_USER }}
SOURCE: "dist/"
TARGET: "/var/www/html"

5.2 GitLab CI

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
# .gitlab-ci.yml
stages:
- install
- test
- build
- deploy

install:
stage: install
script:
- npm ci
cache:
paths:
- node_modules/

test:
stage: test
script:
- npm run test
- npm run lint

build:
stage: build
script:
- npm run build
artifacts:
paths:
- dist/

deploy:
stage: deploy
script:
- scp -r dist/* user@server:/var/www/html
only:
- main

5.3 Docker部署

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Dockerfile
FROM node:16-alpine as builder

WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# nginx.conf
server {
listen 80;
server_name localhost;

location / {
root /usr/share/nginx/html;
index index.html;
try_files $uri $uri/ /index.html;
}

location /api {
proxy_pass http://backend:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# docker-compose.yml
version: '3'
services:
frontend:
build: .
ports:
- "80:80"
depends_on:
- backend

backend:
image: backend:latest
ports:
- "8080:8080"