Most scripts that change nginx config work like this:
nginx -t && nginx -s reload If the test passes and the reload exits 0, the script assumes the change is live. Sometimes it isn't, and nothing in the script's output says so.
This article covers two lesser-known nginx behaviours that cause this, and a deploy procedure that handles them: versioned config directories, an atomic symlink swap, a confirmed reload, and a fallback for when nginx won't start at all. The examples come from the Go control plane of an open-source OpenResty-based gateway. The ideas carry over to Ansible, shell scripts and any other tool that edits nginx config.
The symptom
You add a server block with listen 8443. nginx -t says syntax is ok and test is successful. nginx -s reload exits 0. But nginx never starts listening on 8443: requests to that port still reach whatever other program holds it, and the existing sites keep serving the previous config. The only trace is a line in the error log:
[emerg] ... bind() to 0.0.0.0:8443 failed (98: Address already in use) Two facts explain this.
nginx -t does not open listening sockets. It parses the config, checks directives and loads files such as certificates, but it does not bind ports. A port held by another process, an address that isn't on this host, or a privileged port without the needed capability all pass the test. They fail only when the real master process tries to bind().
nginx -s reload is asynchronous. It sends SIGHUP to the master and exits. The master then re-reads the config, opens log files and listening sockets, and starts new workers. If this fails, the master logs the error, rolls back and keeps running the old configuration with the old workers. The command that sent the signal had already exited successfully.
So "test passed, reload returned 0" means "the config parses, and a signal was delivered". It does not mean the config is being served.
Versioned directories and an atomic "current" symlink
Before getting to confirmation, the layout needs to make rollback cheap. Editing files in place under /etc/nginx/conf.d means a failed change leaves you with broken files and no clean way back.
Corvus renders every deployment into its own directory and points nginx at a symlink:
/data/nginx/ versions/v000041/nginx.conf, hosts/*.conf, ... versions/v000042/nginx.conf, hosts/*.conf, ... current -> versions/v000042 The master is started with -c /data/nginx/current/nginx.conf. A reload re-reads that path, so it picks up whatever current points to at that moment.
One detail matters here. Inside the rendered files, includes use the version directory and not the symlink (include /data/nginx/versions/v000042/hosts/*.conf;). Once nginx has read nginx.conf, every file it pulls in belongs to the same version, even if the link moves during the reload.
The swap itself must be atomic. Whether ln -sfn is atomic depends on the implementation: current GNU coreutils creates a temporary link and renames it over the destination, but older versions and some other implementations unlink and then create, which leaves a short window with no current. Rather than depend on that, create a temporary symlink and rename() it over the old one yourself. On POSIX filesystems, rename() atomically replaces the destination. Simplified from the swapLink method in control/internal/deploy/deploy.go:
func swapLink(baseDir, versionDir string) error { current := filepath.Join(baseDir, "current") tmp := current + ".tmp" _ = os.Remove(tmp) // leftover from a crash if err := os.Symlink(filepath.Join("versions", versionDir), tmp); err != nil { return err } return os.Rename(tmp, current) // atomic replace } The link target is relative (versions/v000042), so the whole tree can be moved or mounted elsewhere. The real code also checks that the directory name matches the expected pattern (^v[0-9]{6,19}$) and resolves inside versions/, because names come from a database that someone could edit.
The same temp-file-then-rename pattern works for single files. Corvus's writeFileAtomic in control/cmd/corvus-control/main.go writes to a temp file in the same directory, sets its mode, calls fsync, renames it over the target, then fsyncs the directory so the rename survives a crash. Corvus uses it for secret files. Any tool that writes one nginx config file in place should do the same.
Old version directories are pruned after each deployment. By default Corvus keeps the directories of the 20 most recent deployed versions (a rollback entry names an older directory, so that one is kept too) and the directory of the active version. The directory current points to is never deleted.
Test the new directory before anything points at it
The new version is rendered and tested before the link moves:
openresty -t -q -e stderr -c /data/nginx/versions/v000043/nginx.conf -e stderr (nginx 1.19.5 and later) keeps the test from writing to the default error log path, which may be read-only. The combined stdout and stderr is kept as the test output.
In Corvus, a deployment runs inside a database transaction (Deployer.Apply). The settings change, a new version row is inserted, files are rendered, and openresty -t runs. If the test fails:
- the version directory is deleted,
- the transaction rolls back, so the stored settings are unchanged,
- a separate
failedversion row is written outside the rolled-back transaction, with the full test output, so the console can show exactly what nginx rejected.
The live config was never touched. If you take one thing from this section, it's this: run the test on the new files in a new location, not on files that are already where nginx will read them.
Confirm the reload actually took effect
This is the part most scripts skip. The fix is to have the served config tell you which version it is.
Every rendered nginx.conf has a loopback-only status server. Simplified from control/internal/compiler/templates/nginx.conf.tmpl, where the port comes from a template value that defaults to 9180:
server { listen 127.0.0.1:9180; location = /version { default_type text/plain; return 200 "v000043"; } location = /healthz { default_type text/plain; return 200 "ok\n"; } } The version string is the name of the version's own directory, filled in by the compiler (Name: filepath.Base(dir)). A worker running config v000043 can only answer v000043.
After the swap and SIGHUP, activate calls WaitActive (control/internal/gateway/gateway.go). It polls http://127.0.0.1:9180/version every 50 ms for up to 15 seconds:
- If the answer equals the new name, the reload is confirmed.
- If the deadline passes and nginx still answers with a different name, it returns a
NotAcceptedError. That means nginx is up and serving, but not the new config.activateswaps the link back to the previous directory, so the next reload or restart doesn't pick up the rejected version, and the error goes back to the caller.
The poller disables HTTP keep-alive. After a reload, old workers stop accepting new connections but finish the ones they have. A reused connection could keep reaching an old worker and report the old version. A fresh connection each time goes to whichever workers are accepting.
The error should explain itself. Corvus runs OpenResty with -e stderr and keeps recent [emerg], [alert] and [crit] lines from its stderr. NotAcceptedError includes the lines logged since the reload was requested, trimmed to the message and de-duplicated, because nginx repeats a failed bind() several times. The operator sees one line:
the gateway kept the previous configuration (v000042) instead of v000043: bind() to 0.0.0.0:8443 failed (98: Address already in use) If no such lines were captured, the message ends with a pointer to the gateway log instead.
Back in Apply, this error rolls back the database transaction and is recorded as a failed version with that message, just like a failed -t.
Simplified confirm loop:
func waitActive(statusURL, want string, timeout time.Duration) error { client := &http.Client{ Timeout: time.Second, Transport: &http.Transport{DisableKeepAlives: true}, } deadline := time.Now().Add(timeout) serving := "" for { if resp, err := client.Get(statusURL); err == nil { b, _ := io.ReadAll(io.LimitReader(resp.Body, 256)) resp.Body.Close() serving = strings.TrimSpace(string(b)) if serving == want { return nil } } if time.Now().After(deadline) { if serving != "" { return fmt.Errorf("still serving %s, not %s", serving, want) } return fmt.Errorf("no answer from %s", statusURL) } time.Sleep(50 * time.Millisecond) } } Some limits apply:
- If the status endpoint gives no answer at all before the timeout, Corvus logs a warning and still counts the deployment. It can't tell "rejected" from "slow" in that case. Only a definite wrong answer triggers rollback.
- The check proves the master switched configs. It does not prove every virtual host works. A wrong upstream address still deploys fine.
- If nginx isn't running, there is nothing to ask, and the check is skipped. The next start loads whatever
currentpoints to, which is the next section.
When nginx won't start at all
The same bind() problem can show up at boot. Say the config was deployed while the port was free, then another container took the port, then the host rebooted. Now nginx exits immediately, every time.
Corvus supervises OpenResty as a child process. Any exit within 30 seconds of starting counts as a boot failure. The number of consecutive boot failures goes to gatewayBootFailure in control/cmd/corvus-control/degraded.go. The count resets when the gateway runs longer than that or when a new configuration is deployed.
- First and second failure: retry the same config after a backoff that starts at 5 seconds and doubles. A port held briefly, for example by a container starting at the same moment, gets two more chances.
- Third failure:
Fallback. Walk back through the recent version history, newest first, skipping the version that just failed, failed attempts and safe-mode versions. Re-test each candidate's directory withopenresty -tand activate the first one that passes. This is recorded as an automatic rollback. If no candidate passes,Fallbackgoes straight to safe mode. - Fourth failure, unless the fallback already ended in safe mode:
SafeMode. Render the config of an empty installation (only the default server, no hosts or streams) from a throwaway empty database, test it, and activate it. - After that: keep retrying with backoff up to 2 minutes.
When the policy switches configuration, the new config is started right away, without waiting for the backoff.
Throughout all of this, the admin console stays up, because it is served by the Go process and not by nginx. The operator can see why the gateway went down, using the [emerg] lines kept from the failed start, and fix the settings.
Some details that avoid surprises:
- Fallback and safe mode don't change the stored settings. The console shows the settings as "not deployed". On the next restart, the stored settings are tried again, because whatever blocked them (the port) may be gone.
- If an operator deploys a new version while the policy is running, the policy checks that the failing version is still the one
currentpoints to. If it isn't, the policy gives up (ErrLiveChanged) and the operator's deployment wins. - On a normal restart, when the active version is neither a manual rollback (kept as is) nor an automatic fallback (the stored settings are redeployed), Corvus re-renders from the database and compares the result file by file with the active version's directory (
rendersSame/sameTree). If they are identical, it keeps the existing directory and creates no new version, so restarts don't fill the history.
A checklist for your own scripts
You don't need a control plane to use most of this:
- Render each change into a new directory. Point nginx at a
currentsymlink, and use the versioned path, not the symlink, in includes. - Run
nginx -t -c <new>/nginx.confbefore the link moves. Keep the output. - Swap the link atomically: create a temp symlink, then
mv -T/rename(). Don't depend onln -sfnbeing atomic. - Put a version id in the config itself, served on a loopback-only location.
- After reload, poll that location with fresh connections until it reports the new id.
- If it still reports the old id, swap the link back and show the error log lines written since the reload.
- Keep a few old directories, and know which one you'd fall back to if nginx won't start.
A bash version of steps 2 to 6:
NEW=v000043 BASE=/etc/nginx/deploy PREV=$(readlink "$BASE/current") LOG_MARK=$(wc -l < /var/log/nginx/error.log) swap() { # atomically point current at $1 (relative target) rm -f "$BASE/current.tmp" ln -s "$1" "$BASE/current.tmp" && mv -T "$BASE/current.tmp" "$BASE/current" } nginx -t -c "$BASE/versions/$NEW/nginx.conf" || exit 1 swap "versions/$NEW" || exit 1 nginx -s reload || { swap "$PREV"; exit 1; } for i in $(seq 150); do # at least 15 s got=$(curl -s -m 1 -H 'Connection: close' http://127.0.0.1:9180/version) [ "$got" = "$NEW" ] && { echo "live: $NEW"; exit 0; } sleep 0.1 done echo "nginx still serving '${got:-nothing}', not $NEW; rolling back link" >&2 swap "$PREV" tail -n +"$((LOG_MARK + 1))" /var/log/nginx/error.log | grep -E '\[(emerg|alert|crit)\]' >&2 exit 1 mv -T is GNU coreutils. On other systems, use a tool that calls rename() directly. The status server block needs return 200 "v000043"; written in by whatever renders your config.
This is how Corvus, an open-source reverse proxy with a WAF that I maintain, deploys config: https://github.com/corvus-gateway/corvus
