Ravindra BagaleCourses & study guides मराठी Track your progress

Chapter 8: Configuring Nginx and Apache

AWS Cloud

8.10 Troubleshooting configuration problems

Friends, if you changed a config and something broke, don't panic. Identify the symptom, find the cause in the table, and try one fix at a time – test after every fix.

SymptomPossible causeNext check
403 after changing the rootSite policy, index selection, directory traversal, file access, or host policyCheck the error for the matched hostname and path. Inspect the selected mapping and relevant permissions or policy for the real worker.
Unexpected welcome pageThe request reached a fallback or another listenerCompare exact destination and hostname. Inspect the parsed site group and confirm the live response.
Nginx parser reports an unexpected brace or an unterminated directiveWrong directive grammar or enclosing blockRead the indicated line, preceding statement and surrounding braces. Recheck the intended candidate.
Apache reports an invalid command or extra argumentMissing module, wrong context, spelling or inline commentInspect candidate modules and directive syntax. Put comments on their own lines.
Bind permission deniedAddress, privileged port or service security policyCheck the intended socket, service identity and applicable local policy before adjusting labels.
New port unreachable from a clientListener, bind address, route, protocol or network policy differsTest locally first, then compare the approved remote route and scope.
Address already in useAnother listener or an overlapping bindIdentify the owning socket and keep unrelated services active. Use a free high port for a local lab.
Changes have no effectWrong source, ignored include, rejected activation or stale response pathCompare candidate configuration, service activation evidence and a fresh named request.
PHP source is returned instead of executingThe file bypassed its intended interpreterFollow the service’s incident procedure and inspect the selected handler and files that could have been served.

Ravindra Bagale's Tip

With the relevant program and startup arguments, nginx -T shows the files parsed for that invocation and Apache -S shows the candidate virtual hosts. Compare that evidence with activation and a fresh named request to the running service.

Lab

Use the private fixture below to compare a route denial, a missing file, an unmatched site, an upstream connection failure and an upstream timeout. Match each reply to the correct log and validate one narrow repair.

How to think while troubleshooting

  1. Write down the exact symptom: the status code, the page you see, the error line.
  2. Check recent relevant configuration, deployment or dependency changes.
  3. Follow the request through the relevant layers. Use a targeted comparison at the first observed mismatch.
  4. Change one thing, test, then decide.
Layer by layerDNSSecurity groupnginx / ApacheApp serverDatabase
An example request path. Confirm the layer that produced the symptom and check its relevant upstream or dependency.

Diagnose by response and gateway evidence

The same code can have different causes depending on what sits behind the web server.

502 and a TCP upstream

Read the exact upstream address and error. Verify the intended listener from the gateway’s network context. An app can be running on another address or port.

502 and a managed worker

Check the relevant process or worker log and the gateway’s configured endpoint. A startup or import failure is one possibility, as are connectivity and response-format issues.

502 and a FastCGI socket

Check the configured runtime, socket path, socket access and FastCGI error. A missing path and a permission denial need different checks.

502 and 503 report different failure states

Identify the component that sent the code. A gateway can generate 502 for a failed upstream interaction. A service or intermediary can use 503 to report temporary unavailability.

502 and an application server

Compare the gateway’s error and the intended local application listener. Verify startup and readiness through the service’s approved logs and health route.

504 and upstream timing

Compare the applicable timeout with the gateway and application traces. Confirm which upstream or dependency delayed the response before deciding on a repair.

403 and enforcing file policy

On an enforcing SELinux system, correlate the exact file path and process with audit evidence. Apply only the context or policy justified by the service’s documented access model.

Example gateway symptom

Compare one gateway timeout with a direct authorized request to its configured upstream and check the matching logs. Identify where the request was received and which stage exceeded the applicable deadline.

Recap

  • Symptom, then "what changed?", then layer by layer.
  • Read the right log for your stack.

Turn the symptom into one request you can reproduce

The training center's library is working, but students say the workshop notes site is down. One student sees a familiar welcome page. Another says the request times out. A third can open the homepage but gets a forbidden response to a single file. These observations can describe different requests, hosts or stages of one system. Before deciding on a remedy, record the exact URL, intended destination, method, observed status or network error, and when it occurred. For a recurring problem, reproduce it with a targeted request and a unique harmless trace marker. A small complete observation tells you more than a broad warning that the website stopped working.

The starting point is the request. A URL gives a scheme, host, optional port, path and sometimes a query. Each can affect where the request goes and which rule controls it. A browser also has cache state, extensions and authentication context that a command-line test may not share. Capture enough context to compare the same route. Look for any automatic redirect and distinguish its initial response from the final output. If you know the expected host and an approved origin endpoint, control name resolution for one curl request while retaining the expected hostname. Record whether the test went through the ordinary edge or directly to the origin.

An origin is the service that supplies or generates the response for an application in this context. An external visitor may reach an intermediary such as a CDN or load balancer before the origin. The intermediary can perform name selection, add a status of its own or serve a stored response. Reproduce the public issue first if possible, then compare a local or permitted internal probe using the exact same hostname and path. If the two outcomes differ, your job is to identify the first handoff where the evidence diverges. The origin working for one route is a valuable observation, but it does not by itself prove the edge reaches that origin.

An access log records requests and their outcomes according to a configured format. An error log reports operational details such as syntax, file or upstream problems. Some errors go to a service journal or standard output. An upstream is a service behind a gateway or proxy that receives a forwarded request. The diagnostic sequence often needs evidence at both hops. Use timestamps, the selected site and a safe trace marker to correlate records. Avoid logging real credentials, token-bearing URLs or entire private content. In the fixture the trace value is a short label we choose.

Read the failure at the layer that produced it

Start with the outermost missing evidence. If the intended hostname cannot resolve from the client, inspect the selected name lookup before changing an application site's file. If the name resolves but the connection cannot be made, inspect the destination address and port, listener and intervening route. A connection refusal can involve an absent listener or an active rejection. A timeout indicates that the client's operation did not complete within its time budget. It is consistent with several causes. Clean local loopback controls let you distinguish some possibilities without guessing at the cloud network.

If TCP connects and HTTPS fails, look at the connection setup, certificate and name that the client used. The HTTP route may never be reached. A mismatch between certificate name and URL often points to the selected TLS listener or certificate coverage. Do not disable verification to turn this observation green. Test the intended hostname, certificate and front-door listener. When a plain HTTP response already exists, you are past at least some connection stages. Identity of the server that answered can still be unknown. A front-end gateway can return an error when the application behind it is unreachable.

A welcome page or body from another site suggests that a service handled the request using another definition. Compare the effective endpoint and hostname first. On Nginx inspect the candidate with the same executable and startup arguments; on Apache use the appropriate virtual-host report. A successful parse only describes the files read for that invocation. The running service can still be using a previously accepted configuration. Check the relevant log and activation state to tie a correct file to the process. Removing a default site before confirming the real match can change other users' traffic while leaving the hostname wrong.

A 403 indicates refusal to fulfill a particular request. It can come from a web server authorization rule, operating-system permissions, effective host security policy, a forbidden directory listing or another component's policy. Check whether the path names an existing file, a directory requiring an index, or an application route. Read the precise error and find which scope handled it. On Linux, inspect parent traversal and file read permission for the actual service identity. On hosts with enforcing security policy, correlate relevant denial evidence before changing labels. A 403 is a symptom and gives no reason to grant broader access by itself.

A 404 ordinarily indicates the server has no current representation for the resource or is unwilling to disclose one. The route may have landed at the wrong site. A real file can be looked up under the wrong root or differ in path case. An application can respond with its own 404 even while the static layer works. Some services purposely send a neutral status to avoid exposing details. Use a site marker and the matching request log to separate a named site's missing path from an explicit unmatched-host fallback. Both can carry HTTP 404 while making different statements about what the server selected.

A 502 means a server acting as a gateway or proxy encountered an invalid response from the server it accessed. A connection failure or invalid upstream HTTP response can produce 502 in common Nginx configurations. A 504 means a gateway did not receive a timely upstream response needed to complete the request. An overloaded app, slow dependency or intentionally short timeout can be involved. Neither status singles out a specific language, framework or database. Compare the failed request with a direct probe to the exact upstream address, port and protocol from the proxy's own network context. Compare its timing and logs before deciding whether addressing, service readiness or backend latency is relevant.

Read what the original symptom establishes, then collect the next observation
ObservationEvidence establishedUseful next comparison
DNS lookup failsThe client could not resolve its chosen nameCompare resolver view and intended record for that name
Local connect refusedThe client could not establish its selected socket connectionCheck listener address, port and service startup on the intended host
HTTP 200 with wrong bodySome HTTP service returned a successful representationCompare authority, actual destination, selected site and expected body
HTTP 403A service refused the selected requestInspect the mapping, applicable policy and exact error, and compare a known allowed path
HTTP 502 or 504 at the edgeA gateway reported an issue with the upstream interactionRead the gateway error and test the configured destination from its own network context

Reproduce four failure classes on one private listener

Use a regular account in a disposable Bash shell with Nginx, curl and Python 3. The fixture uses Nginx at 127.0.0.1 port 18894, a Python origin at port 18895, and a known unused port 18896. Pick free ports and replace every matching reference if one is already in use. All three numbers refer to loopback on the same machine. The intentionally wrong, slow and denied routes are synthetic. You do not need a public address, cloud security changes, or any modification to an installed website. The goal is to produce errors with known causes and compare them using realistic diagnostic evidence.

Begin by checking the three sockets and creating the private scratch area. The positional ports in the script are all unprivileged high ports. The temporary socket reservation closes immediately and reduces ambiguity about the intended unbound test. The Nginx prefix and origin log each belong to the same scratch directory but are operated by independent child processes. The cleanup routine handles each tracked child if an error exits the shell before both have started. One file is publicly served by the fixture, and another synthetic file will remain inaccessible because a selected rule refuses it. They are harmless evidence markers.

if [ "$(id -u)" -eq 0 ]; then
  printf 'Use a regular practice account.\n' >&2
  exit 1
fi
nginx_bin=$(command -v nginx) || exit 1
python3 - <<'PY'
import socket
for port in (18894, 18895, 18896):
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as candidate:
            candidate.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            candidate.bind(("127.0.0.1", port))
    except OSError as exc:
        raise SystemExit(f"Port {port} is unavailable: {exc}")
PY
test "$?" -eq 0 || exit 1
diag_lab=$(mktemp -d /tmp/rb-http-diagnosis.XXXXXX) || exit 1
ng_pid=
up_pid=
diagnostic_cleanup() {
  if [ -n "$ng_pid" ] && kill -0 "$ng_pid" 2>/dev/null; then
    kill -QUIT "$ng_pid"
    wait "$ng_pid" 2>/dev/null || :
  fi
  if [ -n "$up_pid" ] && kill -0 "$up_pid" 2>/dev/null; then
    kill "$up_pid"
    wait "$up_pid" 2>/dev/null || :
  fi
  case "$diag_lab" in
    /tmp/rb-http-diagnosis.??????) rm -r -- "$diag_lab" ;;
  esac
}
trap diagnostic_cleanup EXIT
mkdir "$diag_lab/public"
printf 'workshop-public-ready\n' > "$diag_lab/public/ready.txt"
printf 'workshop-denied-fixture\n' > "$diag_lab/public/reserved.txt"

The Python upstream accepts a known GET path quickly and delays another for until a generated readiness marker appears. The code logs an arrival and safe trace label. It does not imply that a real application's database causes a timed-out request. After the gateway reports its timeout, release the readiness marker and repeat the same path directly. This local comparison distinguishes a reachable endpoint that initially withheld its reply from an address and port with no listener. Starting this tiny app through a separate child also gives a real startup error if one of the sockets is unexpectedly occupied.

cat > "$diag_lab/upstream.py" <<'PY'
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import time

release_file = Path(__file__).with_name("allow-response")

class Fixture(BaseHTTPRequestHandler):
    def do_GET(self):
        labels = {"/healthy": b"origin-healthy\n", "/delayed": b"origin-delayed-complete\n"}
        content = labels.get(self.path)
        if content is None:
            self.send_error(404)
            return
        trace = self.headers.get("X-Lab-Trace", "-")
        print(f"arrived path={self.path} trace={trace}", flush=True)
        if self.path == "/delayed":
            for attempt in range(400):
                if release_file.is_file():
                    break
                time.sleep(0.03)
            else:
                self.send_error(503, "fixture release window closed")
                return
        try:
            self.send_response(200)
            self.send_header("Content-Type", "text/plain")
            self.send_header("Content-Length", str(len(content)))
            self.end_headers()
            self.wfile.write(content)
        except (BrokenPipeError, ConnectionResetError):
            print(f"client-closed trace={trace}", flush=True)

    def log_message(self, fmt, *args):
        return

with ThreadingHTTPServer(("127.0.0.1", 18895), Fixture) as server:
    server.serve_forever()
PY
python3 "$diag_lab/upstream.py" > "$diag_lab/upstream.log" 2>&1 &
up_pid=$!
up_ready=''
for attempt in 1 2 3 4 5 6 7 8 9 10; do
  if ! kill -0 "$up_pid" 2>/dev/null; then break; fi
  up_ready=$(curl --noproxy '*' --max-time 1 -fsS \
    -H 'X-Lab-Trace: origin-start' http://127.0.0.1:18895/healthy 2>/dev/null) || :
  if [ "$up_ready" = origin-healthy ]; then break; fi
  sleep 0.2
done
if ! kill -0 "$up_pid" 2>/dev/null || [ "$up_ready" != origin-healthy ]; then
  cat "$diag_lab/upstream.log" >&2
  exit 1
fi

Now define the listener and deliberately distinct policies. Unknown authority reaches a default with a special body. The named workshop serves one direct readiness file. It explicitly denies a reserved fixture file and returns 404 for an absent file. A good proxy route uses port 18895 and the known healthy endpoint. The failure route connects to an unbound port. The slow route reaches the good upstream port but uses a one-second read-inactivity limit before response headers. A separate library server provides a status and body control while the origin routes fail.

cat > "$diag_lab/nginx.conf" <<'NGINX'
worker_processes 1;
pid nginx.pid;
error_log error.log notice;
events { worker_connections 32; }
http {
    default_type text/plain;
    client_body_temp_path body;
    proxy_temp_path proxy;
    fastcgi_temp_path fastcgi;
    uwsgi_temp_path uwsgi;
    scgi_temp_path scgi;
    log_format diag 'site=$server_name host=$http_host uri=$uri code=$status '
                    'upstream=$upstream_addr upstream_code=$upstream_status '
                    'elapsed=$request_time upstream_elapsed=$upstream_response_time trace=$http_x_lab_trace';
    access_log access.log diag;
    server {
        listen 127.0.0.1:18894 default_server;
        server_name fallback.test;
        return 404 "fallback-no-site\n";
    }
    server {
        listen 127.0.0.1:18894;
        server_name workshop.test;
        root public;
        location = /reserved.txt { deny all; }
        location = /api/healthy {
            proxy_pass http://127.0.0.1:18895/healthy;
        }
        location = /api/refused {
            proxy_connect_timeout 1s;
            proxy_pass http://127.0.0.1:18896/healthy;
        }
        location = /api/slow {
            proxy_read_timeout 1s;
            proxy_pass http://127.0.0.1:18895/delayed;
        }
        location / { try_files $uri =404; }
    }
    server {
        listen 127.0.0.1:18894;
        server_name library.test;
        return 200 "library-still-ready\n";
    }
}
NGINX
"$nginx_bin" -e stderr -p "$diag_lab/" -c "$diag_lab/nginx.conf" -t || exit 1
"$nginx_bin" -e stderr -p "$diag_lab/" -c "$diag_lab/nginx.conf" -g 'daemon off;' &
ng_pid=$!
for attempt in 1 2 3 4 5 6 7 8 9 10; do
  if [ -s "$diag_lab/nginx.pid" ]; then break; fi
  if ! kill -0 "$ng_pid" 2>/dev/null; then break; fi
  sleep 0.2
done
if ! kill -0 "$ng_pid" 2>/dev/null ||
   [ ! -s "$diag_lab/nginx.pid" ] ||
   [ "$(tr -d '[:space:]' < "$diag_lab/nginx.pid")" != "$ng_pid" ]; then
  printf 'The private Nginx endpoint did not start. Inspect its log.\n' >&2
  if [ -r "$diag_lab/error.log" ]; then tail -n 12 "$diag_lab/error.log" >&2; fi
  exit 1
fi

The named log records both the incoming host and selected server, the normalized path and status, the upstream destination and status, and timing. An empty upstream flag on a static or denied request is expected. Different proxy settings or multiple attempted upstreams can produce several values in one field. This fixture uses one direct upstream per route, making that field easy to read. A proxy-generated upstream status entry can reflect the gateway's interpretation of a failed attempt. Do not use it as proof that the upstream ever transmitted a matching HTTP response.

Use distinct trace markers on the following GET requests. Each curl transfer prints status and its timing along with the beginning of the response. The local resolved address and host remain visible and repeatable. Browser users might see very similar error pages for several of these paths, so collect the status, selected rule and direct upstream evidence separately. Use the allowed file under the same named host as a control for the refused file and the intended independent library name as a control for the wider listener.

probe() {
  local name=$1 path=$2 trace=$3
  printf '\n%s %s %s\n' "$name" "$path" "$trace"
  curl --noproxy '*' --max-time 15 -sS --resolve "$name:18894:127.0.0.1" \
    -H "X-Lab-Trace: $trace" -o "$diag_lab/probe.body" \
    -w 'HTTP %{http_code} connected=%{time_connect} start=%{time_starttransfer}\n' \
    "http://$name:18894$path" || return 1
  head -c 110 "$diag_lab/probe.body"
  printf '\n'
}
probe workshop.test /ready.txt public-file
probe unknown.test /ready.txt unknown-name
probe workshop.test /reserved.txt denied-file
probe workshop.test /absent.txt missing-file
probe workshop.test /api/healthy proxy-ok
probe workshop.test /api/refused proxy-refusal
probe workshop.test /api/slow proxy-timeout
probe library.test /ready.txt library-control
touch "$diag_lab/allow-response" || exit 1
curl --noproxy '*' --max-time 15 -sS -H 'X-Lab-Trace: direct-slow' \
  -w 'direct HTTP %{http_code} start=%{time_starttransfer}\n' http://127.0.0.1:18895/delayed

The first request should show the 200 public marker. The unknown authority and absent path should both return 404, but only the former gets the fallback marker and its different server in logs. The reserved fixture exists and returns 403. The healthy proxy returns the Python marker, establishing that your origin works at its proper port. The wrong port produces 502. The slow gateway request produces 504 around the configured wait in this private case, while the direct request returns 200 after the fixture releases the response. The library continues answering, proving that an error for one upstream did not close the known shared listener.

Read the logs while the scratch scope remains active. The origin log should record the healthy proxy, the blocked delay and the direct delayed route that succeeds after release. The refused-route marker should be absent there. The Nginx error log should show distinct lines for a forbidden rule, a failed upstream connection and a timeout reading upstream headers. Wording can vary by platform and version. The log's destination address and port are the stable evidence. Repeat the controlled direct origin probe only if you need to verify where the delay occurred. The timeout measurement shown by curl covers the client-visible timing, which is different from a time field measuring a proxy upstream attempt.

printf '\nAccess and trace records\n'
tail -n 8 "$diag_lab/access.log"
printf '\nServer error details\n'
grep -E 'forbidden by rule|connect\(\) failed|upstream timed out' "$diag_lab/error.log"
printf '\nOrigin arrivals\n'
grep '^arrived ' "$diag_lab/upstream.log"
test -f "$diag_lab/public/reserved.txt" || exit 1

If you are submitting the exercise, save the selected records before the cleanup. State which scope emitted the status and which requests actually reached the upstream. A suggestive error message is useful but its attribution follows from the control and exact input. Once you finish the comparison, stop the two local children and remove the generated paths. The last command proves that the scratch directory is gone. If you observe a partial failure, note the furthest verified stage and then exit the practice shell so it can clean up.

diagnostic_cleanup
trap - EXIT
test ! -e "$diag_lab" && printf 'Troubleshooting lab removed.\n'

Read the timing and ownership in each log line

Start with the denied fixture, because it removes upstream complexity. The local file exists. A different file on the same named site was served successfully. The access log identifies workshop and the reserved path, and the error log describes a rule that rejected it. The request never needed the Python service. That evidence gives specific causal reasoning. The collection tells you where a change would belong if the denial were unexpected. In this exercise the denial is deliberate, so the correct response is to record that the protection worked. A status code is a signal about one request and may match the planned behavior.

Now compare the two 404 results. The named workshop's missing file hit the expected site and returned a generic missing response. The unknown name hit a separate fallback whose body says no site. Both had the same numeric status and no upstream path. Access logs record the relevant configured name and incoming authority. If the apparent missing workshop path instead used the fallback, focus on virtual host and listener selection. If it used workshop, continue to location, root and file handling or the application handler. A fixed URI on two different sites can lead to completely different diagnosis.

Compare the 502 and 504. When Nginx attempted to open the deliberately wrong loopback port, the OS in this fixture reported a refused connection. The error logs show the addressed port, and the origin has no matching trace for it. The 504 case went to the correct port. Its origin received and logged the delayed request before Nginx's response-header wait expired. After releasing the fixture readiness marker, an independent direct request completed the same origin path. The pair supports the claim that the service received the request and withheld headers until the simulated dependency was ready. The readiness condition had changed before the direct control. In another system the cause could be connection establishment, load or any upstream operation. Correlate it before inferring a component.

Read the measurements at their actual boundary. Curl's connection time here describes the client's TCP connection to Nginx. It does not measure the next hop. Its start-transfer time runs until the response begins arriving at the client. The separate upstream time in Nginx logs covers the attempted backend interaction according to that module's fields. The read timeout controls the delay between successive reading operations from the proxied server, rather than imposing an absolute total response time. Our origin sends no headers until the local release condition, so the configured timeout is easy to observe. With streaming data, intervening bytes can change the pattern even when the overall response lasts longer.

When several upstream attempts are configured, the access record can list multiple addresses, statuses or timings. You might need to match each attempt with its corresponding occurrence. A 502 returned by Nginx can be its own response to a connection failure instead of bytes actually sent by the origin. The presence of an upstream status in a proxy log does not automatically mean the named application emitted that status. A trace in one hop and the address and error at the next hop provide stronger attribution.

The readiness marker models a dependency wait. It makes the comparison repeatable without predicting how long a real service will spend in its database or another API. During the first attempt, the origin can acknowledge arrival in its own log while delaying any response to Nginx. After the marker is present, another request on the same path completes. Changing readiness is an explicit change to that input, not an unexplained improvement caused by bypassing the gateway. In an actual incident, distinguish an upstream reached at all from a dependency ready to handle its work.

For the live troubleshooting record, include when and where you obtained each observation. An error logged several minutes earlier may concern a different request or generation. The access record can help connect that timestamp to your selected event. On a system with time zone differences, normalize times or keep the stated offset. For a distributed route, use the existing correlation identifier or an approved harmless label if the policy permits it. Compare the endpoint the customer reaches and the one you can test from the proxy. Curling the origin from a third workstation may succeed while the proxy's network namespace cannot reach it.

Plan a targeted repair and prove it with the same probes

When the wrong port caused the fixture's failure, you could fix that specific mapping rather than raising a timeout. A timeout does not open a missing listener. Check the healthy endpoint and actual expected target first. Then correct the selected proxy destination under the usual change workflow. Reuse the original request, capture the new body and verify the previously unaffected library. Record which origin log entry now matches a fresh trace. The fix to the candidate is a string edit. The proof is that the actual application received the request at the expected endpoint and returned the intended result.

Recover the refused route in the isolated exercise before teardown. Keep the short read timeout case and protected file unchanged for comparison. Save the config outside any active include, and check exactly one expected old destination. The Python helper changes only that fixture reference. Ask the parser to verify the candidate before signaling the tracked private master. Then compare a fresh request to the original user path. If the gateway responds with the previous result just after activation, give it a short bounded chance to settle and check its log.

cp -p -- "$diag_lab/nginx.conf" "$diag_lab/nginx-before.conf" || exit 1
python3 - "$diag_lab/nginx.conf" <<'PY'
from pathlib import Path
import sys

config = Path(sys.argv[1])
text = config.read_text()
old = "proxy_pass http://127.0.0.1:18896/healthy;"
new = "proxy_pass http://127.0.0.1:18895/healthy;"
if text.count(old) != 1:
    raise SystemExit("Expected exactly one wrong fixture port")
config.write_text(text.replace(old, new))
PY
test "$?" -eq 0 || exit 1
"$nginx_bin" -e stderr -p "$diag_lab/" -c "$diag_lab/nginx.conf" -t || exit 1
kill -HUP "$ng_pid" || exit 1
for attempt in 1 2 3 4 5 6 7 8 9 10; do
  probe workshop.test /api/refused repaired-proxy || exit 1
  if grep -Fxq origin-healthy "$diag_lab/probe.body"; then break; fi
  sleep 0.2
done
grep -Fxq origin-healthy "$diag_lab/probe.body" || exit 1
probe library.test /ready.txt library-after
probe workshop.test /reserved.txt denied-after
grep 'trace=repaired-proxy' "$diag_lab/upstream.log"

The new output should report 200 and the healthy origin marker for the original path, and the upstream log should now include the repair trace. The path name still says refused because we kept it stable as an input; the change is the selected destination. The library result and intentional access denial give distinct controls. The timeout policy is unchanged. To repeat the 504 condition, run the experiment with the readiness marker initially absent so its delayed handler again withholds headers. The safe repair has a small scope and a predictable effect. Cleanup removes the lab whether you run the optional repair or stop after diagnosis.

Repair for a real 504 requires different evidence. Decide where the latency is spent and whether the response should be fast at all. Some operations need asynchronous processing or a deliberately different time budget. A smaller request can be a useful positive control when only expensive inputs fail. Do not label a database slow simply because it appears in the architecture. Inspect application timing or dependency evidence within your allowed diagnostic workflow. Extending a timeout can keep more requests waiting and may have a capacity cost. If duration is increased deliberately for a route, verify that the expected result now completes and that unrelated probes and error patterns remain acceptable.

When checking a file policy, identify the actual culprit before choosing a change. If the 403 was an intended rule, protect it and verify the correct public sibling. If it was a missing index, decide whether installing the approved index is appropriate. If the path's access relationship with its worker changed, change only the relevant authorization or filesystem metadata within the service's approved ownership. A broad grant can make a probe succeed while incorrectly exposing other contents. Restore prior input when you cannot justify a scoped repair within the approved window. A reversible change is more valuable than adding another untested edit after every new symptom.

Diagnose earlier startup and later runtime failures with different checks

A startup failure can occur because the parser rejects an instruction, an expected module is missing, a log or certificate cannot be opened, or a listener is unavailable. Use the setup and control clues for the exact program. For a parser complaint about punctuation, read the file context and nearby tokens rather than assuming the error always points to the previous line. For an unknown Apache authorization directive, confirm the intended module and startup config before editing grammar. A missing argument or invalid inline comment is another possibility. These causes can look similar when the only observation is that the process returned a failure code.

Now consider an operator who copied the config but saw no change. Verify the entry file and includes for the actually running service. Compare the chosen source file, its candidate hash or exact bytes and the observed reply from the matched host. An error can come from editing a saved file or from placing a new one outside the enabled directory. The parsed candidate might be correct but never applied. Conversely, a rejected reload can leave a healthy old process and a broken startup candidate on disk. Use evidence about both the file set and the live program to tell those cases apart. See the safe change workflow for the isolated parser and bind comparisons.

For an inherited package app or language runtime, check the installed service name, its configured socket and the application route. A Unix socket is an endpoint represented using a local filesystem path. A failure saying the socket path does not exist differs from a failure saying the process cannot open it. A TCP port can show an analogous missing listener or blocked request. Do not run a guessed app unit command because a common framework often uses a familiar port. Use the configured endpoint found in the proxy trace and test it with a protocol appropriate to that service. A FastCGI socket does not speak normal HTTP just because a browser-facing server sends work to it.

An HTTP script file being returned as a direct download is particularly important. It can mean the route exposed source instead of passing it to the intended language handler. Limit exposure using the service's approved incident workflow and check whether sensitive source was served. Inspect the PHP or application handler mapping and modules before re-enabling that path. A successful static GET is not proof an application interpreter is configured. The normal handler must run with the right scope and input. This page does not need a real script download to prove that point. Use a synthetic health response when confirming a corrected application route.

If you are looking at a public AWS listener, compare the direct application test with the load balancer's target status and metrics. Start from which component actually emitted the reported error. An Application Load Balancer and Nginx can both send gateway-related codes, and their logs record different request fields. An origin access record shows what reached that origin. If nothing arrived, inspect earlier connection or routing stages rather than every possible database. Network and health rules depend on the deployed resource and topology. Verify those settings through the relevant AWS and service documentation instead of reopening ports as a generic symptom fix.

Write a short diagnosis that someone else can verify

Build a small incident note with one row per symptom from the lab. Include the trace label, hostname, route, destination and status. Identify the component that emitted it using the actual server log. Specify which upstream, if any, received the request. For the 403, write the observed reason rather than guessing about file ownership. For the two 404s, compare selected server names. For the 502, show the exact unexpected port and missing trace. For the 504, show the correct upstream and its trace. That note should give all the evidence needed to defend four different diagnoses without relying on the appearance of an error page.

Design a three-request control set for a new problem. Suppose the workshop homepage works and the preview application returns a 504. Choose one static path on the named site, one proxy route expected to be fast and the failing path. Predict which boundaries each result verifies and record any performance difference. If the fast proxy also fails, inspect the shared upstream connection first. If only the preview fails, look at the route and its application behavior. An unrelated site on the same listener checks a different scope, so keep it available as another control for more widespread symptoms.

After making the fixture's one-port repair, write the log evidence that changed. Before it, the failed upstream endpoint was unbound and no matching arrival existed. After it, the working origin saw the new trace at its correct listener. The returned body now matches the observed healthy marker. The original client URI never changed. The library and chosen denial still behave as expected. A diagnosis and a repair are stronger when they predict both what should change and what should remain stable across the exact same input.

Try explaining the case to someone who has not worked with servers. Tell them which number identifies the external route, which server makes the second request and which program supplies the final body. Draw two arrows for the two connections. Place the 502 at the first arrow's server after its attempt toward the unbound second endpoint. Place the 504 at the same first server after it connected to a second endpoint that did not respond within the allowed read wait. That visual exercise turns vague gateway labels into an inspectable network path.

Practice distinguishing a diagnostic transfer exit status from its HTTP result. Curl can complete a transfer successfully and report an ordinary HTTP error because the connection worked. With its fail option, curl reports many HTTP errors as a nonzero process exit. In this exercise the diagnostic probes intentionally print the 403, 404, 502 and 504 responses instead of treating every HTTP error as an exceptional command failure. For a monitoring check you might choose a different option, but still record the returned status and expected marker. A transport failure may give no HTTP status to compare. Record both values rather than converting anything that is not 200 into one generic result.

Compare the trace that tested the upstream directly to the proxy's original trace. They are separate requests and should have separate identifiers in the record. A direct probe that completes after an availability condition changes does not show that the original request had the same conditions. State that the first arrived during the simulated dependency wait and the second arrived after release. Preserve that clarity in a real incident if engineers restored a dependency while another team was testing. A timeline with two observations and their shared path is often enough to explain apparently conflicting logs.

For another practice case, assume the static marker and the named origin both work, but a user says a public HTML route now serves the welcome page. Predict what an intended public authority and direct origin comparison can establish. Identify a fixed test path and meaningful marker. Describe which access log should record the original authority, which address served the response at each boundary, and what would indicate that a proxy used an unexpected Host value. This avoids changing a serving site to solve a question that is still about request selection.

Keep the comparison readable by showing the relevant log line beside each observation and naming the service that supplied it. If a load balancer or proxy inserts its own identifier, document how the trace maps across hops.

Once a repair appears to work, re-run the original input with the same hostname, route and protocol. A generic healthy request is useful as a control, but the original request is the one that establishes whether the symptom ended. Record one independent negative test when a failure status is expected on another route.

For a public incident, distinguish a tentative diagnosis from a verified one in your note. Mark which paths you could test, any logs you could not access and whether the public endpoint was involved. If you observed the issue only with a local synthetic input, describe that scope. Protect any records containing internal customer information. A useful report can tell the receiving operator what to inspect next without requiring them to adopt your first theory about the symptom.

Interview questions, quiz and revision cards

What do you ask first when someone says a website is down?

Ask for the actual observed request, including URL, status or connection error, time and how it was tested. A DNS failure, refusal and wrong-site success require different evidence. Reproduce one small named request and record which destination and route it used.

What distinguishes the lab's two 404 responses?

The unknown hostname selects the explicit fallback and its body marker. The existing workshop name selects the site's ordinary file location but does not find the requested file. The candidate log's selected server and controlled input establish the difference.

How do you separate 502 from 504 in this gateway fixture?

The refused route targets an unbound loopback socket and the origin never logs it. The timed-out route gets to a real origin that records the attempt but withholds the response past the gateway's wait. The gateway error and origin log prove distinct causes. Real deployments need their own evidence.

Why can a valid syntax check and a stale site coexist?

The check describes the files the command just read. The service may still use an earlier accepted version, or the request may go to another site or cache. Verify activation through service evidence and reproduce the actual named request.

What makes a good test for an intended access denial?

Use harmless files, confirm the selected path exists, expect the precise refusal, and compare a working sibling on the same site. Read the relevant error to identify the controlling rule. The status is useful when attached to the expected scope and input.

Quick quiz

  1. A request reaches an Nginx proxy, its error points to a refused connection on the configured upstream port, and the application logs no matching trace. Which next check fits?

    1. Find the upstream listener at the exact address and port
    2. Edit an unrelated cache header
    3. Assume the application got the request and read database query plans
    Check the first answer

    A. The evidence points to the attempted socket connection. Establish the expected destination and whether anything accepts it before inspecting later work.

  2. The protected file exists and one nearby file works, but the intended protected request gets 403 and the error log identifies a deny rule. What does the fixture show?

    1. The server cannot connect to DNS
    2. The configured access policy rejected the selected path
    3. All files under the host are missing
    Check the second answer

    B. The positive control works and the selected refusal matches its explicit rule. Verify policy before changing filesystem access.

  3. The origin logs arrival during a 504, then answers the same path after work can proceed. What comparison is most relevant?

    1. The filenames of unrelated hosts
    2. Whether the CDN configuration has a different project name
    3. The proxy's applicable upstream timeout and the actual origin latency
    Check the third answer

    C. The trace and timed origin response help explain why one budget was exceeded. Determine whether the request can be made faster or needs a justified different policy.

Reproduce one named request

Record destination, host, path, status or transport error and client context. Compare an unaffected request.

Static status and route owner

A selected fallback and a missing file can both return 404. Read the body marker, selected server and configured rule.

Two gateway hops

Use the exact gateway target, log and origin trace. A connection refusal and a delayed response need different repairs.

Prove the repair

Predict the changed result and steady controls. Activate the scoped candidate and repeat the original user request.

Primary references