Complete Docker Setup Guide for Next.js on VPS
Complete Docker Setup Guide for Next.js on VPS
Deploying Next.js applications on a VPS can be challenging, but Docker makes it much easier by providing consistent environments and simplified deployment. This guide will walk you through setting up a production-ready Next.js application with Docker on a VPS.
Prerequisites
Before we begin, make sure you have:
Step 1: Install Docker on Your VPS
First, connect to your VPS via SSH and install Docker:
1# Update package index2sudo apt update3 4# Install prerequisites5sudo apt install -y apt-transport-https ca-certificates curl gnupg lsb-release6 7# Add Docker's official GPG key8curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg9 10# Add Docker repository11echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null12 13# Install Docker14sudo apt update15sudo apt install -y docker-ce docker-ce-cli containerd.io docker-compose-pluginStep 2: Create Dockerfile for Next.js
In your Next.js project root, create a Dockerfile:
1# Use the official Node.js runtime as base image2FROM node:18-alpine AS base3 4# Install dependencies only when needed5FROM base AS deps6RUN apk add --no-cache libc6-compat7WORKDIR /app8 9# Copy package files10COPY package.json package-lock.json* ./11RUN npm ci12 13# Rebuild the source code only when needed14FROM base AS builder15WORKDIR /appStep 3: Configure Next.js for Standalone Output
Update your next.config.js to enable standalone output:
1/** @type {import('next').NextConfig} */2const nextConfig = {3 output: 'standalone',4 // Other config options...5}6 7module.exports = nextConfigStep 4: Create docker-compose.yml
Create a docker-compose.yml file for easier management:
1version: '3.8'2 3services:4 nextjs:5 build:6 context: .7 dockerfile: Dockerfile8 container_name: nextjs-app9 restart: unless-stopped10 ports:11 - "3000:3000"12 environment:13 - NODE_ENV=production14 - NEXT_PUBLIC_API_URL=https://api.yourdomain.com15 volumes:Step 5: Create .dockerignore
Create a .dockerignore file to exclude unnecessary files:
1node_modules2.next3.git4.gitignore5README.md6.env*.local7npm-debug.log*8yarn-debug.log*9yarn-error.log*10.DS_Store11*.pemStep 6: Build and Run Docker Container
On your VPS, clone your repository and build the Docker image:
1# Clone your repository2git clone https://github.com/yourusername/your-nextjs-app.git3cd your-nextjs-app4 5# Build the Docker image6docker compose build7 8# Run the container9docker compose up -d10 11# Check if container is running12docker ps13 14# View logs15docker compose logs -fStep 7: Set Up Nginx Reverse Proxy (Optional)
For production, set up Nginx as a reverse proxy:
1# Install Nginx2sudo apt install -y nginx3 4# Create Nginx configuration5sudo nano /etc/nginx/sites-available/nextjsAdd this configuration:
1server {2 listen 80;3 server_name yourdomain.com www.yourdomain.com;4 5 location / {6 proxy_pass http://localhost:3000;7 proxy_http_version 1.1;8 proxy_set_header Upgrade $http_upgrade;9 proxy_set_header Connection 'upgrade';10 proxy_set_header Host $host;11 proxy_cache_bypass $http_upgrade;12 proxy_set_header X-Real-IP $remote_addr;13 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;14 proxy_set_header X-Forwarded-Proto $scheme;15 }Enable the site and restart Nginx:
1sudo ln -s /etc/nginx/sites-available/nextjs /etc/nginx/sites-enabled/2sudo nginx -t3sudo systemctl restart nginxStep 8: Set Up SSL with Let's Encrypt
Secure your application with SSL:
1# Install Certbot2sudo apt install -y certbot python3-certbot-nginx3 4# Obtain SSL certificate5sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com6 7# Auto-renewal is set up automaticallyBest Practices
1. Use Multi-stage Builds
Multi-stage builds reduce the final image size significantly.
2. Set Environment Variables Securely
Use Docker secrets or environment files for sensitive data:
1services:2 nextjs:3 env_file:4 - .env.production3. Health Checks
Add health checks to your docker-compose.yml:
1services:2 nextjs:3 healthcheck:4 test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:3000/api/health"]5 interval: 30s6 timeout: 10s7 retries: 38 start_period: 40s4. Resource Limits
Set resource limits to prevent resource exhaustion:
1services:2 nextjs:3 deploy:4 resources:5 limits:6 cpus: '1'7 memory: 1G8 reservations:9 cpus: '0.5'10 memory: 512M5. Log Management
Configure log rotation:
1services:2 nextjs:3 logging:4 driver: "json-file"5 options:6 max-size: "10m"7 max-file: "3"Troubleshooting
Container won't start
Check logs: docker compose logs nextjs
Port already in use
Change the port mapping in docker-compose.yml or stop the conflicting service.
Build fails
Ensure all dependencies are in package.json and check Node.js version compatibility.
Conclusion
You now have a production-ready Next.js application running on your VPS with Docker. This setup provides:
Remember to keep your Docker images updated and monitor your application's performance regularly.
Enjoyed this article?
Support our work and help us create more free content for developers.
Stay Updated
Get the latest articles and updates delivered to your inbox.