NGINX is an open-source web server used for reverse proxying, load balancing, and caching. In addition to serving HTTP and HTTPS, it can also function as a proxy server for IMAP, POP3, and SMTP for email services. According to the official website, one of NGINX’s primary goals was to create the fastest web server.
For more in-depth information about NGINX, I recommend reading the official documentation available at https://nginx.org/en/docs/.
In my opinion, the easiest way to install NGINX is by using Docker and Docker Compose. To install Docker, please follow the instructions on the official website at https://docs.docker.com/engine/install.
In addition to Docker, we also require Golang, which you can install by referring to the official documentation at https://go.dev/doc/install. Furthermore, you’ll need a text editor for coding, such as Visual Studio Code.
Open your preferred Golang IDE (I recommend Visual Studio Code), navigate to the desired project folder, and create a main.go file. To initiate the go.mod file, run the following command: go mod init example.com/my-test-project.
Before anything else, let’s create a dummy endpoint to ensure that our API is functioning properly and can provide us with the necessary information.
To host our API, we can use any Golang web framework, such as Gin, Beego, Fiber, Echo, Fasthttp, or others. However, I’ve chosen to use the built-in package net/http.
Try to run it by entering go run main.go in your terminal, and enter at http://localhost:8082/hello. You should see the text Hello world as shown in the screenshot below.
Configure Docker & Docker Compose
We need to create several files to set up NGINX on our machine.
The final step involves generating certificates, which can be achieved using OpenSSL. As we configure NGINX in the ssl.conf file, we require the following files:
We intend to store all certificates in the ‘certs’ directory. To achieve this, create a certs folder using the command mkdir certs and navigate to it by using cd certs in the terminal. Now you can begin generating your certificates.
In my case, since I’m using the Fedora 38 operating system, to establish trust for the certificate, I copy it to the /etc/pki/ca-trust/source/anchors directory. If you are using Windows, you can import this certificate using the Microsoft Management Console (MMC).
Our proxy is ready to run. Type docker-compose -f docker-compose.local.yml up or docker compose -f docker-compose.local.yml up and you should see something like below.
You can use Docker and NGINX to host APIs developed in various technologies, such as Golang, ASP.NET Core, or others. In our configuration, NGINX acts as a reverse proxy. When a user interacts with our reverse proxy, NGINX determines the routing of the request. In our specific case, it forwards the request to the Golang application running on localhost:8082. This means that the user is unaware that another server is handling their request.