How to Use Nginx as a Reverse Proxy for a Server

How to Use Nginx as a Reverse Proxy for a Server

Daily short news for you
  • Deep Research - a web browsing tool for research that produces a summary in just a few minutes - compared to many hours of work for humans, according to their announcement.

    This feature is currently only available for Pro users. Although it has not been tested yet, many articles emphasize the impressive capabilities of this new tool. If you're still unsure what Deep Research can do, just imagine this: Tell it "I need research information on global coffee consumption from last year." That's it! Just sit back and wait a moment for it to search and compile the results, sending you a detailed report. Wow, that's pretty amazing!

    Immediately, huggingface published an article attempting to recreate this tool in their own way. Details at Open-source DeepResearch – Freeing our search agents. And it's no surprise that both have the flavor of AI Agents.

    » Read more
  • Living long enough in the Internet world, you can see that people here are quite eager to follow trends, and they spread rapidly at a dizzying pace.

    Just a few months ago, we were still astonished by the intelligence of large language models (LLMs) that could answer just like humans, and shortly after, they were updated with incredible thinking and reasoning capabilities. They are widely applied not only in programming fields. Recently, the term AI Agents has been creating a stir.

    So, what are AI Agents? In this short article, it is, of course, impossible to provide a brief yet comprehensive definition. Readers can refer to this very detailed article here Agents | Chip Huyen. To make it easier to visualize, AI Agents can be thought of as a person or some entity. The Agents themselves are equipped with all the necessary tools. From these, Agents can combine them to complete a task that we assign.

    Still a bit vague, right? A practical example is when you command the Agents to access Facebook every 8 PM, check for any prominent news from friends, and then send a summary to Telegram. That's it!"

    » Read more
  • I just discovered the idb-keyval library that helps implement a key-value database simply. As shared in the series of posts about the process of making OpenNotas, I was struggling to find a type of database for storage, and it seemed quite difficult; in the end, I settled on localForage.

    idb-keyval is quite similar to localForage, but it seems to be doing a little better. For example, it has an update function to update data, simply imagine it like this:

    update('counter', (val) => (val || 0) + 1);

    Unlike the set function, which completely replaces the data.

    » Read more

What is Nginx?

Nginx là gì

There's no need to say much, I'm sure many of you already know. Nginx is an HTTP server and reverse proxy server. It can also be used as a TCP/UDP server.

Nginx is commonly used for HTTP servers, and it is often used as a reverse proxy. This means that it is a server capable of directing and hiding other services inside the server.

To make it easier to understand, let's take a look at the illustration of the reverse proxy position in a web server system. We can see that all user queries (requests) go through the reverse proxy before being routed to the servers or services inside the server. This also means that users only know and interact with the proxy server without knowing the internal components.

What does a Reverse Proxy do?

Let's imagine a server with 2 services: Frontend (FE) and Backend (BE). The FE is set to run on port 8081, and the BE runs on port 8080. The FE communicates with the BE through a REST API.

Assuming the server's IP address is x.x.x.x, I can access the FE by accessing the address x.x.x.x:8081, and the BE by accessing x.x.x.x:8080. Now, with the domain name 2coffee.dev pointing to the IP, I can access them more easily as 2coffee.dev:8081 and 2coffee.dev:8080.

As you can see, my 2 services are accessed via the domain name (or IP address) along with the port. This means that users know which port my services are running on, which can be exploited for information gathering.

Furthermore, for easy management and professional appearance, I want the FE to be accessed directly from the address 2coffee.dev, while the API is accessed through the subdomain api.2coffee.dev. So, how can this be done? The simple answer is using Nginx as a reverse proxy.

How to Set Up a Reverse Proxy Server with Nginx?

The goal is to see the FE page when accessing 2coffee.dev and to be able to call the API when accessing api.2coffee.dev.

In this section, we will explore the basic reverse proxy configurations. First, make sure that both services on your server can be accessed locally through the addresses localhost:8081 and localhost:8080.

You can use the curl command to check that:

$ curl localhost:8081
# <response>
$ curl localhost:8080
# <response>

If you receive a response, everything is fine. If you receive any error messages indicating that the connection cannot be established, you need to check if the services are started correctly.

Nginx is installed on the server, you can either install Nginx directly on the server or use Docker to install it. If you use Docker, make sure you know how to set up the Docker network to allow it to access the above 2 services. One more note is that you need to map the container's ports 80 and 443 to the server's ports 80 and 443, or you can simply run the container in host network mode.

Open the file /etc/nginx/nginx.conf and check if it includes the following line:

...  
  ...  
  include /etc/nginx/conf.d/*.conf;
...  

This is the configuration for Nginx to automatically load the config files in the /etc/nginx/conf.d directory.

Create a file named my-app.conf in the /etc/nginx/conf.d directory. Here, I'll be using the vi editor.

$ vi /etc/nginx/conf.d/my-app.conf

The contents of the file will look like this:

server {
    listen 80;
    server_name 2coffee.dev;

    location / {
      proxy_pass http://localhost:8081;
      proxy_set_header X-Real-Ip $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $host;
      proxy_set_header REMOTE_ADDR $remote_addr;
      proxy_set_header X-Forwarded-Proto $scheme;
    }
}

server {
    listen 80;
    server_name api.2coffee.dev;

    location / {
      proxy_pass http://localhost:8080;
      proxy_set_header X-Real-Ip $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $host;
      proxy_set_header REMOTE_ADDR $remote_addr;
      proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Save and restart Nginx:

$ sudo nginx -s reload

For those using Docker, restart the Nginx container. One thing to note is that you need to mount the Nginx config files from the container to the outside to avoid losing the configuration when restarting the container.

To explain lines 7 to 11 in the my-app.conf file, you can understand them as follows: Since Nginx acts as a forwarder for user queries to the services, the headers need to be configured so that Nginx knows how to forward them to the services. Otherwise, the header information may be incorrect.

Conclusion

Nginx is a very popular server nowadays due to its powerful features.

Reverse proxy is a great feature provided by Nginx. It helps to direct and hide services inside the server, and using it also makes it easy to set up subdomains.

Premium
Hello

The secret stack of Blog

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (2)

Leave a comment...
Avatar
Trần Cường2 years ago
Mình làm theo mà đang bị lỗi không khởi động lại được nginx ko biết sai ở đâu ko :(
Reply
Avatar
Xuân Hoài Tống2 years ago
Lỗi như thế nào thế bạn
Avatar
Linh Trịnh Mạnh2 years ago
Cho mình hỏi cái reverse proxy này có phải giống như là park domain vào host không nhỉ?
Reply
Avatar
Xuân Hoài Tống2 years ago
Không giống đâu bạn, nó giúp cấu hình subdomain trỏ đến sẻvice trên máy chủ thôi
Scroll or click to go to the next page