How to Build and Deploy a Next.js App on Apache Server

sekihin發表於2024-12-08

Step 1: Installing Next.js

npm install -g yarn
mkdir -pv /var/www/project_folder_name
cd /var/www/project_folder_name
yarn create next-app

Edit package.json and replace the script section with the following:

"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
},

Step 2: Preparing Your Next.js Application for Production

Navigate to your project's root directory and run the following command

cd /var/www/project_folder_name
yarn install
yarn run build

Step 3: Configuring Apache

Edit the Apache configuration file, usually located at /etc/httpd/conf/httpd.conf. Add the following lines at the end of the file.

<VirtualHost *:80>
ServerName your-domain.com
ServerAdmin contact@example.com
ProxyPreserveHost On
ProxyRequests Off
ProxyPass / http://localhost:3000/
ProxyPassReverse / http://localhost:3000/
<Directory "/var/www/project_folder_name">
AllowOverride All
</Directory>
</VirtualHost>

Enable the necessary Apache mod_proxy and mod_proxy_http modules

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

httpd -M

Restart Apache to apply the changes.

sudo service httpd restart

Step 4: Deploying Your Next.js Application And Keeping Your Application Running

Use yarn to start your Next.js application in production mode.

cd /var/www/project_folder_name
yarn start

相關文章