2

I'm new to Docker and nginx so this may be a simple question but I've been searching through question/answers for a while and haven't found the correct solution.

I'm trying to run an nginx server through docker to reroute all requests to my.example.com/api/... to localhost:3000/api/...

I have the following Dockerfile:

FROM nginx
COPY ./nginx.conf /etc/nginx/conf.d/default.conf

and the nginx.conf file:

server {
    server_name my.example.com;
    location / {
        proxy_pass http://localhost:3000/;
    }
}

When I make the calls to the api on localhost:3000 this works fine but when I try to run against my.example.com I get a network error that the host isn't found. To be clear the domain I want to 'redirect' traffic from to localhost host is a valid server address, but I want to mock the api for it for development.

Efie
  • 1,430
  • 2
  • 14
  • 34
  • "localhost" or "127.0.0.1" are your loopback interface, which means (in simple words/terms) that your request allways lands on the host where they came from. In your case docker/nginx. To pass the request that nginx makes to your host system, use `http://host.docker.internal:3000` instead of `http://localhost:3000` – Marc May 18 '22 at 10:33

1 Answers1

3

This isn't working because your nginx proxying request to localhost which is container itself but your app is running on host's port 3000 -- outside of container. check this article

change
proxy_pass http://localhost:3000/;
  to
proxy_pass http://host.docker.internal.

add 127.0.0.1 example.com my.example.com in etc/hosts

Sushil Kumar
  • 131
  • 2
  • 2
  • Thanks. Both docker and nginx are new to me and that makes sense. I'm still getting an error when trying to hit `http://example.com/api/...` that 127.0.0.1:80 is refusing the connection. Should this hypothetically work for any outside domain? For example should I be able to capture and redirect traffic going to google.com using this method as well? – Efie May 18 '22 at 13:32