harbor run -t LiteCoder/nginx-docker-load-balancer__sample_0085_a281c734harbor download LiteCoder/nginx-docker-load-balancer__sample_0085_a281c734Set up a multi-container web application using Docker Compose where Nginx acts as a load balancer distributing traffic across multiple backend Node.js application instances.
http and os modules)/app//app/
├── app/
│ ├── server.js
│ └── Dockerfile
├── nginx/
│ └── nginx.conf
└── docker-compose.yml
/app/app/server.js)3000hostname: the container's hostname (from os.hostname())timestamp: current ISO 8601 timestamp (from new Date().toISOString())message: the string "Hello from backend"Content-Type: application/json header200Example response:
{
"hostname": "abc123def",
"timestamp": "2025-01-15T10:30:00.000Z",
"message": "Hello from backend"
}
/app/app/Dockerfile)node:18-alpine as the base image/usr/src/appserver.js into the container3000node server.js/app/docker-compose.yml)app and nginxapp service:
./app directory3000 (internal only, not published to host)nginx service:
nginx:alpine image./nginx/nginx.conf to /etc/nginx/nginx.conf as a read-only bind mount8080 to container port 80app service/app/nginx/nginx.conf)upstream block named backend that references the app service on port 3000 using Docker Compose DNS resolutionround-robin load balancing (Nginx default)server block listening on port 80location / block must proxy requests to the backend upstreamproxy_set_header Host $host and proxy_set_header X-Real-IP $remote_addr headers in the proxy configurationAfter running docker compose up -d --build from /app/:
http://localhost:8080/ must return valid JSON with the three required fields (hostname, timestamp, message)http://localhost:8080/ should show different hostname values, demonstrating load balancing across replicas