title: Deploy NodeJS app with pm2 and Capistrano
body: <p>I develop project based on NodeJs, pm2, Capistrano 3. </p>
  
  <p>Faced with problem of downtime while deploying Node app with Capistrano.</p>
  
  <p>deploy.rb: </p>
  
  <pre><code>set :linked_dirs, ['node_modules', 'logs']
  set :linked_files, ['ecosystem.json']
  
  set :npm_flags, '--silent --no-spin'
  
  before 'deploy:updated', 'assets:upload'
  after 'deploy:updated', 'assets:webpack'
  after 'deploy:publishing', 'pm2:restart'
  </code></pre>
  
  <p>assets:upload - builds js and css files and uploads to CDN. Build performs with Webpack so it's create webpack-assets.json.</p>
  
  <p>assets:webpack - uploads webpack-assets.json to prod servers. webpack-assets.json is using by node to get exact asset name because it contains hash:</p>
  
  <pre><code>task :webpack do
      run_locally do
          roles(:web).each do |host|
              execute :rsync, '-rvzu', "themes-assets.json", "#{host.user}@#{host.hostname}:#{fetch(:release_path)}"
              execute :rsync, '-rvzu', "webpack-assets.json", "#{host.user}@#{host.hostname}:#{fetch(:release_path)}"
          end
      end
  end
  </code></pre>
  
  <p>pm2:restart - should perform zero time reload. But in fact I'm getting 1second down time. If I perform this task independently there is no downtime.</p>
  
  <pre><code>def restart_app
          within current_path do
              execute :pm2, :startOrRestart, fetch(:deploy_to) + '/shared/ecosystem.json'
          end
      end
  </code></pre>
  
  <p>pm2 logs show the following error</p>
  
  <pre><code>Process with pid 123169 still not killed, retrying...
  </code></pre>