skip to Main Content

I’ve been trying for nearly 2 days now to deploy my node.js application to Amazon AWS on an EC2 instance and I can’t for the life of me figure out why my application won’t show up on the browser at "/".

Here is my application code:

require('dotenv').config()

const fastify = require('fastify')();
const { PORT } = process.env;


fastify.get("/", (request, reply) => { reply.send("<h1>Hello!</h1>") });


fastify.listen({ port: PORT }, function (err) {
    if (err) {
        console.log("Error: " + JSON.stringify(err))
        process.exit(1)
    }

    console.log(`App listening on port: ${PORT}`);

})

I have launched an Amazon Linux instance.
I have connected to it via SSH.
I have installed all my packages with npm install.
I have configured various inbound security rules to allow traffic into PORT 80 of which my application runs on
enter image description here

When I run curl localhost on my server terminal after connecting through ssh it returns "<h1>Hello!</h1>" but when I try and access the public ip from the browser (35.176.45.73) if just tells me that the site can’t be reached.

I’m completely new to AWS and would really appreciate any help, I’ve followed many tutorials step by step with no luck.

2

Answers


  1. Chosen as BEST ANSWER

    Restarting my EC2 instance after applying the changes to my security groups helped the changes to take effect. Hope this helps!


  2. You need to use reverse proxy, like nginx, to serve your application. Check out this article: Hosting Your Node.js API on AWS EC2

    Edit 1:
    Your server is probably not listening on Port 80.
    I recreated your setup:

    # Hard-coded PORT 80
    [root@test-server]# nohup node test.js > nohup.out 2>&1 &
    [root@test-server]# curl localhost
    <h1>Hello!</h1>[
    

    Test connection outside of the server:

    ▶ curl <my-server-public-ip>
    curl: (7) Failed to connect to <my-server-public-ip> port 80 after 49 ms: Connection refused
    

    Check if server is listening on port 80:

    > netstat -tulpan | grep ":80"
    tcp        0      0 127.0.0.1:80            0.0.0.0:*               LISTEN      28945/node
    

    It only listen on port 80 from localhost.

    Edit 2:
    Ok, you don’t need reverse proxy but you need to specify your host:

    fastify.listen({ port: PORT, host: '0.0.0.0' }, function (err) {
    

    Now your server should listen to port 80 from anywhere (0.0.0.0):

    [root@test-server]# netstat -tulpan | grep ":80"
    tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      29607/node
    

    Test connection:

    ▶ curl <my-server-public-ip>
    <h1>Hello!</h1>%
    

    It’s actually in the documentation: https://github.com/fastify/fastify/blob/aea4100062353cf4da1cfcb4fe8167ac0092117c/docs/Server.md?plain=1#L462

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search