From 2b1adef3bfaee103f67d5f4bf3df21bc57a098b3 Mon Sep 17 00:00:00 2001
From: strokh24 <Rokas.Stankunas@Student.Reutlingen-University.DE>
Date: Tue, 26 Nov 2024 12:19:43 +0100
Subject: [PATCH] feat: implement nginx load balancer

---
 docker-compose.yml | 15 +++++++++++++--
 nginx.conf         | 38 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 51 insertions(+), 2 deletions(-)
 create mode 100644 nginx.conf

diff --git a/docker-compose.yml b/docker-compose.yml
index a99e7f9..fc10e49 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,4 +1,3 @@
-version: '3.9'
 services:
   mongodb:
     image: mongo:latest
@@ -33,4 +32,16 @@ services:
     depends_on:
       - mongodb
     environment:
-      - MONGO_URI=${MONGO_URI}
\ No newline at end of file
+      - MONGO_URI=${MONGO_URI}
+
+  nginx:
+    image: nginx:latest
+    container_name: nginx
+    ports:
+      - "80:80"
+    depends_on:
+      - todo-app-1
+      - todo-app-2
+    volumes:
+      - "./nginx.conf:/etc/nginx/nginx.conf:ro"
+      - "/var/log/nginx/access.log:/var/log/nginx/access.log"
diff --git a/nginx.conf b/nginx.conf
new file mode 100644
index 0000000..737504a
--- /dev/null
+++ b/nginx.conf
@@ -0,0 +1,38 @@
+events {
+    # Set the maximum number of simultaneous connections that can be opened by a worker process
+    worker_connections 1024;
+}
+
+http {
+    # Define an upstream group for load balancing the todo-app services
+    upstream todo-app {
+        ip_hash;
+        server todo-app-1:3000;  # First server in the upstream group
+        server todo-app-2:3000;  # Second server in the upstream group
+    }
+
+    # Define a custom log format for capturing upstream request details
+    log_format upstreamlog '[$time_local] $remote_addr - $remote_user - $request '
+                           '"$status" $body_bytes_sent '
+                           '"$http_referer" "$http_user_agent" '
+                           '"$gzip_ratio" '
+                           '${host} $request_uri '
+                           '$upstream_addr ';
+
+    server {
+        listen 80;  # Listen on port 80 for incoming HTTP requests
+        location / {
+            # Proxy requests to the upstream todo-app group
+            proxy_pass http://todo-app;
+            proxy_http_version 1.1;  # Use HTTP/1.1 for proxying
+            proxy_set_header Upgrade $http_upgrade;  # Set the Upgrade header
+            proxy_set_header Connection 'upgrade';  # Set the Connection header to upgrade
+            proxy_set_header Host $host;  # Forward the original Host header
+            proxy_cache_bypass $http_upgrade;  # Bypass cache for upgraded requests
+            # Log access requests using the defined upstream log format
+            access_log /var/log/nginx/access.log upstreamlog;
+        }
+    }
+}
+
+
-- 
GitLab