Recreate ECS load balancing locally with Nginx

In Summary

In this article, I’ll explain how you can use a simple trick to replicate locally an architecture with multiple containers running on a single ECS task and an application load balancer performing content-based routing.

“Routing” — Photo by Javier Allegue Barros on Unsplash

Our example

In our example, we run a blog platform similar to Medium (in React) and our backend architecture is based in microservices. So the API, composed of 3 main components, is accessible via a unique domain (https://api-example). Requests are routed to the correct service following some simple path rules.

The following diagram summarises it:

Our blog architecture

Set up your local to replicate the ECS architecture

When working locally, we might need to replicate this architecture so our React app can define a single API URL (https://localhost:80) to make use of our services and here it’s where Docker Compose can help us.

In our case, the load balancing duties will be carried out by a very basic Nginx server. So the docker-compose file would look like this:

version: '2.0'
services:
users:
build: ./users
ports:
- 8100:8100
depends_on:
- mongo
links:
- mongo
articles:
build: ./articles
ports:
- 8200:8200
depends_on:
- subscriptions
- mongo
links:
- subscriptions
- mongo
subscriptions:
build: ./subscriptions
ports:
- 8000:8000
depends_on:
- users
- articles
- mongo
links:
- users
- articles
- mongo
mongo:
image: mongo:4.0.18
ports:
- 27017:27017
ngnix-server:
image: nginx:1.13
ports:
- "80:80"
volumes:
- './nginx.conf:/etc/nginx/nginx.conf'
links:
- users
- articles
- subscriptions
depends_on:
- users
- articles
- subscriptions

Thus, the Nginx configuration file nginx.conf will contain the path rules responsible for routing requests to the containers found in our local server by following the required path rules.

events { worker_connections 1024;}

http {
server {
listen 80;
location /users {
proxy_pass http://users:8100;
}

location /articles {
proxy_pass http://articles:8200;
}

location /subscriptions {
proxy_pass http://subscriptions:8000;
}
}
}

In summary

A simple docker-compose + Nginx configuration will allow us to replicate in our local machine the behaviour of the ALB in our cloud ECS architecture.

This so

Senior Full Stack Engineer at @gravitywelluk