Configure NGINX as a Reverse Proxy with Docker Compose file

A reverse proxy server accepts a request from the client, forwards it to a backend server, and returns the response from server as if actual server is responding back to the client.
NGINX can be configured as any one of the following: Reverse Proxy Servers, Load Balancing, Web and Content Caching Server.
In this article, a docker compose file is created to run custom NGINX as a container with reverse proxy configuration which eases the creation of the proxy server in a jiffy.
Prerequisites
· Docker
· Docker Compose
1) Create an nginx.conf file and paste the following configuration. The proxy server redirects all the incoming requests through port 80 on which the server would be listening on. The proxy_pass identifier makes the service running on the port 8080 would then be communicated to and from the port 80 based on location context (path or pattern).
events { // events context is mandatory in latest versions
}
http {
server {
listen 80;
location / {
proxy_pass http://127.0.0.1:8080;
}
}
}
2) We can add many locations contexts to redirect to other services as follows
server {
listen 80;
location / {
proxy_pass http://127.0.0.1:8080;
}
location /api/ {
proxy_pass http://127.0.0.1:5000/;
}
. . .}
The second location context /api/ is triggered based on request URI and the request is directed towards the API service being served at port 5000 with contextual path /.
3) Create a compose file “docker-compose.yml” with latest version [use alpine or specific version if needed] of NGINX image and its configuration as shown below
version : “3”
services :
nginx:
image: nginx:latest
container_name: nginx_container
ports:
- 80:80
4) Add a volume to mount nginx.conf file to the container to replace the default file with the one created.
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
5) Run server with host network mode to provide access to other servers running in the host machine.
network_mode: host
The final docker-compose.yml file would look like:
version : “3”
services :
nginx:
image: nginx:latest
container_name: nginx_container
ports:
- 80:80
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf
network_mode: host
Finally, a proxy server can be created within 2 minutes with the basic configuration shown this article. Checkout what’s running on port 80 after running the command docker-compose up
Give a cheer if you like this post
Please comment or share your feedback
Happy coding…