title: Reload Nginx from Rails without interrupting the request
body: <p>I have a Rails 4 application that allows users to create applications, everything works fine, but i'm having a problem finalizing the app deployer.</p>
  
  <p>The deployer does some logic and then creates the Nginx host file for the new app and adds it to Nginx <code>sites-available</code> and then symlinks it to <code>sites-enabled</code>. All this is fine, the problem is that for Nginx to be aware of this new host, it needs to reload, which I am able to do automatically during the deployment but it interrupts the request.</p>
  
  <p>This is the flow:</p>
  
  <p>1 - User clicks on "Deploy" button</p>
  
  <p>2 - Rails controller action does the logic and then makes some system calls including reloading Nginx.</p>
  
  <p>3 - Browser returns a <code>502 Bad Gateway</code> <strong>&lt;- PROBLEM</strong></p>
  
  <p>Then if i reload the page everything is fine and the new app is accessible.</p>
  
  <p>How can I prevent this? I have tried to both use <code>service nginx reload</code> and <code>kill -HUP $( cat /run/nginx.pid )</code> and get the same result.</p>
  
  <p>Interestingly enough, if i do the deployment of an app already deployed (host file already present in the <code>sites-available</code> / <code>sites-enabled</code>) the 502 bad gateway doesn't happen.</p>
  
  <p>Any ideas?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Adding a 3 seconds <code>sleep</code> after the Nginx reload seems to solve the issue, this will do for now but this is hardly the best solution so better ideas are welcome!</p>