MacOS下Docker部署Fastify服务,主机无法访问localhost:8895求助
问题描述
我在MacOS环境下进行开发,以下是我的Fastify代码:
const fastify = require('fastify')({ logger: true }) fastify.get('/ping', (req, reply) => { reply.send({ pong: "pong" }) }) const start = () => { try { fastify.listen({ port: 8895 }) } catch (e) { fastify.log.error(e) process.exit(1) } } start()
该服务运行在Docker容器中,docker-compose配置如下:
version: '3' services: node-app: build: . ports: - "8895:8895"
我的Dockerfile内容为:
FROM node:latest COPY *.json ./ COPY *.js ./ RUN npm install CMD ["npm", "run", "start"]
我执行的启动命令是:
docker-compose down && docker-compose up --build
容器内部一切正常,在容器内执行curl请求能得到Fastify返回的200状态码,但从主机访问http://localhost:8895时,页面提示:
This page isn’t working 127.0.0.1 didn’t send any data. ERR_EMPTY_RESPONSE
请问问题出在哪里?
问题原因及解决办法
问题出在Fastify的监听地址配置上。默认情况下,fastify.listen({ port: 8895 }) 只会绑定容器内部的127.0.0.1地址,这意味着服务仅能在容器内部被访问,无法通过Docker的端口映射暴露给主机。
只需修改Fastify的监听配置,让它绑定到0.0.0.0(允许所有网络地址访问)即可解决:
const start = () => { try { fastify.listen({ port: 8895, host: '0.0.0.0' }) } catch (e) { fastify.log.error(e) process.exit(1) } }
修改代码后,重新执行docker-compose down && docker-compose up --build构建启动容器,主机就能通过http://localhost:8895/ping正常访问服务了。
内容的提问来源于stack exchange,提问作者sensorario
相关产品推荐
相关产品推荐

