Pointing a domain to my remote Node JS application?

前端 未结 1 838
抹茶落季
抹茶落季 2021-01-30 18:46

I\'m trying to work out how exactly to deploy Node JS on my Ubuntu 10.04 LTS server. I\'ve read many different blogs and articles that explain multiple different ways. Most seem

相关标签:
1条回答
  • 2021-01-30 19:16

    You need to separate the notion of the domain name from the actual server. The domain name points to a server. When the browser (or other client) asks for example.com, DNS looks up the associated IP address and directs the browser to the server at that IP address.

    The browser then chooses which port to send its request through by looking at the URL. For example, a request for example.com:345 will select port 345. If left unspecified, by default, when using HTTP, it uses port 80.

    So the browser has sent its request through port 80. Now, on your server, there is a program listening to that port. For you, it would nginx. Nginx reads the request ("oh, you're looking for index.html") and delivers back the contents you requested.

    In your scenario, Node.JS replaces Nginx. For Node.JS to respond, it would also need to listen to a port and respond appropriately. That's where your code comes in:

    require('http').createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello World\n');
    }).listen(1337, "127.0.0.1");
    

    This starts a server, listening at port 1337. Any requests directed to example.com:1337 would be responded to by this Node.JS application with a "Hello World".

    tl;dr: Your domain name already points to your server. You can access your application at example.com:1337, where 1337 is your port.

    0 讨论(0)
提交回复
热议问题