---
title: "nginx 502 Bad Gateway를 해결하고 로그 1줄에서 원인 찾기"
description: "HTTP 502 Bad Gateway는 nginx 같은 게이트웨이가 뒤에 있는 서버에서 유효한 응답을 받지 못했다는 뜻이에요. nginx는 원인과 상관없이 같은 페이지를 보내고, 원인은 오류 로그에 남아요."
canonical: "https://logbrew.co/ko/errors/http-502"
last_updated: "2026-11-27"
---

# nginx 502 Bad Gateway를 해결하고 로그 1줄에서 원인 찾기

HTTP 502 Bad Gateway는 nginx 같은 게이트웨이가 뒤에 있는 서버에서 유효한 응답을 받지 못했다는 뜻이에요. nginx는 원인과 상관없이 같은 페이지를 보내고, 원인은 오류 로그에 남아요.

nginx가 앱에서 쓸 수 있는 응답을 받지 못했으니, nginx 오류 로그에서 그 요청을 찾으세요. `Connection refused`, `prematurely closed connection`, `too big header` 중 하나가 원인을 알려 줘요.

nginx 1.31.8, curl 8.7.1, Python 3.13.5, FastAPI 0.165.0, uvicorn 0.54.0 및 logbrew-fastapi 0.1.14 환경에서 2026년 11월 27일에 테스트

Canonical: https://logbrew.co/ko/errors/http-502

## 어떤 원인이 502를 보냈고 LogBrew는 무엇을 받았는지

| 재현한 원인 | 클라이언트가 `502` 받음 | LogBrew가 이벤트 받음 |
| --- | --- | --- |
| 앱이 실행 중이 아님 | 예, 0.001초 뒤 | 아니요 |
| 앱이 요청 도중에 멈춤 | 예, 1.008초 뒤 | 아니요 |
| 6,165바이트 헤더, `proxy_buffer_size 4k` | 예 | 예, `200` 스팬 |
| 본문 도중의 예외 | 아니요, 잘린 `200` | 예, 이슈 |
| 같은 헤더, `proxy_buffer_size 16k` | 아니요, `200` | 예, `200` 스팬 |
| 서버 2대, 둘 다 멈춤 | 예 | 아니요 |

nginx 1.31.8을 거쳐 logbrew-fastapi 0.1.14가 들어간 FastAPI 앱으로 curl 8.7.1이 보낸 요청 6개.

## 원인 찾기

### nginx가 502를 보냈는지 확인하기

nginx는 157바이트짜리 자체 HTML 페이지로 응답하고, 마지막 줄에 버전을 적어요. 원인마다 같은 페이지를 받았으니 페이지만으로는 원인을 알 수 없어요. 본문이 다른 502는 로드 밸런서나 CDN 같은 다른 프록시에서 온 것이고, 원인은 그 프록시의 로그에 있어요.

```bash
curl -sS -i 'http://127.0.0.1:28502/api/orders'
```

출력

```text
HTTP/1.1 502 Bad Gateway
Server: nginx/1.31.8
Date: Fri, 27 Nov 2026 06:44:56 GMT
Content-Type: text/html
Content-Length: 157
Connection: keep-alive

<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.31.8</center>
</body>
</html>
```

### 오류 로그에서 502 찾기

nginx는 502마다 `error` 수준의 줄을 1개 써요. `while` 앞의 단어가 원인을, 뒤의 단어가 단계를 알려 줘요. Linux에서는 첫 줄이 `connect() failed (111: Connection refused)`예요. 저희 Mac은 이 오류에 61번을 붙이고 앞에 `kevent() reported that`를 더해요.

```bash
grep -E 'connect\(\) failed|response header from upstream' /var/log/nginx/error.log
```

출력

```text
2026/11/27 09:47:06 [error] 36998#0: *1 kevent() reported that connect() failed (61: Connection refused) while connecting to upstream, client: 127.0.0.1, server: , request: "GET /api/orders HTTP/1.1", upstream: "http://127.0.0.1:28503/api/orders", host: "127.0.0.1:28502"
2026/11/27 09:47:09 [error] 36998#0: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: , request: "GET /api/session?bytes=6000 HTTP/1.1", upstream: "http://127.0.0.1:28503/api/session?bytes=6000", host: "127.0.0.1:28502"
2026/11/27 09:47:13 [error] 36998#0: *9 upstream prematurely closed connection while reading response header from upstream, client: 127.0.0.1, server: , request: "GET /api/report HTTP/1.1", upstream: "http://127.0.0.1:28503/api/report", host: "127.0.0.1:28502"
2026/11/27 09:47:14 [error] 36998#0: *11 kevent() reported that connect() failed (61: Connection refused) while connecting to upstream, client: 127.0.0.1, server: , request: "GET /api/orders HTTP/1.1", upstream: "http://127.0.0.1:28503/api/orders", host: "127.0.0.1:28502"
```

### 응답한 업스트림을 로그로 남기기

이 필드를 `http` 블록의 `log_format`에 넣고 `nginx -s reload`를 실행하세요. nginx가 502를 직접 만들면 `upstream_status`는 `502`예요. `upstream_response_time`은 nginx가 기다린 시간이에요. 연결이 거부됐을 때는 0.000초, 앱이 요청 도중에 멈췄을 때는 1.007초였어요.

```bash
log_format upstream '$remote_addr "$request" $status $body_bytes_sent '
                    'upstream_addr=$upstream_addr upstream_status=$upstream_status '
                    'upstream_response_time=$upstream_response_time '
                    'traceparent=$http_traceparent';
access_log /var/log/nginx/upstream.log upstream;
```

출력

```text
127.0.0.1 "GET /api/orders HTTP/1.1" 502 157 upstream_addr=127.0.0.1:28503 upstream_status=502 upstream_response_time=0.000 traceparent=-
127.0.0.1 "GET /api/session?bytes=6000 HTTP/1.1" 502 157 upstream_addr=127.0.0.1:28503 upstream_status=502 upstream_response_time=0.003 traceparent=00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
127.0.0.1 "GET /api/report HTTP/1.1" 502 157 upstream_addr=127.0.0.1:28503 upstream_status=502 upstream_response_time=1.007 traceparent=00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
```

### no live upstreams 찾기

`upstream` 블록에 서버 2대를 넣었어요. 1대를 멈추자 클라이언트는 다른 서버에서 `200`을 받았지만, 오류 로그에는 `connect() failed` 줄이 남았어요. 2대를 모두 멈추자 nginx는 `no live upstreams`를 쓰고 다시 시도하지 않은 채 502를 보냈어요.

출력

```text
2026/11/27 09:46:39 [error] 33103#0: *63 kevent() reported that connect() failed (61: Connection refused) while connecting to upstream, client: 127.0.0.1, server: , request: "GET /pool/orders HTTP/1.1", upstream: "http://127.0.0.1:28503/api/orders", host: "127.0.0.1:28502"
2026/11/27 09:46:39 [error] 33103#0: *63 no live upstreams while connecting to upstream, client: 127.0.0.1, server: , request: "GET /pool/orders HTTP/1.1", …
2026/11/27 09:46:39 [error] 33103#0: *65 no live upstreams while connecting to upstream, client: 127.0.0.1, server: , request: "GET /pool/orders HTTP/1.1", …
```

## 해결하기

### 앱을 시작하거나 proxy_pass의 포트 고치기

`Connection refused`는 `proxy_pass`의 주소에서 아무것도 수신하지 않는다는 뜻이에요. nginx 호스트에서 그 주소로 요청을 보내 보세요. curl도 연결하지 못하면 앱을 시작하거나 포트를 고치세요. 앱이 스스로 멈췄다면 다시 시작하기 전에 이유를 찾으세요.

```bash
curl -sS -i http://127.0.0.1:28503/api/orders
```

출력

```text
curl: (7) Failed to connect to 127.0.0.1 port 28503 after 0 ms: Couldn't connect to server
```

### 앱이 연결을 닫은 이유 찾기

`prematurely closed connection while reading response header`는 앱이 상태 줄을 보내기 전에 연결을 닫았다는 뜻이에요. 저희는 5초짜리 요청을 처리하는 동안 `kill -9`로 앱을 멈췄어요. nginx는 1.007초 뒤에 502를 보냈고, 앱은 아무 줄도 쓰지 않았으며, 다음 요청은 `Connection refused`를 받았어요. 프로세스 관리자와 커널 로그에서 멈춘 프로세스를 찾으세요. 예를 들어 메모리 부족으로 강제 종료된 경우예요.

### 큰 헤더에는 proxy_buffer_size 늘리기

저희 앱은 6,165바이트짜리 응답 헤더를 보냈고, `proxy_buffer_size`는 `4k`였어요. `proxy_buffers`도 함께 늘리세요. `proxy_buffer_size 16k`만 바꾸자 `nginx -t`가 `"proxy_busy_buffers_size" must be less than the size of all "proxy_buffers" minus one buffer`로 실패했어요. 둘 다 `16k`로 바꾸자 같은 요청이 `200`을 받았어요. 기본값은 메모리 1페이지로, Linux 컨테이너에서는 4k, Mac에서는 16k였고 Mac에서는 같은 헤더가 통과했어요.

```bash
location /fix/ {
    proxy_pass http://127.0.0.1:28503/api/;
    proxy_buffer_size 16k;
    proxy_buffers 8 16k;
}
```

출력

```text
127.0.0.1 "GET /fix/session?bytes=6000 HTTP/1.1" 200 11 upstream_addr=127.0.0.1:28503 upstream_status=200 upstream_response_time=0.001 traceparent=-
```

### 응답 헤더 줄이기

저희 테스트에서는 값이 6,000바이트인 쿠키 1개가 헤더 대부분을 차지했어요. 세션 데이터는 서버에 두고 쿠키에는 ID만 보내세요. 클라이언트가 쓰지 않는 헤더도 없애세요.

### 잘린 200과 502 구분하기

`prematurely closed connection while reading upstream`은 응답 헤더 다음에 생겨요. nginx는 이미 클라이언트에 `200`을 보냈기 때문에 연결을 닫을 수밖에 없었어요. 저희 앱은 CSV 내보내기 도중에 예외를 던졌고, curl은 9,780바이트에서 멈췄어요. logbrew-fastapi는 그 예외를 이슈로 보냈어요.

```bash
curl -sS -o /dev/null -w '%{http_code} %{size_download}\n' http://127.0.0.1:28502/api/export
```

출력

```text
curl: (18) transfer closed with outstanding read data remaining
200 9780
```

### 앱이 본 것을 LogBrew에서 찾기

LogBrew에는 nginx 연동이 없어서 502 페이지도, 오류 로그 줄도 받지 않아요. 앱의 SDK는 앱이 본 것을 보내요. 이 명령은 저희 내보내기처럼 앱에서 실패한 요청을 보여 줘요. 헤더가 너무 크면 위의 로그 형식처럼 `traceparent`를 로그로 남기세요. 그러면 502 줄과 앱의 스팬이 같은 트레이스 ID를 가져요. `logbrew read trace`로 열어 보세요.

```bash
logbrew traces --project "<project_id>" --service orders-api --status error --since 1h
```

## 테스트에서 확인한 내용

macOS 27.2의 `127.0.0.1:28502`에서 nginx 1.31.8을 Python 3.13.5와 uvicorn 0.54.0 위의 FastAPI 앱 앞에 두고 실행했어요. logbrew-fastapi 0.1.14가 모든 요청을 기록했고, curl 8.7.1이 모든 요청을 보냈어요. `proxy_buffer_size 4k`와 `proxy_buffers 8 4k`로 설정했어요. 메모리 페이지가 4k인 Linux의 기본값이에요.

모든 502의 본문은 같은 157바이트였어요. 원인을 알려 준 것은 오류 로그 줄뿐이었어요. 본문 도중의 예외는 502가 되지 않았어요. 클라이언트는 `200`과 더 적은 데이터를 받았어요.

|  | `$status` | `$body_bytes_sent` | `$upstream_status` | `$upstream_response_time` |
| --- | --- | --- | --- | --- |
| 앱이 실행 중이 아님 | `502` | `157` | `502` | 0초 |
| 앱이 요청 도중에 멈춤 | `502` | `157` | `502` | 1.007초 |
| 6,165바이트 헤더, `proxy_buffer_size 4k` | `502` | `157` | `502` | 0.003초 |
| 본문 도중의 예외 | `200` | `11346` | `200` | 0.024초 |
| 같은 헤더, `proxy_buffer_size 16k` | `200` | `11` | `200` | 0.001초 |
| 서버 2대, 둘 다 멈춤 | `502` | `157` | `502` | 0초 |

## nginx가 502를 보내는 이유

RFC 9110 15.6.3절에 따르면 502 Bad Gateway는 게이트웨이나 프록시로 동작하는 서버가 뒤에 있는 서버에서 잘못된 응답을 받았을 때 보내요. nginx는 연결이 거부됐을 때처럼 응답이 아예 없을 때도 502를 보내요.

nginx의 `ngx_http_proxy_module` 문서에 따르면 `proxy_buffer_size`는 응답의 첫 부분인 응답 헤더를 담아요. 기본값은 메모리 1페이지이고, 문서에서는 플랫폼에 따라 4k나 8k라고 해요. `proxy_buffers`는 응답의 나머지를 담아요.

nginx는 클라이언트에 응답 헤더를 보내기 전에만 502를 보낼 수 있어요. 그 뒤에는 연결을 닫는 것밖에 할 수 없어요. 잘린 `200`이 그 예예요.

1. nginx가 업스트림에 연결
2. nginx가 응답 헤더를 `proxy_buffer_size`에 읽음
3. nginx가 응답을 클라이언트에 보냄

## LogBrew가 기록하는 내용

logbrew-fastapi 0.1.14는 앱이 본 것을 보내요. 6,165바이트 헤더에서는 앱이 `status_code` `200`인 스팬을 보냈고, 클라이언트는 502를 받았어요. 내보내기에서는 `RuntimeError`를 스택 프레임과 함께 이슈로 보냈고, 스팬은 `error`였어요. SDK를 로컬 엔드포인트로 보내게 하고 페이로드를 그대로 저장했어요.

연결이 거부됐을 때는 요청이 앱에 닿지 않았어요. 요청 도중에 멈춘 앱에 대해 SDK는 아무것도 보내지 않았어요. 이런 502는 nginx 로그에만 남아요. HTTP 499 가이드처럼 nginx 줄을 OTLP 로그로 보내세요.

- `orders-api`
  - 스팬: `GET /api/session`
  - `traceId`: `0af7651916cd43dd8448eb211c80319c`
  - `status`: `ok`
  - `status_code`: `200`
- `orders-api`
  - 이슈: `GET /api/export failed`
  - `exception`: `RuntimeError`
  - 스택 프레임: `app.py:30 rows`

## 자주 묻는 질문

### nginx의 502 Bad Gateway는 무슨 뜻인가요?

nginx가 뒤에 있는 서버에서 유효한 응답을 받지 못해서 자체 502 페이지를 보냈다는 뜻이에요. 오류 로그 줄이 이유를 알려 줘요. 연결 없음, 닫힌 연결, 버퍼에 비해 너무 큰 헤더 중 하나예요.

### 502 Bad Gateway는 무엇인가요?

뒤에 있는 서버가 유효한 응답을 주지 않을 때 게이트웨이나 프록시가 보내는 HTTP 상태예요 (RFC 9110, 15.6.3절). 문제는 브라우저가 아니라 프록시와 앱 사이에 있어요.

### nginx의 502 Bad Gateway는 어떻게 해결하나요?

nginx 오류 로그에서 그 요청의 `[error]` 줄을 찾으세요. `Connection refused`면 앱을 시작하거나 포트를 고치세요. `prematurely closed connection`이면 앱이 멈춘 이유를 찾으세요. `too big header`면 `proxy_buffer_size`와 `proxy_buffers`를 늘리세요.

### nginx가 upstream sent too big header라고 하는 이유는 무엇인가요?

앱의 응답 헤더가 `proxy_buffer_size`보다 크기 때문이에요. 저희 헤더는 6,165바이트였고 설정은 `4k`였어요. `proxy_buffer_size`와 `proxy_buffers`를 함께 늘리거나 쿠키를 줄이세요.

### 502와 504의 차이는 무엇인가요?

502는 앱이 연결을 거부했거나, 연결을 닫았거나, nginx가 쓸 수 없는 응답을 보낸 경우예요. 504는 앱이 너무 느려서 nginx가 타임아웃 뒤에 기다리기를 멈춘 경우예요. HTTP 504 가이드에서 각 타임아웃을 보여 줘요.

### nginx가 502를 보낸 것을 앱이 알까요?

저희 테스트에서는 몰랐어요. 헤더가 너무 컸을 때 앱의 LogBrew 스팬은 `status_code` `200`으로 `ok`였어요. 연결이 거부됐을 때는 요청이 앱에 닿지 않았어요.

## 502마다 뒤에서 앱이 한 일 보기

nginx 뒤의 앱에 LogBrew SDK를 넣으면 예외와 각 요청의 트레이스를 대시보드, CLI, AI 에이전트에서 찾을 수 있어요. 넉넉한 무료 요금제로 시작하세요. 카드 등록은 필요 없어요.

[무료로 시작](https://logbrew.co/ko)

## 출처

- [RFC 9110, HTTP Semantics, 15.6.3 502 Bad Gateway](https://www.rfc-editor.org/rfc/rfc9110#section-15.6.3)
- [nginx docs, ngx_http_proxy_module, proxy_pass](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass)
- [nginx docs, ngx_http_proxy_module, proxy_buffer_size](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffer_size)
- [nginx docs, ngx_http_proxy_module, proxy_buffers](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffers)
- [nginx docs, ngx_http_upstream_module, max_fails](https://nginx.org/en/docs/http/ngx_http_upstream_module.html#max_fails)
- [LogBrewCo/sdk, logbrew-fastapi](https://github.com/LogBrewCo/sdk/blob/main/python/logbrew_fastapi/README.md)

## 오류 해결

- [메시지와 파일, 줄을 숨기는 스크립트 오류 Script error 해결하기](https://logbrew.co/ko/errors/script-error)
- [TypeError Failed to fetch 오류를 고치고 원인 3가지를 구분하는 방법](https://logbrew.co/ko/errors/failed-to-fetch)
- [Kotlin과 Android의 java.lang.NullPointerException을 메시지로 해결하기](https://logbrew.co/ko/errors/nullpointerexception)
- [Minified React error #418과 #185를 전체 메시지와 내 코드 줄로 해결하기](https://logbrew.co/ko/errors/minified-react-error)
- [Cannot use import statement outside a module을 브라우저와 Node.js에서 해결하기](https://logbrew.co/ko/errors/cannot-use-import-statement-outside-a-module)
- [AxiosError Network Error 해결하고 3가지 원인 중 어느 것인지 찾기](https://logbrew.co/ko/errors/axios-network-error)
- [HTTP 499 오류를 해결하고 누가 먼저 기다리기를 멈췄는지 찾기](https://logbrew.co/ko/errors/http-499)
- [413 Request Entity Too Large를 해결하고 어느 계층이 요청 본문을 거부했는지 찾기](https://logbrew.co/ko/errors/http-413)
- [PHP 오류를 모두 표시하고 방문자에게 안 보이는 오류까지 잡기](https://logbrew.co/ko/errors/php)
- [nginx 504 Gateway Time-out을 해결하고 어떤 타임아웃이 끝났는지 찾기](https://logbrew.co/ko/errors/http-504)
- [직접 재현한 JavaScript errors와 각각의 해결법](https://logbrew.co/ko/errors)
