February 28, 2023
How to run a NextJS website on NGINX
This artcle explains how to configure your Nginx server to run a dynymic NextHS application.
Setup bare repo
First you need to get the sourcecode of your NextJS application on the server. This can be accomplished in many ways. For this article I assume you want to have a bare repo, so you can push your code from your local environment to a remote from where the code gets pulled into a directory. To do that, setup a direcory called ‘${project-name}.git’:
|
|
In this directory, create a bare repo with the following command:
|
|
Now you’ll find some files and folders in your bare repo. Go to the hook directory and create a file named ‘post-receive’ and add the following code:
|
|
On line one, we define that this is a bash script. On the next three, we define where our code from the git repo will live. On the fouth line, we define where our bare repo is located. On the last line, we checkout every time a new push to this bare repo is made to the development branch.
You can test everything works by adding a remote in your local environment like so:
|
|
This will create a new remote named nginx. Now push the code to this remote and you should be able to find the sourcecode in the directory ‘/usr/share/nginx/html/${project-name}’
Setup Nginx config file
In the config file you can configure where the server should point at. Configure your configureation file in ‘/etc/nginx/sites-available/default’ as follows:
|
|
This will tell the server which domain is used, and in the location block it will tell the server to listen to port 3000. The last part is only for the SSL encryption and can be ignored.
After you made this change, make sure to restart the Nginx server with the following command:
|
|
Start your server
Now go to your directory where your NextJS application lives in - in our case to ‘/usr/share/nginx/html/${project-name}’ then you need to build and then run your application. To this with the two following commands:
|
|
Now you should be able to go visit your domain and find your running application.