Dinosaur-Guy
Dinosaur-Guy

Reputation: 135

Using Nginx reverse proxy with Docker

I am trying to develop a distributed Angular app deployed on Nginx that should connect to a backend service.

docker-compose.yml:

version: '3'
services: 
  backend_service_1:
    build:
      context: ./app
      dockerfile: Dockerfile
    ports:
      - "3001:5000"
    networks: 
      - my-network

  frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile.3      
    ports:
      - "3000:80"
    networks: 
      - my-network
    links:
      - backend_service_1

networks: 
  my-network:

nginx.conf:

upstream backend {
  server backend_service_1:3001;
}

server {
  listen 80;
  server_name localhost;

  location / {
    root /usr/share/nginx/html/ki-poc;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
  }

  location /backend {
    proxy_pass http://backend/;
    proxy_redirect     off;
    proxy_set_header   Host $host;
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Host $server_name;
  }
}

I can access the app on localhost:3000. I can also get a response from the backend service on localhost:3001 using the browser. However, when I try to get a response from the backend service using the proxy on localhost:3000/backend I receive the following error message: [error] 5#5: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 172.20.0.1, server: localhost, request: "GET /backend HTTP/1.1", upstream: "http://172.20.0.2:3001/", host: "localhost:3000"

Can you tell my, why the request to the linked backend container is getting refused?

Upvotes: 0

Views: 1457

Answers (2)

OriZin
OriZin

Reputation: 11

localhost:3000, localhost:3001 both are direct connecting to each app. but <> is proxy_pass, so if you want to use this, you should run "localhost:80/backend" and you want to enter the backend via frontend,

 location / {
     proxy_pass http://localhost:3000/;
 }

so, -> http:youraddress/ => 80 port, '/' =>localhost:3000/ => frontend ///////// http:youraddress/backend => 80 port, '/backend' => localhost:3000/backend

If you show me your DOCKERFILE, get better answer

or server_name ... localhost; => _;

Upvotes: 0

Quentin Revel
Quentin Revel

Reputation: 1478

You shoul use the port of the container in the nignx config, not the one of the host.

upstream backend {
    server backend_service_1:5000;
}

Upvotes: 1

Related Questions