Skip to content

feat: Add NGINX API gateway demo #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
*~
\#*

#######################
# Terraform variables #
#######################
*.tfvars

##########################
# Backup/temporary files #
##########################
Expand Down
5 changes: 0 additions & 5 deletions NginxOneConsole-demo/readme.md

This file was deleted.

26 changes: 19 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,28 @@
# nginx_demos
[![Project Status: Concept – Minimal or no implementation has been done yet, or the repository is only intended to be a limited example, demo, or proof-of-concept.](https://www.repostatus.org/badges/latest/concept.svg)](https://www.repostatus.org/#concept)
[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/nginx/nginx-demos/badge)](https://securityscorecards.dev/viewer/?uri=github.com/nginx/nginx-demos)
[![Community Support](https://badgen.net/badge/support/community/cyan?icon=awesome)](/SUPPORT.md)
[![Community Forum](https://img.shields.io/badge/community-forum-009639?logo=discourse&link=https%3A%2F%2Fcommunity.nginx.org)](https://community.nginx.org)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](/CODE_OF_CONDUCT.md)

## Requirements
# NGINX Demos

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam elit turpis, varius et arcu elementum, viverra rhoncus sem. Aliquam nec sodales magna, et egestas enim. Mauris lobortis ultrices euismod. Pellentesque in arcu lacus. Mauris cursus laoreet nulla, ac vehicula est. Vestibulum eu mauris quis lorem consectetur aliquam ac nec quam. Vestibulum commodo pharetra mi, at bibendum neque faucibus ut. Mauris et tortor sed sem consectetur eleifend ut non magna. Praesent feugiat placerat nibh, varius viverra orci bibendum sed. Vestibulum dapibus ex ut pulvinar facilisis. Quisque sodales enim et augue tempor mattis. Suspendisse finibus congue felis, ac blandit ligula. Praesent condimentum ultrices odio quis semper. Nunc ultrices, nibh quis mattis pellentesque, elit nulla bibendum felis, quis dapibus erat turpis ac urna.
This repository contains a collection of curated and updated NGINX demos covering NGINX offerings.

## Getting Started
## Repository Structure

Duis sit amet sapien vel velit ornare vulputate. Nulla rutrum euismod risus ac efficitur. Curabitur in sagittis elit, a semper leo. Suspendisse malesuada aliquam velit, eu suscipit lorem vehicula at. Proin turpis lacus, semper in placerat in, accumsan non ipsum. Cras euismod, elit eget pretium laoreet, tortor nulla finibus tortor, nec hendrerit elit turpis ut eros. Quisque congue nisi id mauris molestie, eu condimentum dolor rutrum. Nullam eleifend elit ac lobortis tristique. Pellentesque nec tellus non mauris aliquet commodo a eu elit. Ut at feugiat metus, at tristique mauris. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae;
The demos are divided by NGINX product offering into unique distinct folders. Each folder then contains one or more demos covering various use cases within the respective product offering.

## How to Use
Each demo might have unique deployment requirements. Please refer to each individual README for more details.

Maecenas at vehicula justo. Suspendisse posuere elementum elit vel posuere. Etiam quis pulvinar massa. Integer tempor semper risus, vitae maximus eros ullamcorper vitae. In egestas, ex vitae gravida sodales, ipsum dolor varius est, et cursus lorem dui a mi. Morbi faucibus ut nisi id faucibus. Sed quis ullamcorper ex. In et dolor id nunc interdum suscipit.
## Available Demos

|Title|Description|
|-----|-----------|
|NGINX API gateway|Configure NGINX as an API gateway|
|NGINX Gateway Fabric|Simple overview of configuring NGINX Gateway Fabric to route traffic within Kubernetes|
|NGINX Ingress Controller|Simple overview of deploying and configuring NGINX Ingress Controller|
|NGINX One|Simple overview of NGINX One and its capabilities|

## Contributing

Expand Down
3 changes: 3 additions & 0 deletions nginx-gateway-fabric/appworld/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# NGINX Gateway Fabric Demo

This demo contains the files used in the NGINX Gateway Fabric AppWorld demo.
File renamed without changes.
3 changes: 3 additions & 0 deletions nginx-one/appworld/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# NGINX One Console Demo

The material for this demo can be found within the NGINX One Workshop GitHub repository at <https://github.com/nginxinc/nginx-one-workshops>.
204 changes: 204 additions & 0 deletions nginx/api-gateway/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
# NGINX API Gateway Demo

## Overview

This demo uses Terraform to automate the setup of an NGINX API gateway pseudo-production environment that includes a mock API backend database.

## Requirements

### Terraform

This demo has been developed and tested with Terraform `0.13` through `1.1.5`.

Instructions on how to install Terraform can be found in the [Terraform website](https://www.terraform.io/downloads.html).

### AWS R53

You will need to create R53 hosted zone beforehand. Make sure you own the domain you are using through the R53 hosted zone or you risk running into DNS issues. You should specify the R53 hosted zone `id` as well as a FQDN for the NGINX Plus API gateway and backend API in the corresponding Terraform variables.

## Deployment

To use the provided Terraform scripts, you need to:

1. Export your AWS credentials as environment variables (or alternatively, tweak the AWS provider in [`terraform/provider.tf`](terraform/provider.tf)).
2. Set up default values for variables missing a value in [`terraform/variables.tf`](terraform/variables.tf) (you can find example values commented out in the file). Alternatively, you can input those variables at runtime (beware of dictionary values if you do the latter).

Once you have configured your Terraform environment, you can either:

* Run [`./setup.sh`](setup.sh) to initialize the AWS Terraform provider and start a Terraform deployment on AWS.
* Run `terraform init` and `terraform apply`.

And finally, once you are done playing with the demo, you can destroy the AWS infrastructure by either:

* Run [`./cleanup.sh`](cleanup.sh) to destroy your Terraform deployment.
* Run `terraform destroy`.

## Demo Overview

You will find a series of NGINX configuration files in the [`nginx_api_gateway_config`](nginx_api_gateway_config/) folder. The folder is divided into individual steps, meant to be copied into their respective directory in order. By default, the folder is uploaded to your NGINX API gateway instance.

Do note that you will have to replace the `<backend-api-fqdn>` placeholder value found in the API backends NGINX configuration file in Step 3 with the corresponding value you used when deploying the Terraform environment (see [`nginx_api_gateway_config/step_3/api_backends.conf`](nginx_api_gateway_config/step_3/api_backends.conf) for more details).

A deployment script to help you copy the configuration files, [`deploy.sh`](nginx_api_gateway_config/deploy.sh), is also provided. To run the script, use the step number as a parameter, e.g. `./deploy.sh 1` for step 1. You might need to make the deployment script executable by running `sudo chmod +x deploy.sh`.

### Step 1 -> Define the entry point of the NGINX API gateway

To deploy:

`./deploy.sh 1`

To test:

`curl -s http://localhost:8080`

Expected response:

```html
<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.19.5</center>
</body>
</html>
```

### Step 2 -> Define default JSON error codes

To deploy:

`./deploy.sh 2`

To test:

`curl -s http://localhost:8080 | jq`

Expected response:

```json
{"status":400,"message":"Bad request"}
```

To test (headers):

`curl -sI http://localhost:8080`

Expected response:

```text
HTTP/1.1 400 Bad Request
...
```

### Step 3 -> Define the API endpoints and upstream/backend servers

To deploy:

`./deploy.sh 3`

To test:

`curl -s http://localhost:8080/api/f1/drivers/alonso | jq`

Expected response:

```json
{
"MRData": {
"xmlns": "http://ergast.com/mrd/1.5",
"series": "f1",
"url": "http://ergast.com/api/f1/drivers/alonso",
"limit": "30",
"offset": "0",
"total": "1",
"DriverTable": {
"driverId": "alonso",
"Drivers": [
{
"driverId": "alonso",
"permanentNumber": "14",
"code": "ALO",
"url": "http://en.wikipedia.org/wiki/Fernando_Alonso",
"givenName": "Fernando",
"familyName": "Alonso",
"dateOfBirth": "1981-07-29",
"nationality": "Spanish"
}
]
}
}
}
```

### Step 4 -> Enable rate limiting

To deploy:

`./deploy.sh 4`

To test (run multiple times in quick succession):

`curl -s http://localhost:8080/api/f1/drivers/alonso | jq`

Expected response:

```json
{"status":429,"message":"API rate limit exceeded"}
```

### Step 5 -> Set up API Key authentication

To deploy:

`./deploy.sh 5`

To test (unauthorized requests):

`curl -s http://localhost:8080/api/f1/drivers/alonso | jq`

Expected response (unauthorized requests):

```json
{"status":401,"message":"Unauthorized"}
```

To test (authorized requests):

`curl -sH "apikey: 7B5zIqmRGXmrJTFmKa99vcit" http://localhost:8080/api/f1/drivers/alonso | jq`

Expected response (authorized requests):

```json
{"MRData": {
"xmlns": "http://ergast.com/mrd/1.4",
"series": "f1",
"url": "http://ergast.com/api/f1/drivers/alonso",
...
}}
```

### Step 6 -> Set up JSON body validation using NJS

To deploy:

`./deploy.sh 6`

To test (incorrect JSON):

`curl -sH "apikey: 7B5zIqmRGXmrJTFmKa99vcit" -i -X POST -d 'garbage123' http://localhost:8080/api/f1/seasons`

Expected response (incorrect JSON):

```text
HTTP/1.1 415 Unsupported Media Type
```

To test (correct JSON):

`curl -sH "apikey: 7B5zIqmRGXmrJTFmKa99vcit" -i -X POST -d '{"season":"2020"}' http://localhost:8080/api/f1/seasons | jq`

Expected response (correct JSON):

```text
HTTP/1.1 200 OK
```
4 changes: 4 additions & 0 deletions nginx/api-gateway/cleanup.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
cd terraform \
&& terraform destroy -auto-approve \
&& rm -f terraform.tfstate terraform.tfstate.backup \
&& rm -rf .terraform
19 changes: 19 additions & 0 deletions nginx/api-gateway/nginx_api_gateway_config/deploy.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/bin/bash

if [ -z $1 ]; then
echo "You need to pass a step number"
exit 1;
fi

if (($1 < 1 || $1 > 8)); then
echo "Only steps 1 through 8 exist"
exit 1;
fi

sudo cp -r step_$1/* /etc/nginx
sudo nginx -s reload

if [ $? = 0 ]; then
echo "NGINX successfully reloaded"
fi

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
server {
listen 8080;

include conf.d/my_apis/*.conf;

location / {
return 400;
}

default_type application/json;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
error_page 400 = @400;
location @400 {
return 400 '{"status":400,"message":"Bad request"}\n';
}
error_page 401 = @401;
location @401 {
return 401 '{"status":401,"message":"Unauthorized"}\n';
}
error_page 403 = @403;
location @403 {
return 403 '{"status":403,"message":"Forbidden"}\n';
}
error_page 405 = @405;
location @405 {
return 405 '{"status":405,"message":"Method not allowed"}\n';
}
error_page 429 = @429;
location @429 {
return 429 '{"status":429,"message":"API rate limit exceeded"}\n';
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
upstream f1-admin {
server <backend-api-fqdn>;
}

upstream f1-data {
server <backend-api-fqdn>:8000;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
location /api/f1/ {
location = /api/f1/seasons {
proxy_pass http://f1-admin;
}

location ~ /api/f1/[12][0-9]+ {
proxy_pass http://f1-data;
}

location /api/f1/drivers {
proxy_pass http://f1-data;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
limit_req_zone $remote_addr zone=perip:1m rate=1r/s;

server {
listen 8080;

include conf.d/my_apis/*.conf;

location / {
return 400;
}

default_type application/json;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
location /api/f1/ {
limit_req zone=perip nodelay;
limit_req_status 429;

location = /api/f1/seasons {
proxy_pass http://f1-admin;
}

location ~ /api/f1/[12][0-9]+ {
proxy_pass http://f1-data;
}

location /api/f1/drivers {
proxy_pass http://f1-data;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
map $http_apikey $api_client_name {
"7B5zIqmRGXmrJTFmKa99vcit" "client_one";
"QzVV6y1EmQFbbxOfRCwyJs35" "client_two";
default "";
}
Loading