首页 > 解决方案 > Express docker应用程序上的连接被拒绝

问题描述

我有一个更复杂的应用程序,我对它进行 CURL 并收到此响应

http: error: ConnectionError: HTTPConnectionPool(host='localhost', port=3000): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x10ded04d0>: Failed to establish a new connection: [Errno 61] Connection refused')) while doing GET request to URL: http://localhost/

所以我重新创建了一个显示错误的较小示例。

app.use(createRouter());


const port = 3000;
http
  .createServer(app)
  .listen(port, "0.0.0.0", () => console.log(`Listening on port ${port}`));

createRouter 看起来像

export default function createRouter() {
  // *********
  // * SETUP *
  // *********
  const router = express.Router();

  /**
   * Uncached routes:
   * All routes that shouldn't be cached (i.e. non-static assets)
   * should have these headers to prevent 304 Unmodified cache
   * returns. This middleware applies it to all subsequently
   * defined routes.
   */
  router.get("/*", (req, res, next) => {
    res.set({
      "Last-Modified": new Date().toUTCString(),
      Expires: -1,
      "Cache-Control": "must-revalidate, private"
    });
    next();
  });

  // *****************
  // * API ENDPOINTS *
  // *****************

  router.all("/", (req, res, next) => {
    res.send({ message: "Welcome to Age Bold" });
  });

  // 404 route
  router.all("/*", (req, res, next) => {
    next(new ApplicationError("Not Found", NOT_FOUND));
  });
  router.use((err, req, res, next) => {
    if (err instanceof ApplicationError) {
      res.status(err.statusCode).send({
        message: err.message,
        data: err.data || {}
      });
      return;
    }
    res.status(INTERNAL_SERVER_ERROR).send({
      message: "Uncaught error"
    });
  });
  return router;
}

这就是我的 Dockerfile 的样子

FROM node:8-alpine
RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app
COPY package*.json ./
COPY . .
RUN npm install -g yarn
RUN yarn install
RUN yarn build

EXPOSE 3000

ENV NODE_ENV=local

CMD [ "node", "build/index.js" ]

我这样运行

docker run -p 3000:3000 <image-name>

据我所知,我正在做我需要做的一切来完成这项工作。

这就是我提出 curl 请求的方式(使用 httpie)

curl http://localhost:3000

catch all 路线应该返回一些东西,但我得到了错误。

我在 MacOSX 上。

我需要做什么才能使其正常工作?

标签: node.jsdockerexpress

解决方案


好的,这很愚蠢。

我不知道这个关于 docker,但是当你运行时

eval $(minikube docker-env)

您是在说“使用 Minikube 的 docker daemon”。我没有意识到 Minikube 的 docker daemon 与我的主机 docker daemon 不同,这意味着点击 localhost 意味着什么也没有。


推荐阅读