How to deploy your Next.js website to a Virtual Machine
This tutorial will focus on deploying Next.js to a Virtual Machine.
Prerequisites
- Linux based cloud server
- Basic understanding of command-line interface (CLI) and terminal usage
- A Next.js application (if you don’t have one, use
npx create-next-app my-app
)
Steps
Deploy your Cloud Server
- Choose a Cloud Server with sufficient resources (CPU, RAM) to handle your application’s traffic.
- Select an appropriate operating system (OS) like Ubuntu or Debian, which are commonly used for Node.js deployments.
Connect to the VM
Use a tool like SSH to establish a secure connection to your VM. Refer to your cloud provider’s documentation for specific commands and authentication methods.
Set Up the Server Environment
Update package lists:
sudo apt update
sudo apt install nodejs npm
node -v
npm -v
Clone or Transfer Your Next.js App
If your app is in a Git repository, clone it using SSH:
git clone git@github.com:your-username/your-app.git
Alternatively, upload the built application files (from ./out
after running npm run build
) to the VM using a method like SCP or SFTP.
Install Dependencies and Build the Application
cd your-app
Install production dependencies:
npm install --production ``` (or `yarn install --production`)
npm run build ``` (or `yarn build`)
Configure a Process Manager (Optional):
Process managers (PMs) like PM2 or forever can help keep your Next.js server running automatically and handle restarts.
Install a PM (e.g., using npm install pm2 -g
):
npm install pm2 -g
pm2 start npm -- start # Adjust the port if needed (e.g., pm2 start npm -- start -p 8080)