Double Rewards

Rotating IPs:Buy 50GB, get 10GB free

Static IPs:Get 7 extra days for every 30 days purchased, plus 500MB per order

Buy Now >

Security AlertA fraudulent phishing site ( rola-ip.com) is impersonating our previous official website. ROLA IP's only official website is rola-ip.co (make sure it uses the .co domain suffix). To protect your funds, do not make payments on any other domain!

How to Configure an NGINX Docker Reverse Proxy with Rola IP Egress

Adrian Cole

Nov 26, 2026 · Guides · 14 min read

An NGINX Docker reverse proxy routes incoming HTTP requests to an application on a shared Docker network. To send the application’s outbound requests through Rola IP, configure its HTTP client separately with the issued proxy endpoint and authentication details. This guide covers both paths: client → NGINX → app, and app → Rola IP → destination.

This guide uses Docker Compose, an NGINX container, and a small Python 3.12 application reachable as app:3000. It is suitable for authorized API calls, public-page monitoring, regional QA, and other workflows where you have permission to access the target. The example application uses an HTTP proxy endpoint; a SOCKS5 endpoint requires an HTTP client with SOCKS5 support.

architecture

Quick answer: what should NGINX proxy to?

Use proxy_pass http://app:3000; for the Docker service that runs your application. Do not use proxy_pass http://your-rola-gateway:port; as a shortcut for arbitrary outbound proxying. That directive forwards a request to a named HTTP upstream; it does not turn the NGINX http module into a CONNECT-capable forward proxy, and it does not automatically translate SOCKS5.

For a Dockerized scraper or API worker, set its proxy through the client or framework it actually uses. With cURL, the proxy is selected with --proxy or -x; with an application, use the framework’s documented HTTP proxy or SOCKS5 setting. If the Rola endpoint is HTTP, an HTTPS destination can normally be reached through the HTTP proxy’s tunnel support. If the endpoint is SOCKS5 and the client supports proxy-side DNS, use the documented socks5h mode when DNS should resolve through the proxy.

Prerequisites and supported inputs

You need:

  • Docker Engine 28.0.0 or newer and Docker Compose v2 with --wait and --wait-timeout. Run the lab from the Docker host.
  • An NGINX official image tag selected for your deployment. This example uses nginx:1.27-alpine; pin a digest after your own image review.
  • The included Python 3.12 application, or an application with the same /health, /direct-check, and /proxy-check contract.
  • A Rola IP endpoint generated in your account: host, port, username, password, and the documented protocol.
  • An approved target URL for the first request and an IP-information endpoint for egress verification.

Record the deployment environment before changing configuration. Record the OS, Docker Engine, and Compose versions from the host running the lab:

uname -a
docker version
docker compose version

The example uses the python:3.12-alpine and nginx:1.27-alpine image tags. Tags can change. Record the resolved image digests and runtime versions for any run you need to reproduce.

Copy the issued connection details from your account. See the Rola IP proxy Quick Start.

Setting Used by the example
127.0.0.1:8080 NGINX entry point on the Docker host
app:3000 Python upstream on the Compose network
ROLA_PROXY_HOST, ROLA_PROXY_PORT Issued HTTP proxy gateway and port
ROLA_PROXY_USERNAME, ROLA_PROXY_PASSWORD Outbound proxy credentials
ROLA_PROXY_SCHEME=http HTTP proxy transport with CONNECT for HTTPS destinations
ROLA_CHECK_URL Fixed HTTPS endpoint that returns an IP in JSON

Keep provider connection fields separate from application code. A username parameter can control location or session behavior, but it does not replace permission to access a target.

Choose the correct protocol

The Python app supports HTTP proxy endpoints. The SOCKS5 rows describe cURL’s URL conventions for a separate client.

Rola endpoint Client setting Practical boundary
HTTP proxy http://host:port or the client’s HTTP proxy option Works for HTTP requests and HTTPS destinations when the client supports tunneling.
SOCKS5 proxy socks5://host:port cURL resolves the destination locally.
SOCKS5 with proxy-side DNS socks5h://host:port cURL passes the destination hostname to the SOCKS5 proxy.

NGINX’s standard proxy_pass directive supports http and https upstream URLs. It is therefore appropriate for the inbound app service in this tutorial, not as a replacement for a SOCKS5-aware egress client.

How to set up an NGINX reverse proxy in Docker

Step 1: Create the Compose project

Create the project directory and a private environment file. If you have the companion project, start in its root directory and copy .env.example to .env with private permissions before editing.

mkdir nginx-docker-reverse-proxy
cd nginx-docker-reverse-proxy
(umask 077 && touch .env)
mkdir -p app
printf '\n.env\n' >> .gitignore

Add only the values used by the included application to .env:

ROLA_PROXY_SCHEME=http
ROLA_PROXY_HOST=YOUR_ISSUED_HOST
ROLA_PROXY_PORT=YOUR_ISSUED_PORT
ROLA_PROXY_USERNAME=YOUR_GENERATED_USERNAME
ROLA_PROXY_PASSWORD=YOUR_PASSWORD
ROLA_CHECK_URL=https://api.ipify.org?format=json

Restrict the file and turn off shell tracing before working with it:

chmod 600 .env
set +x

Do not place a raw username and password into an unreviewed proxy URL. If your client requires a URL, percent-encode userinfo characters first. Passing host, port, username, and password as separate secret values is easier to validate, but environment variables are configuration inputs, not a secret store. Avoid typing real values into recorded commands, shell history, CI output, or logs.

Step 2: Define the Docker network and services

Create compose.yaml. The included app is built locally, listens on port 3000, and reads the proxy variables. The NGINX container is the only service published to the host in this pattern.

services:
  nginx:
    image: nginx:1.27-alpine
    ports:
      - "127.0.0.1:8080:80"
    volumes:
      - ./nginx:/etc/nginx/lab:ro
    command: ["nginx", "-c", "/etc/nginx/lab/nginx.conf", "-g", "daemon off;"]
    depends_on:
      app:
        condition: service_healthy
    networks:
      - app_net

  app:
    build:
      context: ./app
    expose:
      - "3000"
    env_file:
      - .env
    environment:
      NO_PROXY: ""
      no_proxy: ""
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request; urllib.request.build_opener(urllib.request.ProxyHandler({})).open('http://127.0.0.1:3000/health', timeout=2).close()"]
      interval: 5s
      timeout: 3s
      retries: 10
    networks:
      - app_net

networks:
  app_net:
    driver: bridge

Compose gives services on the same network DNS names based on service names. That is why NGINX should call app:3000 rather than a changing container IP. The host mapping binds NGINX to loopback. Keep the diagnostic routes private because they can expose IP information and trigger billable requests. Remove them before any public deployment. The Python app is a local lab service.

compose-network

Save this as app/Dockerfile:

FROM python:3.12-alpine
WORKDIR /app
COPY app.py ./
EXPOSE 3000
USER nobody
CMD ["python", "app.py"]

Save the Python standard-library app as app/app.py:

import json
import os
import time
from http.client import HTTPException
from ipaddress import ip_address
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlsplit
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener

from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer


CHECK_URL = os.environ.get("ROLA_CHECK_URL", "https://api.ipify.org?format=json")
PORT = int(os.environ.get("APP_PORT", "3000"))


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def result_for(url: str, use_proxy: bool) -> dict:
    target = urlsplit(url)
    if target.scheme != "https" or not target.hostname or target.username is not None:
        return {"ok": False, "error": "check_url_invalid", "via_proxy": use_proxy}
    started = time.monotonic()
    handler = ProxyHandler({"https": proxy_url()}) if use_proxy else ProxyHandler({})
    request = Request(url, headers={"Accept": "application/json", "User-Agent": "rola-nginx-docker-example/1.0"})
    try:
        with build_opener(handler, NoRedirect()).open(request, timeout=10) as response:
            body = response.read(4097)
            try:
                if len(body) > 4096:
                    raise ValueError("IP response exceeds limit")
                candidate = json.loads(body)["ip"]
                exit_ip = str(ip_address(candidate)) if isinstance(candidate, str) else None
            except (ValueError, KeyError, TypeError):
                exit_ip = None
            return {
                "ok": response.status == 200 and exit_ip is not None,
                "http_status": response.status,
                "elapsed_ms": round((time.monotonic() - started) * 1000, 1),
                "response_bytes": len(body),
                "exit_ip": exit_ip,
                "via_proxy": use_proxy,
            }
    except HTTPError as error:
        return {
            "ok": False,
            "http_status": error.code,
            "elapsed_ms": round((time.monotonic() - started) * 1000, 1),
            "response_bytes": 0,
            "error": "upstream_http_error",
            "via_proxy": use_proxy,
        }
    except (OSError, HTTPException) as error:
        reason = error.reason if isinstance(error, URLError) else error
        tunnel_407 = use_proxy and str(reason).startswith("Tunnel connection failed: 407 ")
        return {
            "ok": False,
            "http_status": 407 if tunnel_407 else None,
            "elapsed_ms": round((time.monotonic() - started) * 1000, 1),
            "response_bytes": 0,
            "error": "proxy_auth_required" if tunnel_407 else type(reason).__name__,
            "via_proxy": use_proxy,
        }


def proxy_url() -> str:
    scheme = os.environ.get("ROLA_PROXY_SCHEME", "http").lower()
    if scheme != "http":
        raise ValueError("This reference app supports an HTTP proxy; use a SOCKS5-capable client for SOCKS5.")
    host = os.environ["ROLA_PROXY_HOST"]
    port = int(os.environ["ROLA_PROXY_PORT"])
    if not host or not 1 <= port <= 65535:
        raise ValueError("Invalid proxy endpoint")
    username = quote(os.environ["ROLA_PROXY_USERNAME"], safe="")
    password = quote(os.environ["ROLA_PROXY_PASSWORD"], safe="")
    return f"http://{username}:{password}@{host}:{port}"


class Handler(BaseHTTPRequestHandler):
    def send_json(self, payload: dict, status: int = 200) -> None:
        encoded = json.dumps(payload, separators=(",", ":")).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(encoded)))
        self.end_headers()
        self.wfile.write(encoded)

    def do_GET(self) -> None:
        if self.path == "/health":
            self.send_json({"ok": True, "service": "app"})
        elif self.path == "/direct-check":
            self.send_json(result_for(CHECK_URL, use_proxy=False))
        elif self.path == "/proxy-check":
            try:
                self.send_json(result_for(CHECK_URL, use_proxy=True))
            except (KeyError, ValueError):
                self.send_json({"ok": False, "error": "proxy_configuration_invalid"}, status=500)
        else:
            self.send_json({"ok": False, "error": "not_found"}, status=404)

    def log_message(self, fmt: str, *args) -> None:
        # Avoid request headers or URLs containing credentials in application logs.
        print("app: " + (fmt % args).split("?")[0], flush=True)


if __name__ == "__main__":
    ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever()

The app exposes three fixed routes:

  • /health returns a local readiness response and does not use the proxy.
  • /direct-check calls the configured ROLA_CHECK_URL with proxy use disabled, giving a direct baseline from the app container.
  • /proxy-check calls the same URL through the Rola HTTP proxy and returns only status, elapsed time, response size, proxy mode, and a parsed ip field. It never returns the response body or credentials.

The sample deliberately uses a fixed URL from ROLA_CHECK_URL rather than accepting a URL query parameter. That prevents turning a health endpoint into an unrestricted server-side request feature. Set the URL only to an endpoint you are authorized to test.

Step 3: Configure NGINX as the inbound reverse proxy

Create the nginx/ directory and save this as nginx/nginx.conf. Mounting the directory lets NGINX see files replaced by editors during updates.

events {
    worker_connections 1024;
}

http {
    log_format main '$remote_addr - $request_method $uri $status $request_time';
    access_log /var/log/nginx/access.log main;

    server {
        listen 80;
        server_name _;

        location = /health {
            proxy_pass http://app:3000/health;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
        }

        location / {
            proxy_http_version 1.1;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_pass http://app:3000;
            proxy_redirect off;
        }
    }
}

The forwarded headers describe the original client request to the application. This single-entry-point example overwrites X-Forwarded-For with the address NGINX observed, so an internet client cannot inject an identity through a pre-existing header. If a trusted load balancer sits in front of NGINX, adapt the header policy and application trust list to that documented proxy chain.

connection-fields

Step 4: Validate, start, and reload

Run each block in order. Stop if a command fails. Compose waits for the app health check before the one-off NGINX container resolves app on the shared network.

docker compose config --quiet &&
  docker compose up --build --wait --wait-timeout 60 app &&
  docker compose run --rm --no-deps nginx nginx -t -c /etc/nginx/lab/nginx.conf &&
  docker compose up -d nginx

Check the incoming path. The expected response is HTTP 200 with {"ok":true,"service":"app"}.

docker compose ps
curl --noproxy '*' --fail --show-error --max-time 15 http://127.0.0.1:8080/health

terminal-check

Before editing the working configuration, save a backup.

cp nginx/nginx.conf nginx/nginx.conf.bak

After editing, validate, reload, and check the route in order.

docker compose exec -T nginx nginx -t -c /etc/nginx/lab/nginx.conf &&
  docker compose exec -T nginx nginx -s reload -c /etc/nginx/lab/nginx.conf &&
  curl --noproxy '*' --fail --show-error --max-time 15 http://127.0.0.1:8080/health

If validation or the health check fails, restore the backup, then repeat the validation, reload, and health-check commands above.

cp nginx/nginx.conf.bak nginx/nginx.conf

If NGINX has exited, repeat the startup block after restoring the file. When Compose recreates the app, its IP may change while the service name stays app. This static proxy_pass resolves the name when NGINX loads its configuration. Wait for the replacement app to become healthy, then validate and reload NGINX to resolve it again. If your configuration contains an IP literal, replace it with the service name or update the address before reloading.

Step 5: Verify the Rola exit IP and DNS mode

The included app makes the three checks explicit. Run them through the same NGINX entry point so the request path is curl → NGINX → app in every case:

curl --noproxy '*' --fail --show-error --max-time 15 http://127.0.0.1:8080/health

curl --noproxy '*' --fail --show-error --max-time 15 http://127.0.0.1:8080/direct-check

curl --noproxy '*' --fail --show-error --max-time 15 http://127.0.0.1:8080/proxy-check

Check that both responses report ok: true, an upstream HTTP 200, and a valid exit_ip. via_proxy identifies the mode requested from the app. Compare the direct IP with the proxy IP and check whether the proxy exit matches the issued endpoint and any targeting you selected. Treat a missing IP, a failed request, or an unexplained match with the direct baseline as inconclusive. If policy disallows direct internet access, skip the direct baseline and use the proxy account’s expected exit information.

The default ROLA_CHECK_URL is ipify’s JSON IP endpoint. It returns the public IP observed for the request, not geolocation or a DNS-resolution location. If location targeting matters, verify location separately with an approved geolocation source and record its date and method. Do not treat one IP response as proof of target-site authorization, high-volume performance, or a permanent IP reputation.

If the generated endpoint is SOCKS5, the included Python reference app is intentionally not a SOCKS5 client. Use an application client that documents SOCKS5 support, and choose socks5:// or socks5h:// according to that client’s DNS behavior. In cURL, --socks5-hostname is the equivalent of proxy-side hostname resolution; do not infer that HTTP 407 describes every SOCKS5 authentication failure.

If you maintain a separate PHP integration, see using cURL with a proxy in PHP.

For the end-to-end record, save the two JSON responses without credentials, then inspect the application and NGINX logs:

docker compose logs --tail=100 nginx app

If /health and /direct-check work but /proxy-check returns proxy_configuration_invalid, check the app’s four Rola variables and the documented endpoint scheme. If /proxy-check returns an HTTP proxy status such as 407, verify the issued host, port, username, password, and authentication method. If the proxy check returns the same IP as the direct check, the request may be bypassing the proxy or the application may be receiving the wrong environment values.

troubleshooting-layers

Common errors and diagnosis

502 Bad Gateway or upstream connection refused

This usually belongs to the NGINX-to-app hop. Confirm that the application listens on 0.0.0.0:3000, not only 127.0.0.1:3000, and that the Compose service is named app. Check docker compose ps and the application logs. Do not fix a 502 by pointing proxy_pass at the Rola gateway; that changes the wrong layer.

For outbound connection refusals, check gateway reachability from the app container first. Browser-specific examples are covered in proxy connection refused.

407 Proxy Authentication Required

A 407 is an HTTP proxy response that means the proxy authentication exchange was not accepted. Re-copy the generated username and password, verify the HTTP endpoint protocol and port, and check whether a username parameter was truncated or URL-decoded incorrectly. If you are using SOCKS5, inspect that client’s negotiation or authentication error instead; 407 is not the standard response for every SOCKS5 failure. Do not log the full proxy URL while debugging.

DNS or host not found

For the internal hop, use the Compose service name app and keep NGINX and the application on the same user-defined network. For the external proxy hop, verify that the container can resolve the issued proxy hostname. If your client supports socks5h, use it when the destination hostname must be resolved by the proxy. The NGINX resolver directive does not make an HTTP reverse-proxy block into a SOCKS5 client.

Health works, but the exit IP does not change

The health route confirms the inbound path. Compare both IP checks from the same app. This Compose service clears both cases of the proxy bypass variable. If you adapt the example to another client, check its bypass settings and confirm that it reads the intended gateway settings.

Reload broke the route

Run nginx -t against the mounted file, inspect docker compose logs nginx, restore the last known-good file, and reload. Keep the change small enough that you can identify whether the failure is syntax, service discovery, an upstream port, or a header policy.

When Rola IP fits this architecture

Rola IP is relevant at the point where a containerized application needs a documented outbound proxy endpoint, location control, session behavior, or a separate egress path for an authorized workflow. Its current documentation lists rotating residential, rotating datacenter, and mobile IP networks, with country targeting available across those networks and state/city targeting documented for rotating residential. Choose the network and session model based on the task rather than assuming that a proxy solves every target-side restriction.

Review Rola’s proxy network and connection options when choosing a network for your task.

If the workload needs residential network addresses, review Rola’s residential proxies against your authorized use case. Keep target access authorized, respect the target’s terms and rate limits, and treat the proxy as a network-routing component rather than an authorization or anonymity guarantee.

FAQs