To allow NGINX to route requests for a given service, we must define a server block directive within the http context:
http {
server {
...
}
}
Within the server block, we can define certain directives that are only available in the server context. Here is a short list of the most common ones:
- listen: Which port should this service be listening to. If this is not set, it'll default to port 80.
- server_name: Which domain name(s) should apply to this server block.
- location: How it should process requests based on the URL path. The location directive usually has two parameters. The first parameter is the prefix, and the second is another block of directives that specify how that request should be handled. That inner block can have the following directives:
- root: Used for serving static files. It tells NGINX where it can find the requested resources on our server.
- proxy_pass: Used for reverse proxying. It tells NGINX the URL to which it should relay the request.
When NGINX receives a request that matches the server block's listen and server_name directives, it will pass it to the server block. Then, the path of the URL of the request would be extracted and it will try to match with the prefixes of each location directive. If it finds a match, the request will be processed in accordance with the directives specified within that location block. If there is more than one location prefix that matches the URL, the location block with the longest (and thus most specific) prefix will be used.
Open up /etc/nginx/nginx.conf and add the following server block to reverse proxy requests to our API server:
...
http {
....
server {
listen 80 default_server;
location / {
proxy_pass http://localhost:8080;
}
}
}
When NGINX receives a request at http://142.93.241.63/, the URL path (/) matches the prefix of the first location block. The proxy_pass directive then directs the request to our API, which would be running on port 8080. NGINX will also relay the API's response back to the client.
So, let's revert our change to the SERVER_PORT environment variable by editing the envs/.env file:
SERVER_PORT=8080
Then, start both our API server and the NGINX service, test our API on http://142.93.241.63/, and check that everything is still working:
hobnob@hobnob:$ npx pm2 delete 0; yarn run serve
hobnob@hobnob:$ sudo systemctl reload nginx.service