問題描述
如何從 http 請求中阻止端口服務器 (How to block port server from http request)
我有 Nginx 有一個反向代理來將客戶端請求連接到 docker 運行容器。問題是您可以通過鍵入 serverhost.fr:port_number
來訪問容器。我希望客戶端只能通過特定主機名訪問正在運行的容器。這是我的 docker‑compose.yml 文件:
version: '3'
services:
api:
image: username/backendimgage:latest
ports:
‑ "8081:8000"
restart: always
front:
depends_on:
‑ api
image: username/frontendimage:latest
ports:
‑ "8080:36073"
restart: always
我試圖用 ufw 阻止,它破壞了一切。我嘗試使用 if 語句在 Nginx 上發送 401 代碼,例如
if ( $host = serverhost.fr:port_number ){ return 401; }
OR
6if ( $host ~* portnumber ){ return 401; }
但它不起作用。我沒有大的操作背景,所以我有點迷路了。
參考解法
方法 1:
If you're running the nginx proxy outside of Docker, you must connect to the published ports:
from your containers.
By default when you publish ports:
they're published on all interfaces of the host system. However, you can specify an alternate bind address. If you set a backend service to only publish on the 127.0.0.1 localhost interface, it won't be reachable from off host.
version: '3'
services:
api:
image: username/backendimgage:latest
ports:
‑ "127.0.0.1:8081:8000"
# ^^^^^^^^^
(If you're trying to connect from one container to another by using its host port – something like http://host.docker.internal:8081
on MacOS/Windows platforms – this will interfere with that, but you should be able to use Docker‑native inter‑container communication there.)
(by Pierre Monier、David Maze)