Reputation: 11
I built a simple NodeJS server with Hapi and tried to run it inside a Docker container.
It runs nicely inside Docker, but I can't get access to it (even though I have done port mapping).
const hapi = require("@hapi/hapi");
const startServer = async () => {
const server = hapi.Server({
host: "localhost",
port: 5000,
});
server.route({
method: 'GET',
path: '/sample',
handler: (request, h) => {
return 'Hello World!';
}
});
await server.start();
console.log(`Server running on port ${server.settings.port}`);
};
startServer();
Docker file is as follows:
FROM node:alpine
WORKDIR /usr/app
COPY ./package.json ./
RUN npm install
COPY ./ ./
CMD [ "npm","run","dev" ]
To run docker, I first build with:
docker build .
I then run the image I get from above command to do port mapping:
docker run -p 5000:5000 <image-name>
When I try to access it via postman on http://localhost:5000/sample
or even localhost:5000/sample
, it keeps saying Couldn't connect to server
and when I open in chrome, it says the same Can't display page
.
PS. When i run the code as usual without Docker container, with simply npm run dev
from my terminal, the code runs just fine.
So, I am confident, the API code is fine.
Any suggestions??
Upvotes: 1
Views: 1084
Reputation: 954
Or simply remove it altogether.
You see, hapi will bind the server to an ip but that can only be known at runtime (the ip of the container) or localhost.
You could find a way to conditionally assign that to either localhost or the container ip...but that's just too much mental gymnastics for me today after 4 hours debugging :)
Upvotes: 0
Reputation: 10080
As mentioned by @pzaenger on your HAPI server configuration change localhost to 0.0.0.0.
host: 'localhost' to host: '0.0.0.0',
Upvotes: 2