When several containerized applications need to share ports 80 and 443, NGINX can be their single public entry point. It receives HTTP requests, selects an application container, and returns its response. The application containers need no published ports. NGINX can also serve content itself. section 20.0 section 20.1
To put an application behind NGINX:
- Create a Docker network and start NGINX with a bind-mounted site-configuration folder. Its default page lets you check that the server is running before adding a proxy. section 20.1
- Start the application on the same network without publishing its port. Map a local domain to your machine in the hosts file, then add an NGINX site configuration for that domain. section 20.1
- Reload NGINX and request the domain with curl. Start the application before reloading: if a configured upstream is unavailable when NGINX reads the configuration, NGINX exits. section 20.1 section 20.2
Listing 20.1 Nginx proxy configuration for the who-am-I website
server {
server_name whoami.local; # the domain hostname
location / {
proxy_pass http:/./whoami:8080; # source address for content
proxy_set_header Host $host; # copy the host header
add_header X-Host $hostname; # add proxy name in response
}
}
A site configuration matches the request’s hostname, proxies its path to an application container, forwards the Host header, and adds a response header identifying the proxy. section 20.1
Routing can use either a hostname or a request path, letting one domain expose a web application and an API. With multiple upstream containers, NGINX can load balance requests without changes to application code. An HTTP site can also redirect to HTTPS, with NGINX serving the certificate. section 20.2
Check whether caching helps
Configure NGINX to cache the image gallery’s web and API responses, then make the same request twice. An X-Cache: MISS first shows that NGINX fetched the response upstream; a subsequent HIT shows it served the cached copy. The API example keeps successful responses for one minute, while the web configuration uses a longer cache and can serve stale content during specified upstream failures. Cache only content suitable for sharing between users. section 20.3


