对于大学,我正在使用
Node.js
创建一个非常简单的项目。我想要的是设置对托管在 Google Cloud
中的虚拟机的持续交付。
使用
GitHub Actions
,我创建了一个yaml
来使用node.js构建项目。
name: Node.js CI
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18.x, 20.x, 22.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps:
- uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm ci
- run: npm run build --if-present
然后,我创建了
Dockerfile
来创建容器
FROM node:latest
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]
现在,我在 Google 中找不到将此映像部署到虚拟机的操作。我读过这些文件:
但它们非常复杂,并且没有与 Docker 集成。有任何文档吗?或者您能给我使用的 yaml 吗?
您可以使用 SSH 访问您的虚拟机。
在您的 github 操作中,使用任何 SSH 操作来连接您的虚拟机,并在那里提取最新的代码。这样,每当主分支上的代码更新时,代码都会自动传送到您的虚拟机。
使用此命令在本地计算机上生成 SSH 密钥。
ssh-keygen -t rsa -b 4096 -C "[email protected]"
将生成的公钥复制到虚拟机上的“~/.ssh/authorized_keys”文件。
将私钥、VM IP、docker 用户名和 docker hub 令牌作为秘密添加到您的 GitHub 存储库。
在构建步骤之后在 YAML 文件中添加一个新步骤,以登录 docker hub 并更新映像。
之后添加新作业,通过 docker hub 的 SSH 访问将最新映像拉入虚拟机。
name: CI/CD Pipeline
on:
push:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '16'
- run: npm ci
- run: npm run build --if-present
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ vars.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and Push Docker Image
run: |
docker build -t your-dockerhub-username/your-app-name:latest .
docker push your-dockerhub-username/your-app-name:latest
deploy:
runs-on: ubuntu-latest
needs: build
steps:
- name: Install SSH client
run: sudo apt-get install -y openssh-client
- name: Add SSH key
uses: shimataro/ssh-key-action@v2
with:
key: ${{ secrets.SSH_PRIVATE_KEY }}
known_hosts: ${{ secrets.GCP_VM_IP }}
- name: Deploy to Google Cloud VM
run: |
ssh -o StrictHostKeyChecking=no username@${{ secrets.GCP_VM_IP }} << 'EOF'
docker pull your-dockerhub-username/your-app-name:latest
docker stop your-container-name || true
docker rm your-container-name || true
docker run -d --name your-container-name -p 3000:3000 your-dockerhub-username/your-app-name:latest
EOF
这将连接到您的虚拟机并从您的存储库中下载最新代码。现在,每次将代码推送到主分支时,Github Actions 都会自动将最新版本的代码部署到 VM。