I tried to containerize a server using Docker for practicing but it doesn't work when it's containerized.
My simple Node.js server looks likes this:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
console.log("data is recieved from the server");
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello world');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
I suspect something might be wrong with my package.json
, it looks like this:
{
"name": "dockerservers",
"version": "1.0.0",
"description": "first server for dockering",
"main": "app.js",
"dependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start":"node app.js"
},
"author": "scully86",
"license": "MIT"
}
And my Dockerfile
looks like this:
# Use the official Node.js 18 image as the base image
FROM node:18
# Set the working directory inside the container
WORKDIR /usr/src/app
# Copy the rest of the application code to the working directory
COPY . /usr/src/app/
# Install dependencies
RUN npm install
# Expose the port on which the server listens
EXPOSE 3000
ENV NAME dockerservers
# Start the server
CMD ["node","app.js"]
I successfully built the image and ran it with this command:
docker run -p 3000:3000 nodeserver
All the things working properly until now.
The problem is, the Node.js server is not sending response to the exposed port and this error is shown:
Can anyone help? I've been stuck for almost a day now.