如何实现从GitHub自动将Next.js/React.js应用部署至cPanel?
自动部署React.js到cPanel(GitHub Push触发)
前置要求
- cPanel主机支持Git版本控制和Node.js环境
- GitHub仓库已包含你的React项目,
package.json中配置了正确的build命令
步骤1:配置React项目
确保package.json中的scripts包含:
"scripts": { "build": "react-scripts build", // ...其他脚本 }
本地执行npm run build测试,确认生成build文件夹(静态产物目录)。
步骤2:cPanel配置Git部署
- 登录cPanel,找到Git Version Control(部分主机叫Deployments)
- 点击Create,选择Clone Repository,输入GitHub仓库的SSH/HTTPS地址,指定部署分支(如
main),设置本地存储路径(如~/repos/react-app/) - 勾选Automatic Deployment(自动部署)并保存
步骤3:设置GitHub Webhook触发部署
- 返回cPanel的Git部署页面,复制对应仓库的Webhook URL
- 打开GitHub仓库的Settings > Webhooks > Add webhook
- 粘贴Webhook URL,设置Content type为
application/json,触发事件选择Just the push event,点击Add webhook
步骤4:配置部署后构建与文件同步
在cPanel的Git部署页面,找到对应仓库的Post-deployment Command,填入以下命令(替换为你的实际路径):
cd $HOME/repos/react-app && npm install --production && npm run build && cp -r build/* $HOME/public_html/ && chmod -R 755 $HOME/public_html/
--production:跳过开发依赖安装,节省空间cp -r build/* ...:将静态产物同步到cPanel网站根目录(public_html)chmod:确保文件权限符合Web访问要求
自动部署Next.js到cPanel(GitHub Push触发)
Next.js分两种部署场景,需根据项目特性选择:
场景1:静态导出(SSG/ISR,无SSR/API路由)
步骤1:配置Next.js静态导出
在next.config.js中添加静态导出配置:
/** @type {import('next').NextConfig} */ const nextConfig = { output: 'export', // ...其他配置 } module.exports = nextConfig
本地执行npm run build测试,确认生成out文件夹(静态产物目录)。
步骤2-4:复用React部署流程
仅需将Post-deployment Command中的build替换为out:
cd $HOME/repos/next-app && npm install --production && npm run build && cp -r out/* $HOME/public_html/ && chmod -R 755 $HOME/public_html/
场景2:SSR/API路由(需Node.js服务器)
前置要求
cPanel主机支持Node.js Application Manager(或类似功能)
步骤1:cPanel创建Node.js应用
- 登录cPanel,找到Node.js(或Application Manager)
- 点击Create Application,设置:
- 应用根目录:如
~/apps/next-app/ - Node.js版本:与项目
package.json的engines字段匹配 - 启动命令:
npm start(确保项目package.json的scripts包含"start": "next start")
- 应用根目录:如
- 保存后,cPanel会自动分配端口并配置反向代理(将域名指向Node.js应用)
步骤2:配置Git部署到Node.js应用目录
- 在cPanel的Git Version Control中,克隆GitHub仓库到
~/apps/next-app/ - 开启Automatic Deployment,设置Webhook(参考React步骤3)
步骤3:配置部署后构建与重启
在Post-deployment Command中填入以下命令(替换Node.js版本路径为你的实际路径):
cd $HOME/apps/next-app && npm install --production && npm run build && /usr/local/bin/ea-nodejs18/bin/pm2 restart next-app
- 可通过
which pm2命令获取pm2的实际路径 pm2 restart:重启Node.js应用,确保新代码生效
常见问题
- 若cPanel未自动配置反向代理,可在Domains > Redirects或Apache Configuration > Include Editor中手动设置,将域名请求转发到Node.js应用的端口
- 确保项目
package.json的engines字段指定兼容的Node.js版本,避免构建失败
内容的提问来源于stack exchange,提问作者Siam Parvez
相关产品推荐
相关产品推荐

