{"id":20619746,"url":"https://github.com/twtrubiks/docker-django-nginx-uwsgi-postgres-load-balance-tutorial","last_synced_at":"2026-03-14T16:40:49.492Z","repository":{"id":84518938,"uuid":"111918792","full_name":"twtrubiks/docker-django-nginx-uwsgi-postgres-load-balance-tutorial","owner":"twtrubiks","description":"實戰 Docker + Django + Nginx + uWSGI + Postgres - Load Balance -Tutorial 📝","archived":false,"fork":false,"pushed_at":"2019-11-02T08:05:09.000Z","size":22,"stargazers_count":112,"open_issues_count":2,"forks_count":23,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-08-25T13:35:29.786Z","etag":null,"topics":["django","docker","load-balancer","nginx","postgresql","proxy-server","tutorial","uwsgi"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/twtrubiks.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-11-24T12:59:12.000Z","updated_at":"2025-05-28T17:09:11.000Z","dependencies_parsed_at":"2023-03-02T04:30:28.738Z","dependency_job_id":null,"html_url":"https://github.com/twtrubiks/docker-django-nginx-uwsgi-postgres-load-balance-tutorial","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/twtrubiks/docker-django-nginx-uwsgi-postgres-load-balance-tutorial","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fdocker-django-nginx-uwsgi-postgres-load-balance-tutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fdocker-django-nginx-uwsgi-postgres-load-balance-tutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fdocker-django-nginx-uwsgi-postgres-load-balance-tutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fdocker-django-nginx-uwsgi-postgres-load-balance-tutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/twtrubiks","download_url":"https://codeload.github.com/twtrubiks/docker-django-nginx-uwsgi-postgres-load-balance-tutorial/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fdocker-django-nginx-uwsgi-postgres-load-balance-tutorial/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279013708,"owners_count":26085394,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-13T02:00:06.723Z","response_time":61,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["django","docker","load-balancer","nginx","postgresql","proxy-server","tutorial","uwsgi"],"created_at":"2024-11-16T12:12:24.961Z","updated_at":"2025-10-13T05:45:25.019Z","avatar_url":"https://github.com/twtrubiks.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# docker-django-nginx-uwsgi-postgres-load-balance-tutorial\n\n實戰 Docker + Django + Nginx + uWSGI + Postgres - **Load Balance**  📝\n\n這篇文章主要接續上一篇\n\n[Docker + Django + Nginx + uWSGI + Postgres 基本教學 - 從無到有 ( Docker + Django + Nginx + uWSGI + Postgres Tutorial )](https://github.com/twtrubiks/docker-django-nginx-uswgi-postgres-tutorial)\n\n繼續介紹，這次的重點會放在 Nginx 的 **Load Balance** 上 :blush:\n\n* [Youtube Tutorial PART 1 - 正向代理器  VS 反向代理器 - 簡介](https://youtu.be/R2I8BBXnJJ8)\n* [Youtube Tutorial PART 2 - Docker + Django + Nginx + Load Balance - 概念](https://youtu.be/W4EMOO-THGs)\n* [Youtube Tutorial PART 3 - Docker + Django + Nginx + Load Balance - 實戰](https://youtu.be/ChK8MtQUDf0)\n* [Youtube Tutorial PART 4 - Django + Nginx + Load Balance - Docker scale](https://youtu.be/w83_lV5tORI)\n\n## 簡介\n\n在開始介紹 Nginx 的 Load Balance 之前，我會先帶大家了解一些名詞。\n\n還記得在 [上一篇](https://github.com/twtrubiks/docker-django-nginx-uswgi-postgres-tutorial) 教學中，提到 Nginx 可以設定 反向代理器 嗎？\n\n那時候沒有詳細解釋什麼是 反向代理器 ，這邊我將先帶大家了解\n\n**正向代理器** 以及 **反向代理器** 的差別 :notebook:\n\n### 正向代理器  VS 反向代理器\n\n#### 正向代理器\n\n正向代理器是一個位於使用者端以及目標 Server 之間的 **代理伺服器 ( Proxy Server )**，\n\n透過代理伺服器收發 Request / Respond 資料，\n\n![](https://i.imgur.com/zWIk8QW.png)\n\n如上圖，X 無法直接和 Z 請求資料，但是 Y 可以和 Z 請求資料 ( 於是 X 透過 Y 向 Z 請求資料 )，\n\nY 得到資料後，再將資料回傳給 X，這樣 X 就能順利得到 Z 的資料了 。\n\n通常正向代理器必須額外做一些設定才可以使用。\n\n正向代理器，Client 和 Proxy 可視為同一個 LAN ，對 Server 是隱藏的。\n\n![](https://i.imgur.com/MJ0Pr2q.png)\n\n溫馨小提醒 :heart:\n\n* LAN ( Local Area Network )，又稱 區域網路\n\n* WAN ( Wide Area Network )，又稱 廣域網路\n\n* WLAN ( Wireless LAN )，又稱 無線區域網路\n\n正向代理器是代理使用者端（ Client 端 ），替使用者端（ Client 端 ）收發 Request / Respond，\n\n讓真正的使用者對伺服器端（ Server 端 ）隱藏。\n\n可能你自己也有使用過（ 或正在使用 :grin: ）正向代理器 ，只是你不知道而以，像最常見的就是 **翻牆 ( VPN )** :smirk:\n\n今天主角是阿鬼，阿鬼無法瀏覽 FB，但可以瀏覽 Server A，而阿鬼發現 Server A 可以訪問 FB，\n\n於是阿鬼就透過 Server A 去瀏覽 FB，整個流程是，阿鬼透過 Server A 去瀏覽 FB，Server A 收到\n\n來自阿鬼的 Request 時，去瀏覽 FB，FB 再把 Response 回傳給 Server A，Server A 再把收到的\n\nResponse 回傳給阿鬼，這樣阿鬼就能順利得到 FB 的資料，這就是透過 Proxy ( 正向代理器 )。\n\n#### 反向代理器\n\n反向代理器則相反過來，對於使用者端來說，反向代理器就好像是目標 Server，\n\n使用者端也不需要做額外的設定，\n\n![](https://i.imgur.com/kUBGgKz.png)\n\n如上圖，雖然整個流程還是 X-\u003eY-\u003eZ，但因為不用特別設定，所以使用者端會感覺好像直接是 X-\u003eZ，\n\n反向代理器，Proxy 和 Server 屬於一個 LAN，對 Client 隱藏\n\n![](https://i.imgur.com/j6wnvnt.png)\n\n反向代理器是代理伺服器端（ Server 端 ），替伺服器端（ Server 端 ）收發 Request / Respond，\n\n讓真正的伺服器（ Server 端 ）對使用者隱藏。\n\n本次的主角 **Load Balance** 就是反向代理器的一種應用 :open_mouth:\n\n## 教學\n\n解釋了那麼多，我們要開始實戰 Nginx 的 Load Balance，範例一樣是使用 [上一篇](https://github.com/twtrubiks/docker-django-nginx-uswgi-postgres-tutorial) 做修改，\n\n因為要做 Load Balance，所以增加一台主機（ service ），名稱命名為 [api2](https://github.com/twtrubiks/docker-django-nginx-uwsgi-postgres-load-balance-tutorial/tree/master/api2)，基本上內容\n\n都和 [api](https://github.com/twtrubiks/docker-django-nginx-uwsgi-postgres-load-balance-tutorial/tree/master/api) 差不多，只是修改了一些名稱（ 方便區別而已 ），可參考 [docker-compose.yml](https://github.com/twtrubiks/docker-django-nginx-uwsgi-postgres-load-balance-tutorial/blob/master/docker-compose.yml)。\n\n整體的 Load Balance 的概念可以參考下圖\n\n![](https://i.imgur.com/RxUtPiz.png)\n\n這樣有什麼好處呢 ？\n\n最直接的好處就是，如果一台掛了，整個系統還是不會死，\n\n因為其他的 Server 還是正常工作:relaxed:\n\n再來就是我們的主角 [my_nginx.conf](https://github.com/twtrubiks/docker-django-nginx-uwsgi-postgres-load-balance-tutorial/blob/master/nginx/my_nginx.conf)，其實主要也是修改這邊的設定而已 :laughing:\n\n```config\n# the upstream component nginx needs to connect to\nupstream uwsgi {\n    # server api:8001; # use TCP\n    server unix:/docker_api/app.sock weight=4 ; # for a file socket\n    server unix:/docker_api2/app2.sock  weight=6; # for a file socket\n}\n\n# configuration of the server\nserver {\n    # the port your site will be served on\n    listen    80;\n    # index  index.html;\n    # the domain name it will serve for\n    # substitute your machine's IP address or FQDN\n    server_name  twtrubiks.com www.twtrubiks.com;\n    charset     utf-8;\n\n    client_max_body_size 75M;   # adjust to taste\n\n    # Django media\n    # location /media  {\n    #     alias /docker_api/static/media;  # your Django project's media files - amend as required\n    # }\n\n    location /static {\n        alias /docker_api/static; # your Django project's static files - amend as required\n    }\n\n    location / {\n        uwsgi_pass  uwsgi;\n        include     /etc/nginx/uwsgi_params; # the uwsgi_params file you installed\n    }\n\n}\n```\n\n其實設定並不難，只是在 `upstream` 裡面增加一台 Server 而已，後面的 `weight` 則代表權重，\n\nNginx 預設會使用 round-robin 演算法來實作 Load balance。\n\n### Load balancing methods\n\nNginx 主要的 Load balance 有三種\n\n****round-robin — requests to the application servers are distributed in a round-robin fashion****\n\n使用輪詢的方式，也可以加上 `weight` 權重，讓比較強的 Server 承受比較大的壓力（ `weight` 設定高一點）。\n\n****least-connected — next request is assigned to the server with the least number of active connections****\n\n此種方式，Nginx 會將請求給負載 Loading 較輕的 Server，避免負載（A Server） Loading 已經很大了，\n\n還將請求交給 A Server 處理。\n\n****ip-hash — a hash-function is used to determine what server should be selected for the next request (based on the client's IP address)****\n\n不管是 round-robin 還是 least-connected 的 Load balance ，每個 User 送出的請求都可能會被分到不同的\n\nServer，並不能保證同一個 User 每次的請求都一定會連到同一台 Server，\n因為這個原因，於是有了 ip-hash，\n\n透過這個方法，會使用 ip 的方式將同一個 User 的請求都導到同一台\nServer （除非這台 Server 掛了 :sob: ）\n\n介紹完了 Nginx 主要的三種 Load balance 演算法，至於要使用哪一種，就看你自己的需求了 :grinning:\n\n更多範例以及詳細的說明可參考官網\n\n ( 建議閱讀 ，雖然我有幫大家整理重點出來了 :grinning:  )\n\n[http://nginx.org/en/docs/http/load_balancing.html](http://nginx.org/en/docs/http/load_balancing.html)\n\n## 執行步驟\n\n直接執行 `docker-compose up` 見證奇蹟\n\n細部的圖就不再貼一次了，請參考 [上一篇](https://github.com/twtrubiks/docker-django-nginx-uswgi-postgres-tutorial)\n\n會發現我們多了一台 `api2`\n\n![](https://i.imgur.com/KhROEky.png)\n\n接著開啟另一個 terminal，進入 `api` ( Django + uWSGI ) 的容器，\n\n指令可參考之前的 [docker-tutorial-指令介紹](https://github.com/twtrubiks/docker-tutorial#指令介紹)，\n\n```cmd\ndocker exec -it \u003cContainer ID\u003e bash\n```\n\n執行 migrate\n\n```cmd\npython manage.py makemigrations musics\npython manage.py migrate\n```\n\n![](https://i.imgur.com/nQDwP7e.png)\n\n建立 user\n\n```cmd\npython manage.py createsuperuser\n```\n\n![](https://i.imgur.com/saaDD7R.png)\n\n最後再執行\n\n```cmd\npython manage.py collectstatic\n```\n\n![](https://i.imgur.com/1EKNNOx.png)\n\n將 Django 中的 static files 收集起來，變成 static folder，\n\n我們不需要再進入 `api2` 的 container 執行剛剛的動作，因為我們都是連同一個 db，\n\n到這裡基本上就是完工了:smile:\n\n瀏覽 [http://localhost:8080/api/music/](http://localhost:8080/api/music/) 確認是否正常。\n\n## 執行畫面\n\n瀏覽 [http://localhost:8080/api/music/](http://localhost:8080/api/music/)\n\n![](https://i.imgur.com/jl43jST.png)\n\n![](https://i.imgur.com/Fw6LjbE.png)\n\n那要怎麼確定真的有 Load balance 呢？\n\n可以在頁面上瘋狂點擊 F5，然後我們觀察 terminal，你會發現\n\n![](https://i.imgur.com/7xuFXw5.png)\n\n有時候是 `api`，有時候是 `api2`，還記得前面設定的 `weight` 權重，\n\n`api` 和 `api2` 是 4:6，4:6 是什麼意思呢:question::question:\n\n假如現在有 10 個 Request 進來，4 個 Request 會交給 `api` 這個 Server 處理，\n\n而剩下的 6 個 Request 則會交給 `api2` 這個 Server 處理 :+1:\n\n`weight` 權重可以依照自己的需求設定。\n\n接著再來模擬一台 Server 掛了的時候，如下圖，Server 因為某種原因掛了，\n\n![](https://i.imgur.com/fRa1Q9t.png)\n\n先透過 stop 指令將 `api` container 停止\n\n( 模擬 `api` 這台 Server 掛了 )\n\n```cmd\ndocker stop [OPTIONS] CONTAINER [CONTAINER...]\n```\n\n![](https://i.imgur.com/LkoQeDc.png)\n\n![](https://i.imgur.com/lHmMPUu.png)\n\n然後再繼續瀏覽 [http://localhost:8080/api/music/](http://localhost:8080/api/music/)，你會發現網站正常 work ( 確實沒有掛掉 )，\n\n而且 terminal 現在都只會輸出 `api2`，\n\n![](https://i.imgur.com/RTdzQqX.png)\n\n因為我們已經將 `api` 停止了（模擬機器意外掛了），\n\n有沒有很酷 :satisfied: 這就是最簡單的 Load balance :flushed:\n\n範例是總共有兩台 server ( `api` 以及 `api2` )， 你也可以自己多新增幾台來玩玩看。\n\n## 其他的負載平衡\n\n除了 Nginx 的 Load banlance 之外，假設你的系統更龐大且有規模，\n\n可以考慮使用更專業的負載平衡，像是 [HAProxy](http://www.haproxy.org/) ( High Availability Proxy ) ，\n\n如果要專注在 Load banlance 上，選擇 [HAProxy](http://www.haproxy.org/) 應該會比 Nginx 的\n\nLoad banlance 還來的好。\n\n如果對 HAProxy 有興趣，可參考 [Docker Swarm + HAProxy](https://github.com/twtrubiks/docker-swarm-tutorial#docker-swarm--haproxy) :sunglasses:\n\n## 後記：\n\n這次主要介紹了 Nginx 的 Load Banlance 給大家，建議大家可以動手玩玩看，整體會比較有感覺 :smiley:\n\n這次嘗試參考網路上的圖自己簡單的畫一遍，希望對大家多多少少有幫助:flushed:\n\n如果有在玩像是 AWS 的人，可以知道還有一種東西更狂，就是 異地同步備份，大家有興趣自行研究:sunglasses:\n\n如果有任何講錯的地方，請麻煩大家和我說，我會再修改，感謝各位的閱讀:v:\n\n下一步可以試試看用 Docker scale 的方法來完成( 更好的寫法 )，可參考 [better](https://github.com/twtrubiks/docker-django-nginx-uwsgi-postgres-load-balance-tutorial/tree/better) 分支。\n\n如果意猶未盡，延伸閱讀 :satisfied:\n\n* [Docker Swarm 基本教學 - 從無到有 Docker-Swarm-Beginners-Guide📝](https://github.com/twtrubiks/docker-swarm-tutorial)\n\n## 執行環境\n\n* Mac\n* Python 3.6.2\n* windows 10\n\n## Reference\n\n* [https://docs.docker.com/](https://docs.docker.com/)\n* [nginx-load_balancing](http://nginx.org/en/docs/http/load_balancing.html)\n\n## Donation\n\n文章都是我自己研究內化後原創，如果有幫助到您，也想鼓勵我的話，歡迎請我喝一杯咖啡:laughing:\n\n![alt tag](https://i.imgur.com/LRct9xa.png)\n\n[贊助者付款](https://payment.opay.tw/Broadcaster/Donate/9E47FDEF85ABE383A0F5FC6A218606F8)\n\n## License\n\nMIT license\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftwtrubiks%2Fdocker-django-nginx-uwsgi-postgres-load-balance-tutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftwtrubiks%2Fdocker-django-nginx-uwsgi-postgres-load-balance-tutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftwtrubiks%2Fdocker-django-nginx-uwsgi-postgres-load-balance-tutorial/lists"}