全部產品
Search
文件中心

Container Service for Kubernetes:Nginx Ingress營運相關知識點

更新時間:Dec 30, 2025

本文介紹關於Nginx基礎知識點,Nginx Ingress Controller實現原理,以及相關營運能力。

Nginx基礎知識點

在Nginx中,可以採用指令來配置其轉送 Proxy功能邏輯。這些指令通常在/etc/nginx/nginx.conf設定檔中指定,或者在通過主設定檔include語句引入的其它設定檔中進行指定。其中Nginx設定檔主要由四部分:Main(全域設定)、Server(主機配置)、Upstream(負載平衡伺服器設定)和Location(URL匹配特定位置設定)組成。

image

Nginx設定檔結構。

  1. Main塊:配置影響Nginx全域的指令。一般有運行Nginx伺服器的使用者組、Nginx進程PID存放路徑、日誌存放路徑、設定檔引入、允許產生Worker Process數等。

    # configuration file /etc/nginx/nginx.conf:
    # Configuration checksum: 15621323910982901520
    # setup custom paths that do not require root access
    pid /tmp/nginx/nginx.pid;
    daemon off;
    worker_processes 31;
    worker_cpu_affinity auto;
    worker_rlimit_nofile 1047552;
    worker_shutdown_timeout 240s ;
    access_log /var/log/nginx/access.log upstreaminfo  if=$loggable;
    error_log  /var/log/nginx/error.log notice;
  2. Events塊:配置影響Nginx伺服器或與發起網路請求的終端使用者的網路連接,包括每個進程的最大串連數、選取哪種事件驅動模型處理串連請求等。

    events {
        multi_accept        on;
        worker_connections  65536;
        use                 epoll;
    }
  3. HTTP塊:可以嵌套多個Server(每個server塊配置了一個虛擬機器主機或伺服器)、代理、緩衝、記錄定義等絕大多數功能和第三方模組的配置。例如檔案引入、Mime-type定義、日誌自訂、是否使用Sendfile傳輸檔案、連線逾時時間、單串連請求數等。

    http {
        lua_package_path "/etc/nginx/lua/?.lua;;";
        lua_shared_dict balancer_ewma 10M;
        lua_shared_dict balancer_ewma_last_touched_at 10M;
        lua_shared_dict balancer_ewma_locks 1M;
        lua_shared_dict certificate_data 20M;
        lua_shared_dict certificate_servers 5M;
        lua_shared_dict configuration_data 20M;
        lua_shared_dict global_throttle_cache 10M;
        lua_shared_dict ocsp_response_cache 5M;
        init_by_lua_block {
            collectgarbage("collect")
            -- init modules
            local ok, res
            ok, res = pcall(require, "lua_ingress")
            if not ok then
            error("require failed: " .. tostring(res))
            else
            lua_ingress = res
            lua_ingress.set_config({
                use_forwarded_headers = false,
                use_proxy_protocol = false,
                is_ssl_passthrough_enabled = false,
                http_redirect_code = 308,
                listen_ports = { ssl_proxy = "442", https = "443" },
                hsts = true,
                hsts_max_age = 15724800,
                hsts_include_subdomains = true,
                hsts_preload = false,
            ... 
        }
        ...
    }
  4. Server塊:配置虛擬機器主機的相關參數,一個HTTP中可以有多個Server。

        ## start server www.example.com
        server {
            server_name www.example.com ;
            listen 80  ;
            listen [::]:80  ;
            listen 443  ssl http2 ;
            listen [::]:443  ssl http2 ;
            set $proxy_upstream_name "-";
            ssl_certificate_by_lua_block {
                certificate.call()
            }
            location / {
                set $namespace      "xapi";
                set $ingress_name   "xapi-server";
                set $service_name   "xapi-server-rta";
                set $service_port   "80";
                set $location_path  "/";
                set $global_rate_limit_exceeding n;
                rewrite_by_lua_block {
                    lua_ingress.rewrite({
                        force_ssl_redirect = false,
                        ssl_redirect = false,
                        force_no_ssl_redirect = false,
                        preserve_trailing_slash = false,
                        use_port_in_redirects = false,
                        global_throttle = { namespace = "", limit = 0, window_size = 0, key = { }, ignored_cidrs = { } },
                    })
                    balancer.rewrite()
                    plugins.run()
                }
               ...
            }
    }
    ## end server www.example.com
  5. Location塊:配置請求的路由,以及各種頁面的處理情況。

    location / {
      proxy_pass http://upstream_balancer;
    }

下面是一個樣本Nginx.conf檔案,其中包含一些常見的指令塊:

# the number of worker processes to use
worker_processes 4;

# include additional configuration files
include /etc/nginx/conf.d/*.conf;

http {
  # HTTP server settings
  server {
    # listen on port 80
    listen 80;

    # server name
    server_name www.example.com;

    # default location
    location / {
      # root directory
      root /var/www/html;

      # index file
      index index.html;
    }
  }
}

在此樣本中:

  • worker_processes:指令指定Nginx應使用的背景工作處理序數。

  • include:指令用於包含其他設定檔。

  • server:塊包含特定伺服器的設定。

  • location:塊指定預設位置的設定,即伺服器的根URL。

瞭解更多的指令詳細資料,請參見Nginx官方文檔

接下來,我們將概述在Nginx設定檔中最關鍵的幾個部分。

指令塊

HTTP塊

HTTP塊在Nginx設定檔中定義了HTTP伺服器的全域配置參數。這些參數包括啟動並執行背景工作處理序的數量、允許的最大串連數、日誌記錄的細節等。以下是一個Nginx設定檔中HTTP塊的樣本:

http {
    client_max_body_size 128m; 

    access_log /var/log/nginx/access.log; 
    error_log /var/log/nginx/error.log; 

    server {
        ...
    }
}

在該樣本中,HTTP塊設定了背景工作處理序的數量、檔案描述符的最大數量以及用戶端請求允許的最大本文大小。它還指定了訪問和錯誤記錄檔的位置,並且該HTTP塊內嵌了一個server塊,用於指定Web伺服器的配置。

Server塊

在Nginx配置中,Server塊用於定義特定網域名稱或一組網域名稱的流量請求處理規則。允許您為同一伺服器上託管的多個網站或應用程式定義不同的設定和行為。

以下是Nginx設定檔中伺服器塊的樣本:

server {
    listen 80;
    server_name www.example.com;

    location / {
        root /var/www/html/example;
        index index.html index.htm;
    }

    location /app {
        proxy_pass http://localhost:3000;
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

在此樣本中,伺服器只處理連接埠80上www.example.com域的未加密流量。

  • listen指定伺服器應偵聽連接埠80上的傳入串連。

  • server_name指定此伺服器塊應處理的網域名稱。

  • listenserver_name一起使用來定義伺服器應該偵聽和處理流量的域和連接埠。

server_name指令

指定虛擬機器主機網域名稱。

server_name name1 name2 name3

# example:
server_name www.example.com;

網域名稱匹配的四種寫法:

  • 精確匹配:server_name www.example.com

  • 左側通配:server_name *.example.com

  • 右側通配:server_name www.example.*

  • 正則匹配:server_name ~^www\.example\.*$

匹配優先順序:精確匹配 > 左側萬用字元匹配 > 右側萬用字元匹配 > Regex匹配

Location塊

在Nginx中,Location塊是用來定義伺服器對於特定URL路徑或URL模式的請求處理規則。允許您根據網站或應用程式的不同部分定義不同的行為,如為特定目錄提供靜態檔案,或將請求代理到另一台伺服器。

以下是Nginx設定檔中位置塊的樣本:

server {
    ...

    location / {
        root /var/www/html/example;
        index index.html index.htm;
    }

    location /app {
        proxy_pass http://localhost:3000;
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

在此例子中:

  • / 的位置塊指定應通過提供/var/www/html/example目錄中的檔案來處理對網站根URL的請求。

  • /app的位置塊指定對/appURL的請求應代理到連接埠3000上的localhost

  • /50x.html的位置塊指定伺服器應如何通過提供特定檔案來處理伺服器錯誤。

在Nginx中,當存在多個location塊時,請求的處理將根據location的匹配規則和優先順序被第一個相匹配的location塊捕獲並處理。

文法拼接:

  • location [ = | ~ | ~* | ^~ ] uri { ... }

  • location @name { ... }

文法規則

描述

location = /uri

= 開頭表示精確匹配,只有完全符合上才會生效。

location ^~ /uri

^~ 開頭對URL路徑進行首碼匹配,並且在Regex之前,匹配到即停止搜尋。

location ~ Regex

~ 開頭表示區分大小寫正則匹配。

location ~* Regex

~* 開頭表示不區分大小寫正則匹配。

location !~ Regex

!~ 區分大小寫不匹配的正則。

location !~*Regex

!~* 不區分大小寫不匹配的正則。

location /uri

不帶任何修飾符,也表示首碼匹配,但在正則匹配之後。

location /

通用匹配,任何未匹配到其他location的請求都會匹配到,相當於Switch中的Default。

location @名稱

Nginx內部跳轉。

匹配優先順序: = > ^~ > ~ > ~* > 不帶任何字元

參考樣本如下:

# 通用的預設匹配,所有未匹配location的都會匹配此種匹配;
# 正則和最長字串會優先匹配
location / {

}


# 精確匹配 / ,主機名稱後面不能帶任何字串
location = / {

}

# 首碼匹配
location ^~ /xx/ {
     # 匹配任何以 /xx/ 開頭的請求並且停止搜尋。
}
# 不帶正則描述的首碼匹配;
location  /uri {
}

# 正則匹配
location ~*.(gif|jpg|jpeg)$ {
     # 匹配任何以 gif、jpg 或 jpeg 結尾的請求。
}

Nginx Ingress會將Host下多個Ingress path按長度降序進行排序。瞭解更多詳情,請參見Ingress路徑匹配Nginx的伺服器和位置塊選擇演算法

指令繼承和覆蓋

在Nginx配置中,指令遵循從外到內的繼承機制,位於內部的子上下文會從其外層的父上下文中繼承配置指令。例如,在http{}上下文中設定的指令會被所有嵌套於其下的server{}location{}上下文所繼承,同樣,server{}上下文中的指令會被它所包含的所有location{}上下文繼承。需要注意的是,當同一個指令在父子上下文中均被定義時,子上下文中的配置將覆蓋父上下文中的相應設定,而不是疊加。

參考樣本如下:

http {
    add_header X-HTTP-LEVEL-HEADER 1;
    add_header X-ANOTHER-HTTP-LEVEL-HEADER 1;

    server {
        listen 8080;
        location / {
            return 200 "OK";
        } 
    }

    server {
        listen 8081;
        add_header X-SERVER-LEVEL-HEADER 1;

        location / {
            return 200 "OK";
        }

        location /test {
            add_header X-LOCATION-LEVEL-HEADER 1;
            return 200 "OK";
        }

        location /correct {
            add_header X-HTTP-LEVEL-HEADER 1;
            add_header X-ANOTHER-HTTP-LEVEL-HEADER 1;

            add_header X-SERVER-LEVEL-HEADER 1;
            add_header X-LOCATION-LEVEL-HEADER 1;
            return 200 "OK";
        } 
    }
}

Nginx的反向 Proxy配置

proxy_pass指令

Nginx反向 Proxy配置使得Nginx作為Proxy 伺服器運行,它監聽用戶端請求並將其轉寄至一個或多個後端伺服器。這使得Nginx能夠接收請求並將其路由至合適的後端服務進行處理。配置Nginx反向 Proxy,可以在Nginx配置中的位置塊中使用proxy_pass指令。

以下是配置Nginx反向 Proxy的樣本:

server {
    listen 80;
    server_name www.example.com;

    location / {
        proxy_pass http://localhost:3000;
    }
}

在此樣本中,/的位置塊指定對www.example.com域的所有請求都應代理到連接埠3000上的本地主機。這意味著Nginx將把接收到的請求轉寄到在localhost:3000上啟動並執行伺服器。

proxy_set_header指令

還可以使用proxy_set_header指令指定要添加到代理請求中的其他標題。

樣本如下:

server {
    listen 80;
    server_name www.example.com;

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://localhost:3000;
    }
}

在此樣本中,proxy_set_header指令指定應將HostX-Real-IP標題添加到代理請求中,並將傳入請求的主機名稱和發出請求的用戶端的IP地址分別設定為對應的值。這對於將傳入請求的資訊傳遞到上遊伺服器非常有用。

Nginx常用指令

常用指令

描述

proxy_pass

指定將請求轉寄到哪個後端伺服器,可以是IP地址加連接埠號碼,也可以是網域名稱。

proxy_set_header

設定轉寄給後端伺服器的要求標頭資訊,如Host、X-Real-IP等。

proxy_read_timeout

設定讀取後端伺服器響應的逾時時間。

proxy_buffer_size和proxy_buffers

設定緩衝後端伺服器響應的緩衝區大小。

Nginx常用命令

常用命令

描述

nginx -s reload

向主進程發送訊號,重新載入設定檔,進行熱重啟。

nginx -s reopen

重啟Nginx。

nginx -s stop

快速關閉。

nginx -s quit

等待背景工作處理序處理完成後關閉。

nginx -T

查看當前Nginx最終的配置。

nginx -t

檢查配置是否有問題。

Nginx Ingress Controller

實現原理

Nginx Ingress Controller是一個集控制平面和資料平面於一體的實現方案。每個Pod下有一個Controller進程,同時也包含Nginx相關進程。

image

Nginx Ingress資料面相關核心模組

第三方模組:

瞭解更多模組詳情,請參見Nginx官方文檔

配置同步原理

瞭解配置同步的工作原理之後,我們便能夠掌握如何減少配置Reload的頻率,以及在何種情況下需要執行配置Reload。

image

Nginx Ingress Controller通過Watch Ingress、Service、Pod、Endpoint相關資源,將配置更新到nginx.conf檔案或lua table中。Lua部分主要包含了Upstream端點、灰階發布和認證部分,而如果修改了需要寫入 nginx.conf 檔案的其他Nginx原生參數,則仍會觸發Reload。詳細資料,請參見Nginx Ingress社區文檔部分《When a reload is required》。

Nginx Ingress控制面配置

啟動參數說明

瞭解更多啟動參數詳情,請參見Ingress控制器命令列參數

查看Nginx Ingress對應的Deployment或者Pod Spec可以看到Nginx Ingress對應的Container的啟動參數,大致如下:

containers:
  - args:
    - /nginx-ingress-controller
    - --election-id=ingress-controller-leader-nginx
    - --ingress-class=nginx
    - --watch-ingress-without-class
    - --controller-class=k8s.io/ingress-nginx
    - --configmap=$(POD_NAMESPACE)/nginx-configuration
    - --tcp-services-configmap=$(POD_NAMESPACE)/tcp-services
    - --udp-services-configmap=$(POD_NAMESPACE)/udp-services
    - --annotations-prefix=nginx.ingress.kubernetes.io
    - --publish-service=$(POD_NAMESPACE)/nginx-ingress-lb
    - --enable-annotation-validation
    - --validating-webhook=:8443
    - --validating-webhook-certificate=/usr/local/certificates/cert
    - --validating-webhook-key=/usr/local/certificates/key
    - --v=2

其中-v指定記錄層級:

  • --v=2使用Diff顯示有關Nginx中配置更改的詳細資料。

  • --v=3顯示有關服務、入口規則、端點更改的詳細資料,並以JSON格式轉儲Nginx配置。

  • --v=5Debug偵錯模式。

負載平衡演算法

Ingress Nginx允許設定全域預設的負載平衡演算法,主要提供了Round_robin和Ewma兩種選項,預設使用Round_robin。Round_robin演算法迴圈遍曆後端工作負載,使請求均勻分配,但如果後端效能差異較大,可能會出現負載不均衡。相反,Ewma演算法可以將請求發送到加權平均負載最低的工作負載上,加權負載指數會隨著請求的到來而逐漸層化,使得負載平衡更加均衡。

要使用IP或其他變數的一致雜湊進行Server Load Balancer,請考慮使用nginx.ingress.kubernetes.io/upstream-hash-by注釋。要使用會話Cookie進行Server Load Balancer,請考慮使用nginx.ingress.kubernetes.io/affinity注釋。

相關實現:

相關逾時配置

全域逾時配置

可通過以下配置項進行Ingress Nginx的全域逾時配置:

配置項

描述

取實值型別

預設值

nginx.ingress.kubernetes.io/proxy-connect-timeout

設定與Proxy 伺服器建立串連的逾時時間,單位為秒(s)。

int

nginx.ingress.kubernetes.io/proxy-connect-timeout: "5"

建議不超過75

nginx.ingress.kubernetes.io/proxy-read-timeout

設定從Proxy 伺服器讀取響應的逾時。該逾時僅在兩個連續的讀取操作之間設定,而不是為整個響應的傳輸設定,單位為秒(s)。

int

nginx.ingress.kubernetes.io/proxy-read-timeout: "60"

nginx.ingress.kubernetes.io/proxy-send-timeout

設定向Proxy 伺服器傳輸請求的逾時。該逾時只在兩個連續的寫操作之間設定,而不是為整個請求的傳輸設定,單位為秒(s)。

int

nginx.ingress.kubernetes.io/proxy-send-timeout: "60"

nginx.ingress.kubernetes.io/proxy-stream-next-upstream-timeout

限制允許將串連傳遞到下一個伺服器的時間,設定為0s則關閉此限制。

string

nginx.ingress.kubernetes.io/proxy-stream-next-upstream-timeout: "600s"

nginx.ingress.kubernetes.io/proxy-stream-timeout

設定用戶端或Proxy 伺服器串連上兩個連續的讀或寫操作之間的逾時時間。如果在這個時間內沒有資料轉送,串連就會關閉。

string

nginx.ingress.kubernetes.io/proxy-stream-timeout: "600s"

nginx.ingress.kubernetes.io/upstream-keepalive-timeout

設定一個逾時時間,在這個時間內,與上遊伺服器的空閑串連將保持開放,單位為秒(s)。

int

nginx.ingress.kubernetes.io/upstream-keepalive-timeout: "900"

nginx.ingress.kubernetes.io/worker-shutdown-timeout

設定優雅停機的逾時時間。

string

nginx.ingress.kubernetes.io/worker-shutdown-timeout: "240s"

nginx.ingress.kubernetes.io/proxy-protocol-header-timeout

設定接收代理協議標頭檔的逾時值。預設的5秒可以防止TLS直通處理常式無限期地等待一個中斷的串連。

string

nginx.ingress.kubernetes.io/proxy-protocol-header-timeout: "5s"

nginx.ingress.kubernetes.io/ssl-session-timeout

設定 SSL 會話緩衝中的會話參數的有效時間。會話到期時間是相對於建立時間而言的。每個會話緩衝會佔用大約0.25MB的空間。

string

nginx.ingress.kubernetes.io/ssl-session-timeout: "10m"

nginx.ingress.kubernetes.io/client-body-timeout

定義讀取用戶端請求本文的逾時,單位為秒(s)。

int

nginx.ingress.kubernetes.io/client-body-timeout: "60"

nginx.ingress.kubernetes.io/client-header-timeout

定義讀取用戶端要求標頭的逾時,單位為秒(s)。

int

nginx.ingress.kubernetes.io/client-header-timeout: "60"

特定的資源自訂逾時配置

以下是特定的資源自訂逾時配置,以及相關的參數配置。

配置項

描述

nginx.ingress.kubernetes.io/proxy-connect-timeout

設定代理連線逾時時間。

nginx.ingress.kubernetes.io/proxy-send-timeout

設定代理髮送逾時時間。

nginx.ingress.kubernetes.io/proxy-read-timeout

設定代理讀取逾時時間。

nginx.ingress.kubernetes.io/proxy-next-upstream

配置重試策略或者重試條件,可以使用多個組合用空格分隔,例如設定為http_500http_502、支援下列策略:

  • error:串連失敗,直接返回。

  • timeout:連線逾時,直接返回。

  • invalid_response:無效返回狀態代碼,直接返回。

  • http_xxx:xxx可以替換為狀態代碼,例如設定為http_500的含義是上遊返回500時選擇下一個工作負載。支援的狀態代碼為:500、502、503、504、403、404、429。

  • off:關閉重試機制,不論任何錯誤都直接返回。

nginx.ingress.kubernetes.io/proxy-next-upstream-tries

如果滿足重試條件,則可用的重試次數。

nginx.ingress.kubernetes.io/proxy-request-buffering

是否啟用請求緩衝功能。

  • on啟用請求緩衝。如果啟用了請求緩衝功能,則會在接收到完整的請求資料之後才將其轉寄到後端工作負載,否則可能會在接收到部分請求資料時就開始轉寄請求。HTTP/1.1 Chunked編碼的請求不受此參數限制,始終會進行緩衝。

  • off則禁用請求緩衝。如果禁用,當Nginx向後端轉寄請求的過程中發生錯誤時,將不會嘗試將該請求轉寄給下一個後端伺服器

通用全域配置ConfigMap

瞭解更多詳情資訊,請參見Nginx-configuration_configmap

其他Annotation

瞭解更多詳情資訊,請參見Nginx-configuration_annotations

自訂配置snippet

  • nginx.ingress.kubernetes.io/configuration-snippet:對應配置會生效到Location塊下。

  • nginx.ingress.kubernetes.io/server-snippet:對應配置會生效到Server塊下。

  • nginx.ingress.kubernetes.io/stream-snippet:對應配置會生效到Stream塊下。

Nginx Ingress資料面配置

Nginx Ingress的資料平面是通過結合Nginx和ngx_lua模組(即OpenResty)來實現的。Nginx採用多模組化設計,將HTTP請求處理切分成多個階段,允許多個模組協同工作,其中每個模組負責處理一個獨立且簡單的功能。這使得處理更高效、更可靠,並提高了系統的可擴充性。

OpenResty依託NGINX的處理階段,在Rewrite/Access階段、Content階段和Log階段注入了自訂的Handler。加上系統啟動的初始階段,即Master階段,總計OpenResty提供了11個階段,這些階段賦予了 Lua指令碼在HTTP請求處理過程中介入的能力。接下來是OpenResty主要可用階段的圖示描述:

image

HTTP塊

http {
    lua_package_path "/etc/nginx/lua/?.lua;;";
    lua_shared_dict balancer_ewma 10M;
    lua_shared_dict balancer_ewma_last_touched_at 10M;
    lua_shared_dict balancer_ewma_locks 1M;
    lua_shared_dict certificate_data 20M;
    lua_shared_dict certificate_servers 5M;
    lua_shared_dict configuration_data 20M;
    lua_shared_dict global_throttle_cache 10M;
    lua_shared_dict ocsp_response_cache 5M;
    ...
}

init_by_lua_block

init_by_lua_block {
        collectgarbage("collect")
        -- init modules
        local ok, res
        ok, res = pcall(require, "lua_ingress")
        if not ok then
        error("require failed: " .. tostring(res))
        else
        lua_ingress = res
        lua_ingress.set_config({
            use_forwarded_headers = false,
            use_proxy_protocol = false,
            is_ssl_passthrough_enabled = false,
            http_redirect_code = 308,
            listen_ports = { ssl_proxy = "442", https = "443" },
            hsts = true,
            hsts_max_age = 15724800,
            hsts_include_subdomains = true,
            hsts_preload = false,
            global_throttle = {
                memcached = {
                    host = "", port = 11211, connect_timeout = 50, max_idle_timeout = 10000, pool_size = 50,
                },
                status_code = 429,
            }
        })
        end
        ok, res = pcall(require, "configuration")
        if not ok then
        error("require failed: " .. tostring(res))
        else
        configuration = res
        configuration.prohibited_localhost_port = '10246'
        end
        ok, res = pcall(require, "balancer")
        if not ok then
        error("require failed: " .. tostring(res))
        else
        balancer = res
        end
        ok, res = pcall(require, "monitor")
        if not ok then
        error("require failed: " .. tostring(res))
        else
        monitor = res
        end
        ok, res = pcall(require, "certificate")
        if not ok then
        error("require failed: " .. tostring(res))
        else
        certificate = res
        certificate.is_ocsp_stapling_enabled = false
        end
        ok, res = pcall(require, "plugins")
        if not ok then
        error("require failed: " .. tostring(res))
        else
        plugins = res
        end
        ...
  }

初始化載入了Lua相關模組:

  • configuration

  • balancer

  • monitor

  • certificate

  • plugins

init_worker_by_lua_block

    init_worker_by_lua_block {
        lua_ingress.init_worker()
        balancer.init_worker()
        monitor.init_worker(10000)
        plugins.run()
    }

upstream和balancer_by_lua_block

    upstream upstream_balancer {
        ### Attention!!!
        #
        # We no longer create "upstream" section for every backend.
        # Backends are handled dynamically using Lua. If you would like to debug
        # and see what backends ingress-nginx has in its memory you can
        # install our kubectl plugin https://kubernetes.github.io/ingress-nginx/kubectl-plugin.
        # Once you have the plugin you can use "kubectl ingress-nginx backends" command to
        # inspect current backends.
        #
        ###
        server 0.0.0.1; # placeholder
        balancer_by_lua_block {
            balancer.balance()
        }
        keepalive 8000;
        keepalive_time 1h;
        keepalive_timeout  60s;
        keepalive_requests 10000;
    }

Stream塊

stream {
    lua_package_path "/etc/nginx/lua/?.lua;/etc/nginx/lua/vendor/?.lua;;";
    lua_shared_dict tcp_udp_configuration_data 5M;
    resolver 192.168.0.10 valid=30s;
    init_by_lua_block {
        collectgarbage("collect")
        -- init modules
        local ok, res
        ok, res = pcall(require, "configuration")
        if not ok then
        error("require failed: " .. tostring(res))
        else
        configuration = res
        end
        ok, res = pcall(require, "tcp_udp_configuration")
        if not ok then
        error("require failed: " .. tostring(res))
        else
        tcp_udp_configuration = res
        tcp_udp_configuration.prohibited_localhost_port = '10246'
        end
        ok, res = pcall(require, "tcp_udp_balancer")
        if not ok then
        error("require failed: " .. tostring(res))
        else
        tcp_udp_balancer = res
        end
    }

    init_worker_by_lua_block {
        tcp_udp_balancer.init_worker()
    }
    lua_add_variable $proxy_upstream_name;
    log_format log_stream '[$remote_addr] [$time_local] $protocol $status $bytes_sent $bytes_received $session_time';
    access_log off;
    error_log  /var/log/nginx/error.log notice;
    upstream upstream_balancer {
        server 0.0.0.1:1234; # placeholder
        balancer_by_lua_block {
            tcp_udp_balancer.balance()
        }
    }
    server {
        listen 127.0.0.1:10247;
        access_log off;
        content_by_lua_block {
            tcp_udp_configuration.call()
        }
    }
  }

同HTTP類似,init_by_lua_block部分載入了TCP相關的Lua模組並進行了初始化。

日誌相關

    access_log off;
    error_log  /var/log/nginx/error.log notice;
  • 關閉了access_log

  • 錯誤記錄檔層級設定為了notice,還可以設定為debugdebug_coredebug_allocdebug_eventdebug_http等)、infowarnerrorcritalertemerg等值,層級越高,記錄的資訊越少。

執行以下命令,可以通過查看Nginx Ingress Pod日誌是否有相關報錯資訊。

kubectl logs -f <nginx-ingress-pod-name> -n kube-system  |grep -E '^[WE]'

相關文檔

關於Nginx Ingress的配置,請參見社區文檔

關於Nginx Ingress排查方法,請參見常見檢查方法

關於Nginx Ingress進階用法,請參見Nginx Ingress進階配置