I’m new to Nginx and I’m trying to define locations to match certain patterns.
I’m not sure if this is the correct approach, but this what I figured out so far.
Requirements
Location | Proxy Pass |
---|---|
/api/cars/carID?queryString | https://myapi/api/cars/carID?queryString |
/api/cars/carID/model?queryString | https://myapi/api/cars/carID/model?queryString |
/api/cars/carID/anythingElse?queryString | Shouldn’t be proxied |
/api/cars/carID/model/anythingElse?queryString | Shouldn’t be proxied |
Attempted
location ~*/api/cars/([A-Za-z0-9]+)/model$ {
proxy_pass https://myapi/api/cars/$1/model;
}
location ~*/api/cars/([A-Za-z0-9]+)$
proxy_pass https://myapi/api/cars/$1;
}
Update
Getting the following error message in the ngnix error logs
no resolver defined to resolve myapi
It is worth mentioning that I’m running nginx inside docker container.
I examined the resolv.conf
and it looks like the DNS requests are being forwarded to the host (Windows machine).
2
Answers
Your api server host
myapi
is not resolved from your nginx container.Your api server should either:
Run in a container named
myapi
and have the same network as your nginx container (if usingdocker-compose
all containers defined are part of the same network).Have a proper DNS which can be resolved on the internet or your private net
A couple of pointers to help you with your development, though my answer may not satisfy every one of your requirements:
RESOLVING DOCKER DNS HOST NAMES
During developoment you can use the Docker embedded DNS server to resolve URLs. So if you have a deployed API like this in Docker Compose:
Then specifying the Docker internal DNS server will ensure that DNS is resolved correctly for other Docker containers. Further info in this article.
RESOLVING HOST COMPUTER DNS HOST NAMES
Sometimes you may want to route through NGINX in Docker back to an API running on the host computer. On the host you might define a custom host name in the
hosts
file like this:You can then point NGINX running in Docker to the local API like this: