'nginx reverse-proxy bad gateway, no idea what im doing wrong
First time using nginx reverse-proxy with docker and i need your help, i have a service written in golang and I'm trying to implement nginx but im getting error and have no idea what is happening.
this is my yml file:
version: "3.6"
services:
reverse-proxy:
image: nginx:1.17.10
container_name: reverse_proxy
volumes:
- ./reverse_proxy/nginx.conf:/etc/nginx/nginx.conf
ports:
- 80:80
this is my nginx.conf file:
events {
worker_connections 1024;
}
http {
server {
listen 80 default_server;
server_name localhost 127.0.0.1;
location /api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://127.0.0.1:8081;
}
}
}
after running my service and docker-compose up when i hit curl localhost/api im getting bad gateway 502, although if i run curl localhost:8081, my service is running without any issue.Any help is appreciated because im really stuck here.Thanks in advance.
Solution 1:[1]
This is more a Docker problem than a nginx or go, when you are running containers inside the Docker engine, each one will run isolated from each other, so your nginx service doesn't know your backend service.
So, to fix this, you should use Docker networks. A network will enable your services to communicate between them. To do that, you should first edit your docker-compose.yml file
# docker-compose.yml
version: "3.8"
services:
my_server_service:
image: your_docker_image
restart: "always"
networks:
- "api-network"
reverse-proxy:
image: nginx:1.17.10
container_name: reverse_proxy
volumes:
- ./reverse_proxy/nginx.conf:/etc/nginx/nginx.conf
ports:
- 80:80
networks:
- "api-network"
networks:
api-network:
After that, you need to change the proxy-pass of your nginx.conf file to use the same name as your backend service, so change the string "127.0.0.1" to "my_server_service".
# nginx.conf
user nginx;
events {
worker_connections 1024;
}
http {
server {
listen 80 default_server;
server_name localhost 127.0.0.1;
location /api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://my_server_service:8081;
}
}
Also, as you are using nginx as reverse proxy, you even don't need to bind your backend service port with your host machine, the docker network can solves it internally between the services
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jictyvoo |
