title: Node.js: Relationship among http.Server, http.Agent, sockets, and http.request
body: <p>Per the <a href="https://nodejs.org/dist/latest-v6.x/docs/api/http.html#http_http_request_options_callback" rel="noreferrer">docs</a>:</p>
  
  <blockquote>
    <p>Node.js maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.</p>
  </blockquote>
  
  <p>The docs further specify that Node relies on <code>http.globalAgent</code> to make requests by default, but that you can use your own agent by creating a new <code>http.Agent</code>.  Agents are used to "pool sockets" for http requests.</p>
  
  <p>My interpretation of all this is that each time you do a <code>http.createServer</code>, by default you get several sockets (presumably that is what is meant by "connections") to make http requests and these sockets are pooled / managed by <code>http.globalAgent</code>.</p>
  
  <p>What isn't clear to me is what happens when you create your own <code>http.Agent</code>.  Does the <code>Agent</code> just "take over" the sockets that were previously being managed by <code>http.globalAgent</code>?  Or do you have to create a new socket for your new <code>Agent</code> via <code>agent.createConnection</code>?</p>
  
  <p>On a related note, if I were to start up two servers in the same node process and subsequently make an http request, e.g.</p>
  
  <pre><code>const server1 = http.createServer(function(req, res) {
    res.end('Hello from server1');
  }).listen(3000);
  
  const server2 = http.createServer(function(req, res) {
    res.end('Hello from server2');
  }).listen(5000);
  
  http.get('/someurl');
  </code></pre>
  
  <p>from which server would the request be made?  Does <code>http.Agent</code> come into play here?</p>