1. Server environment preparation
1. Installation dependencies: · Requires an environment (LTS version is recommended).
# UbuntuExample curl -fsSL /setup_lts.x | sudo -E bash - sudo apt-get install -y nodejs
· PM2 (process management tool, used to keep the application running):
sudo npm install -g pm2
· Nginx (optional for reverse proxy and static resource processing):
sudo apt install
· 2. nginx configuration firewall · Open necessary ports (such as 80, 443, 3000):
sudo ufw allow 80 /tcp sudo ufw allow 443 /tcp sudo ufw allow 3000 /tcp sudo ufw reload
2. Project configuration and construction
1. Upload the code to the server ·Clone the project through Git (make sure the server has permission to access the repository):
git clone cd your-project
You can also manually upload the code to compress the package and decompress it.
2. Install dependencies and build · Install dependencies:
npm install --production
·Environment variable configuration: Create or update . files in the project root directory. This file will be read during build (variables need to be exposed to the client with the NEXT_PUBLIC_ prefix). · Build the project:
npm run build
2. Start the service
· Use PM2 to start:
pm2 start npm --name "next-app" -- start pm2 save pm2 startup
3. Configure Nginx reverse proxy (recommended)
1. Create an Nginx configuration file · Create a new file /etc/nginx/sites-available/next-app, the content is as follows:
server { listen 80; server_name ; # Replace with the internal domain name or IP of the company location / { proxy_pass http://localhost:3000; # Forward to service proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } # Static resource cache (optional) location /_next/static { alias /path/to/your-project/.next/static; expires 365d; access_log off; } }
2. Enable configuration and restart Nginx
sudo ln -s /etc/nginx/sites-available/next-app /etc/nginx/sites-enabled/ sudo nginx -t # Test whether the configuration is correctsudo systemctl restart nginx
4. HTTPS configuration (optional)
Use Let’s Encrypt to apply for a certificate (requires a public domain name) or issue it within the company’s internal CA. Modify the Nginx configuration to listen to port 443 and add the SSL certificate path:
server { listen 443 ssl; server_name ; ssl_certificate /path/to/; ssl_certificate_key /path/to/; # ...Other configurations are the same as above}
V. Verification and monitoring
1. Check the service status
pm2 status # Check the PM2 process statussystemctl status nginx # examineNginxWhether to run
2. View the log
pm2 logs next-app # logjournalctl -u nginx -f # Nginxlog
6. Advanced optimization (optional)
1. Use Docker containerized deployment · Create a Dockerfile:
FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm install --production COPY . . RUN npm run build CMD ["npm", "start"]
· Build the image and run it:
docker build -t next-app . docker run -d -p 3000:3000 next-app
2. Configure CI/CD
· Automatically trigger deployment scripts through Jenkins/GitLab CI.
- Environment variables: Ensure that production environment variables (such as API addresses) are correctly configured and sensitive information should not be submitted to the code base.
- Resource limitations: The memory limit may need to be adjusted. You can add –max-old-space-size=4096 at startup.
- Backup and rollback: Back up the old version before deployment, which facilitates quick rollback.
After completing the above steps, access the server's IP or domain name to view the successfully deployed application.
Complete deployment script:
The following is a complete deployment script designed for the environment, including dependency installation, project construction, process management and Nginx reverse proxy configuration, which can be saved and executed directly:
#!/bin/bash # Deployment script: Automatically deploy the project to the local server (environment)#Usage method: chmod +x && ./# ---------------------------------- # Configuration area (modify according to actual situation)# ---------------------------------- PROJECT_NAME="my-next-app" # Project NamePROJECT_PORT=3000 # Service PortPROJECT_GIT_REPO="/yourusername/" # Git repository addressPROJECT_DIR="/var/www/$PROJECT_NAME" # Project deployment directoryNGINX_AVAILABLE="/etc/nginx/sites-available/$PROJECT_NAME.conf" # Nginx configuration pathNGINX_ENABLED="/etc/nginx/sites-enabled/$PROJECT_NAME.conf" #Nginx enable link# ---------------------------------- # Color output function# ---------------------------------- RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[0;33m' NC='\033[0m' # Restore default colorsuccess() { echo -e "${GREEN}$1${NC}"; } error() { echo -e "${RED}$1${NC}"; exit 1; } warning() { echo -e "${YELLOW}$1${NC}"; } # ---------------------------------- # 1. Installation dependencies# ---------------------------------- install_dependencies() { success "\n[1/6] Install system dependencies..." # Install (LTS version) if ! command -v node &> /dev/null; then warning "Not installed, installing..." curl -fsSL /setup_lts.x | sudo -E bash - sudo apt-get install -y nodejs || error "Installation failed" fi # Install PM2 if ! command -v pm2 &> /dev/null; then sudo npm install -g pm2 || error "PM2 installation failed" fi # Install Nginx (optional) if ! command -v nginx &> /dev/null; then warning "Nginx is not installed, installing..." sudo apt install -y nginx || error "Nginx installation failed" fi } # ---------------------------------- # 2. Configure the firewall# ---------------------------------- configure_firewall() { success "\n[2/6] Configure the firewall..." sudo ufw allow $PROJECT_PORT/tcp # Open port sudo ufw allow 'Nginx Full' # Open HTTP/HTTPS sudo ufw reload } # ---------------------------------- # 3. Pull project code# ---------------------------------- clone_project() { success "\n[3/6] Pull project code..." if [ -d "$PROJECT_DIR" ]; then warning "A existing project directory was detected, update the code..." cd $PROJECT_DIR git pull || error "Code pull failed" else sudo mkdir -p $PROJECT_DIR sudo chown -R $USER:$USER $PROJECT_DIR git clone $PROJECT_GIT_REPO $PROJECT_DIR || error "Code cloning failed" cd $PROJECT_DIR fi } # ---------------------------------- # 4. Install dependencies and build# ---------------------------------- build_project() { success "\n[4/6] Install dependencies and build..." npm install --production || error "Dependency installation failed" # Check whether the environment variable file exists if [ ! -f . ]; then warning "A missing . file was detected, please create it manually!" touch . fi npm run build || error "Project construction failed" } # ---------------------------------- # 5. Start the PM2 process# ---------------------------------- start_pm2() { success "\n[5/6] Start the PM2 process..." # Check whether a process with the same name already exists if pm2 list | grep -q $PROJECT_NAME; then pm2 reload $PROJECT_NAME || error "PM2 process restart failed" else pm2 start npm --name "$PROJECT_NAME" -- start || error "PM2 process failed to start" fi pm2 save pm2 startup # Prompt the user to execute the generated command to set up the startup} # ---------------------------------- # 6. Configure Nginx reverse proxy# ---------------------------------- configure_nginx() { success "\n[6/6] Configure Nginx reverse proxy..." sudo bash -c "cat > $NGINX_AVAILABLE << EOF server { listen 80; server_name _; # Replace with the actual domain name or IP location / { proxy_pass http://localhost:$PROJECT_PORT; proxy_set_header Host \$host; proxy_set_header X-Real-IP \$remote_addr; proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto \$scheme; } # Static resource cache location /_next/static { alias $PROJECT_DIR/.next/static; expires 365d; access_log off; } } EOF" # Create an enable link sudo ln -sf $NGINX_AVAILABLE $NGINX_ENABLED sudo nginx -t || error "NginxConfiguration test failed" sudo systemctl restart nginx } # ---------------------------------- # Main execution process# ---------------------------------- install_dependencies configure_firewall clone_project build_project start_pm2 configure_nginx success "\n✅ Deployment is complete! Visit http://Server IP View site"warning "Tip: If HTTPS is required, please manually modify the Nginx configuration to add SSL certificate"
1. Modify the configuration
Open the script and modify the configuration area at the top:
- PROJECT_NAME: Project name (for PM2 and Nginx configurations
- PROJECT_PORT: Service port (default 3000)
- PROJECT_GIT_REPO : Your Git repository address (make sure the server has access rights)
- PROJECT_DIR: Project deployment directory (default /var/www/my-next-app)
2. Grant execution permissions
chmod +x
3. Run the script
./
4. Follow-up operations
· Create . File manually according to the prompts and fill in the production environment variables
cd /var/www/my-next-app nano . # Example content:NEXT_PUBLIC_API_URL=
- · Execute the command generated by pm2 startup (set the power-on startup)
- · Log monitoring: Use pm2 logs to view real-time logs:
pm2 logs my-next-app
This is the article about how to deploy React+ projects to the server. For more related React deployment content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!