在我本地的筆記本電腦上。
我正在學習埠和 Docker,并且在 nginx 中使用不同的埠時遇到問題。我想啟動一個 nginx 容器并指定一個埠,打開容器外殼,并在我指定的埠上使用 curl 測驗 Web 服務器。在 Docker 中,我嘗試使用--expose <different_port_here>并且-e NGINX_PORT=<different_port_here>在創建容器時也嘗試過,但它們都不起作用。只有默認埠 80 有效。
有人知道我如何在容器中打開不同的埠嗎?我不想在容器外發布和轉發埠。
嘗試 1
我嘗試的第一件事是使用--expose <different_port_here>
docker run --name my-nginx-container-w-expose -d --expose 100 nginx:stable-perl
當我這樣做時docker ps,它顯示埠 100/tcp 和 80/tcp,所以我認為埠 100 現在也將打開。
然后我進入 shell 并使用以下命令嘗試 curl
docker exec -it my-nginx-container-w-expose /bin/bash
curl http://localhost:<different_port_here>
回傳以下內容:
curl: (7) 無法連接到 localhost 埠 100: 連接被拒絕
嘗試 2
我嘗試的第二件事是使用-e NGINX_PORT=<different_port_here>
docker run --name my-nginx-container-w-env-variable -d nginx:stable-perl
當我這樣做docker ps時,它不顯示埠 100/tcp,但顯示 80/tcp。
然后我進入 shell 并使用以下命令嘗試 curl
docker exec -it my-nginx-container-w-env-variable /bin/bash
curl http://localhost:<different_port_here>
curl: (7) 無法連接到 localhost 埠 100: 連接被拒絕
我唯一可以使用的埠是 80
curl 在容器中使用的唯一埠是 80。
curl http://localhost:80
回傳
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
uj5u.com熱心網友回復:
你的 nginx 配置告訴 nginx 監聽哪些埠。如果你有一個像這樣的名為 nginx.conf 的檔案
server {
listen 80;
location / {
index index.html;
root /usr/share/nginx/site1;
try_files $uri $uri/ $uri.html =404;
}
}
server {
listen 100;
location / {
index index.html;
root /usr/share/nginx/site2;
try_files $uri $uri/ $uri.html =404;
}
}
nginx 將監聽埠 80 和埠 100,并在兩個埠上提供不同的內容。
如果你然后像這樣制作一個 Dockerfile
FROM nginx
COPY nginx.conf /etc/nginx/conf.d/default.conf
RUN mkdir -p /usr/share/nginx/site1 && \
mkdir -p /usr/share/nginx/site2 && \
echo Site1 > /usr/share/nginx/site1/index.html && \
echo Site2 > /usr/share/nginx/site2/index.html
你可以像這樣構建、運行和測驗它
docker build -t test .
docker run -d --rm -p 8080:80 -p 8100:100 test
curl localhost:8080
curl localhost:8100
2 curl 命令然后回傳“Site1”和“Site2”
如果您不想公開埠,則可以在docker run命令中省略埠映射。Nginx 仍然會監聽容器中的埠(80 和 100)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/423115.html
標籤:
