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);
}
});
其余部分应该相同。要在本地尝试,可以使用:
参考:
- https://www.fastify.io/docs/latest/Getting-Started/#your-first-server
更多推荐
Fastify无法在Docker / Kubernetes上运行
发布评论