【问题标题】:running instance of a hello world node app in docker but unable to reach on port 8080在 docker 中运行 hello world 节点应用程序的实例,但无法访问端口 8080
【发布时间】:2022-02-15 09:05:06
【问题描述】:

我有一个简单的网络服务器监听器,它在 docker 中使用命令运行良好

docker build -t node-hello-world:latest .
docker run -it -p 8080:8080 --name node-hello-world node-hello-world:latest

这是应用程序:

'use strict';

const express = require('express')
const app = express();

const port = 8080;
const host = '0.0.0.0';

app.get('/', (req, res) => {
    res.send('Hello World from IBM Cloud Essentials!');
})

app.listen(port, host);
console.log(`Running on http://${host}:${port}`);

第一个日志条目输出正常:Running on http://${host}:${port}

但尝试localhost:8080 只会说“无法访问此站点”。这是我的docker ps -a 代码:

CONTAINER ID   IMAGE                                 COMMAND                  CREATED          STATUS          PORTS                                                                                                                                  NAMES
0995c28fabed   node-hello-world:latest               "docker-entrypoint.s…"   15 minutes ago   Up 15 minutes   0.0.0.0:8080->8080/tcp                                                                                                                 node-hello-world

【问题讨论】:

  • 该设置看起来不错;你有正确的docker run -p 选项,你正在收听0.0.0.0,这是我要检查的两件重要事情。您从哪里调用该 URL?您的主机操作系统和 Docker 安装是什么?

标签: node.js docker server


【解决方案1】:

这篇文章可能会有所帮助:

https://www.cloudsavvyit.com/14114/how-to-connect-to-localhost-within-a-docker-container/

Docker Desktop 18.03+ for Windows 和 Mac 支持 host.docker.internal 作为 localhost 的功能别名。用这个 容器中的字符串以访问您的主机。

  • localhost 和 127.0.0.1 - 这些解析到容器。
  • host.docker.internal - 解析到外部主机。'

另外,

Docker 提供了一个主机网络,让容器可以共享您主机的 网络堆栈。这种方法意味着容器内的 localhost 解析到物理主机,而不是容器本身。

容器通过添加--network=host 标志与主机网络一起启动:

docker run -d --network=host my-container:latest

现在您的容器可以直接引用 localhost 或 127.0.0.1。

如果您使用的是 Docker Compose,请修改容器的服务 包含 network_mode 字段的定义:

services:
  my-service:
    network_mode: host

另见:https://www.tutorialspoint.com/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-machine

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    相关资源
    最近更新 更多