如何在docker nginx容器中打开另一个端口(只在容器中;所以,不发布是-p标志)?

0 人关注

在我的本地笔记本电脑上。

我正在学习端口和Docker,在nginx中使用不同的端口时遇到了问题。我想启动一个nginx容器,并指定一个端口,打开容器外壳,在我指定的端口上用curl测试Web服务器。在Docker中,我曾尝试使用 --expose <different_port_here> ,也曾在创建容器时尝试 -e NGINX_PORT=<different_port_here> ,但都没有成功。只有默认的80端口起作用。

有谁知道我怎样才能在我的容器内打开一个不同的端口?我不希望在容器外发布和转发端口。

我尝试的第一件事是使用 --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端口失败:拒绝连接

我尝试的第二件事是使用 -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>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
</style>
</head>
<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>
2 个评论
Nginx是否在你试图连接的端口上进行监听(例如用 curl ? 用下面的命令检查一下, netstat -tlpn 在一个容器内。 首先,你必须在Nginx的配置中定义一个你喜欢的端口的 server (如定义的 80 端口的默认端口)。
我没能在容器中安装 netstat ,所以我不确定。我所知道的是,使用 curl https://localhost:80 可以工作,但我试图打开的任何其他端口都不行。
docker
nginx
zipline86
zipline86
发布于 2022-01-28
1 个回答
Hans Kilian
Hans Kilian
发布于 2022-01-29
已采纳
0 人赞同

你的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端口,并在两个端口提供不同的内容。

如果你再做一个像这样的Docker文件

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