Deploying a Next.js application can be streamlined by automating the process with Git hooks and managing the application lifecycle with PM2. In this article, I'll walk you through setting up your server, transferring your application.
Step 1: Set Up the Server
Install Node.js, npm, pm2, git:
ssh your-username@serverIp
sudo apt update
sudo apt install -y nodejs npm
sudo npm install -g pm2
sudo apt install -y git
Step 2: Transfer Your Next.js Application to the Server
On your local machine:
Add the Remote Repository
git remote add deploy ssh://your-username@serverIp/your-username/home/apps/my-nextjs-app.git
On the server:
Create the Bare Repository
mkdir -p /your-username/home/apps/my-nextjs-app.git
cd /your-username/home/apps/my-nextjs-app.git
git init --bare
Set Up the Post-Receive Hook
cd /your-username/home/apps/my-nextjs-app.git/hooks
nano post-receive
Add the following script to the post-receive hook:
#!/bin/bash
REPO_PATH=/your-username/home/my-nextjs-app.git
APP_PATH=/your-username/home/apps/my-nextjs-app
NODE_ENV=production
GIT_WORK_TREE=$APP_PATH git checkout -f main
cd $APP_PATH
npm install
npm run build
pm2 restart nextjs-app || pm2 start npm --name "nextjs-app" -- start
Make the hook executable:
chmod +x post-receive
Step 3: Deploy Your Application
On your local machine, push your code:
git push deploy main
Conclusion
In conclusion, deploying a Next.js application on Ubuntu can be efficiently managed through manual deployment, CI/CD pipelines, containerization, cloud services, PaaS solutions, static site export, or third-party hosting services, each offering unique benefits based on scalability, ease of use, cost, and complexity
Top comments (1)
Great article ! Thx !