Fastify无法在Docker / Kubernetes上运行

编程入门 行业动态 更新时间:2024-10-12 05:46:43

<a href=https://www.elefans.com/category/jswz/34/1771267.html style=Fastify无法在Docker / Kubernetes上运行"/>

Fastify无法在Docker / Kubernetes上运行

我有一个非常简单的应用程序,它返回“ Hello World”字符串,在本地运行良好。正如您将从下面的应用程序代码中看到的那样,它在端口4000上运行。当我创建docker映像并运行容器时,无法从计算机上的localhost:4000访问它,但是我可以看到docker正确执行了node index.js命令,并且应用程序正在运行,没有任何错误。

我还尝试将其部署到Kubernetes集群,当我访问负载均衡器ip时得到ERR_EMPTY_RESPONSE。通过kubectl检查该应用程序后,我可以看到一切运行正常,图像已下载并且pod正在运行。

我正在努力了解我错过的内容以及为什么它只能在本地使用。

NodeJS应用

import fastify from 'fastify';

const server = fastify();

server.get('/', (_request, reply) => {
   reply.status(200).send("Hello World");
});

server.listen(4000, error => {
  if (error) {
    process.exit(1);
  }
});

Dockerfile

FROM node:14.2-alpine

WORKDIR /app

COPY package.json yarn.lock /app/

RUN yarn

COPY . .

EXPOSE 4000

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

Kubernetes清单

---
# Load balancer
apiVersion: v1
kind: Service
metadata:
  name: development-actions-lb
  annotations:
    service.beta.kubernetes.io/do-loadbalancer-name: "development-actions-lb"
    service.beta.kubernetes.io/do-loadbalancer-algorithm: "round_robin"
spec:
  type: LoadBalancer
  selector:
    app: development-actions
  ports:
    - name: http
      protocol: TCP
      port: 80
      targetPort: 4000
---
# Actions deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: development-actions
spec:
  replicas: 1
  selector:
    matchLabels:
      app: development-actions
  template:
    metadata:
      labels:
        app: development-actions
    spec:
      containers:
        - image: registry.digitalocean/myapp/my-image:latest
          name: development-actions
          ports:
            - containerPort: 4000
              protocol: TCP
      imagePullSecrets:
        - name: registry-myapp
回答如下:

[首先,当我尝试您的代码时,我使用本地docker进行了尝试,但是行为是相同的,因此我希望它可以避免默认情况下fastify仅监听localhost

docker build -t development-actions:latest .
docker run -it -p 4000:4000 development-actions:latest

在Docker内部,您应该明确提及'0.0.0.0',因为默认情况下,fastify仅在localhost 127.0.0.1接口上扩展。要侦听所有可用的IPv4接口,应将示例修改为侦听0.0.0.0,因此我将其更改为以下内容:

const server = require('fastify')({ logger: true })

server.get('/', (_request, reply) => {
   reply.status(200).send("Hello World");
});

server.listen(4000, '0.0.0.0', error => {
  if (error) {
    process.exit(1);
  }
});

其余部分应该相同。要在本地尝试,可以使用:

参考:

  1. https://www.fastify.io/docs/latest/Getting-Started/#your-first-server

更多推荐

Fastify无法在Docker / Kubernetes上运行

本文发布于:2024-05-07 16:00:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1757035.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Fastify   Docker   Kubernetes

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!