Welcome! Log In Create A New Profile

Advanced

Node.js is running on port 3000 but Nginx cannot see it

Posted by hack3rcon 
Node.js is running on port 3000 but Nginx cannot see it
April 03, 2024 05:52AM
Hello,
The Dockerfile is as follows:

FROM node:latest

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY ./www/package.json /usr/src/app/package.json
RUN npm install
RUN npm update

COPY ./www /usr/src/app

EXPOSE 3000

The YAML file is as follows:

version: '3.9'
services:
nodejs:
container_name: Node
build:
context: .
dockerfile: Dockerfile
command: npm start
volumes:
- ./www:/usr/src/app
expose:
- "3000"
nginx:
image: nginx:latest
container_name: Nginx-NodeJS
ports:
- '80:80'
volumes:
- ./default.conf:/etc/nginx/conf.d/default.conf
- ./www:/usr/share/nginx/html
depends_on:
- nodejs
links:
- nodejs

The default.conf file is as follows:

server {
listen 80;
server_name default_server;
error_log /var/log/nginx/error.system-default.log;
access_log /var/log/nginx/access.system-default.log;
charset utf-8;

root /usr/share/nginx/html;
index index.html index.php index.js;

location ~ \.js$ {
proxy_pass http://nodejs:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}

location / {
autoindex on;
try_files $uri $uri/ $uri.html =404;
}
}

The index.js file is as follows:

const http = require('http')
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/html' })

if (req.url === '/') {
res.write('<h1>Node and Nginx on Docker is Working</h1>')
res.end()
} else {
res.write('<h1>404 Nout Found</h1>')
res.end()
}
})

server.listen(process.env.PORT || 3000, () => console.log(`server running on ${server.address().port}`))

Result:

# curl http://localhost/index.js
<h1>404 Nout Found</h1>

What is wrong?

Thank you.
Sorry, only registered users may post in this forum.

Click here to login

Online Users

Guests: 245
Record Number of Users: 8 on April 13, 2023
Record Number of Guests: 421 on December 02, 2018
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready