
Learn how to deploy a Next js app on a VPS with this comprehensive step-by-step guide. Ensure server package repositories are up to date.
Deploying a Next.js app on a Virtual Private Server (VPS) can be straightforward with the right tools. This guide will walk you through how to deploy a Next js app using PM2 to manage the Node.js process and Caddy as the web server for handling HTTPS and reverse proxy.
sudo apt update && sudo apt upgrade -y && sudo apt autoremove -ycurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
For the latest version, refer to the official NVM repository.
echo 'export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"' >> ~/.bashrc
echo '[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"' >> ~/.bashrcsource ~/.bashrcnvm --versionnvm install --ltsnode -v
npm -vgit clone https://github.com/your_username/your_nextjs_app.git
cd your_nextjs_app
npm install
npm run buildnpm install -g pm2ecosystem.config.js file:{
"apps": [
{
"name": "nextjs",
"script": "node_modules/next/dist/bin/next",
"args": "start",
"cwd": "./",
"instances": "max",
"exec_mode": "cluster",
"env": {
"NODE_ENV": "production",
"production": true
}
}
]
}You can adjust based on your need
pm2 start ecosystem.config.jsit will start your application on background and it will keep running, pm2 also have so many feature you can learn more from there official website https://pm2.keymetrics.io/
pm2 save
pm2 startupsudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
sudo apt update
sudo apt install caddyIf this not work you can alway get updated code from official website https://caddyserver.com/docs/install#debian-ubuntu-raspbian
sudo nano /etc/caddy/Caddyfileyour_domain with your actual domain):your_domain {
reverse_proxy localhost:3000
}sudo systemctl restart caddyCaddy will automatically manage SSL/TLS certificates for you. Just make sure your domain’s DNS is correctly pointed to your VPS IP.