node.js - Nginx can't find upstream node app when running via Docker-compose
one text
Solution:
The problem is that in your Nginx configuration you are referencing the IP of the Web service as 127.0.0.1 which is the loopback address of the Host machine running the docker container. This may work depending on your setup (OS, firewall) or may not.
The correct way would be to make the nginx
service depends on the web
service in your docker-compose.yml file and update the Nginx config to reference the Web service by name (web
) instead of by IP address. Here you can find more info related to docker compose depends on capability.
The updated docker-compose.yml file would be:
version: '3.0'
services:
web:
build: .
nginx:
build:
context: .
dockerfile: Dockerfile.nginx
ports:
- 8080:8080
depends_on:
- web
Notice that I have stop exposing the port of the web
service. May be you need to keep it to monitor the Web service but is not required for the nginx
service.
With this update to the docker-compose.yml file the Nginx config will be as follows:
events {
worker_connections 1024;
}
http {
upstream node_app {
server web:3000;
}
server_tokens off;
# Define the MIME types for files.
include mime.types;
default_type application/octet-stream;
# Speed up file transfers by using sendfile()
# TODO: Read up on this
sendfile on;
server {
listen 8080;
server_name localhost;
location / {
proxy_pass http://node_app;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
}
}
Source