github actions 自动部署 standalone模式的nextjs
1.在next.config.js
中开启standalone
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
}
module.exports = nextConfig
2.编写github actions
的deploy.yml
创建.github/workflows/deploy.yml
文件(.github前面有个点)
name: 部署
on:
push:
branches:
- main
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: 检出代码
uses: actions/checkout@main
- name: 设置node版本
uses: actions/setup-node@v4
with:
node-version: "22"
- name: 安装pnpm
run: npm install pnpm -g
- name: 安装依赖
run: pnpm install
- name: 生成prisma client
run: npx prisma generate
- name: Build 打包
run: npm run build
- name: cp to Server 拷贝standalone里的所有文件
uses: appleboy/[email protected]
with:
host: "126.11.31.123"
username: root
key: ${{ secrets.SSH_PRIVATE_KEY }}
port: 22
source: ".next/standalone/"
target: "/root/test/"
overwrite: true
strip_components: 2 #这里填写2是去掉前缀不然会把 .next/standalone/ 这两个文件夹一起拷贝过去的
- name: cp to Server 因为上一步会把standalone里的.next文件夹拷贝过来,而项目的static文件夹需要放在.next文件里
uses: appleboy/[email protected]
with:
host: "126.11.31.123"
username: root
key: ${{ secrets.SSH_PRIVATE_KEY }}
port: 22
source: ".next/static"
target: "/root/test/.next/"
overwrite: true
strip_components: 1 #这里填写1会把static(包含文件夹)放在 /root/test/.next/ 里
- name: cp to Server 把项目根目录的public和pm2.json拷贝到/root/test里
uses: appleboy/[email protected]
with:
host: "126.11.31.123"
username: root
key: ${{ secrets.SSH_PRIVATE_KEY }}
port: 22
source: "public,pm2.json"
target: "/root/test/"
overwrite: true
- name: 部署脚本
uses: appleboy/ssh-action@master
with:
host: "126.11.31.123"
username: root
key: ${{ secrets.SSH_PRIVATE_KEY }}
port: 22
#注意要带--env production不然pm2.json中定义的环境变量不生效
script: "cd /root/test && pm2 restart pm2.json --env production"
3.编写pm2
启动文件pm2.json
{
"apps": [
{
"name": "app",
"script": "./server.js",
"exec_mode": "cluster_mode",
"max_memory_restart": "1000M",
"instances": 2,
"env_production": {
"NODE_ENV": "production",
"PORT": 3000, # 监听的端口
"HOSTNAME": "0.0.0.0"
}
}
]
}
License:
CC BY 4.0