сайт не загружается после развертывания с помощью mina + unicorn + nginx - PullRequest
0 голосов
/ 10 июня 2018

Я новичок в развертывании, у меня есть приложение rails с Ruby 2.4.1 и rails v 5.1.Я использовал развертывание mina с единорогом в качестве сервера приложений, а nginx - веб-сервер.Я развернул приложение, используя инструмент развертывания mina, и он показывает, что результаты успешны.Я проверил свои логи в единороге, в nginx, ошибки не найдено.я обновил mina и nginx.conf, основываясь на разных уроках, это не дает результата.Также nginx работает хорошо.Я использовал gcloud для провайдера развертывания.

mina файл deploy.rb

require 'mina/git'
require 'mina/rbenv'
require 'mina/bundler'
require 'mina/rails'
require 'mina/unicorn'
require 'mina/rvm'

# preset defaults
set :application_name, 'blog_app'
set :domain, 'XXXXXX'
set :deploy_to, 'path'
set :repository, 'url'
set :branch, 'staging'
set :user, 'ggg'
set :rails_env, 'staging'
set :identity_file, "blog_app.pem"

set :forward_agent, true
set :port, '22'
set :unicorn_pid, "#{fetch(:deploy_to)}/shared/pids/unicorn.pid"

set :shared_files, ['config/database.yml', 'log', 'config/secrets.yml', '.env', 'public/uploads']
# rails pid
set :pid_file, "#{fetch(:deploy_to)}/shared/pids/#{fetch(:rails_env)}.pid"

task :remote_environment do
invoke :'rvm:use', 'ruby-2.4.1@default'
end

task :setup => :remote_environment do

command %[mkdir -p "#{fetch(:deploy_to)}/shared/log"]
command %[chmod g+rx,u+rwx "#{fetch(:deploy_to)}/shared/log"]

command %[mkdir -p "#{fetch(:deploy_to)}/shared/config"]
command %[chmod g+rx,u+rwx "#{fetch(:deploy_to)}/shared/config"]

command %[touch "#{fetch(:deploy_to)}/shared/config/database.yml"]
command  %[echo "-----> Be sure to edit 'shared/config/database.yml'."]

command %[touch "#{fetch(:deploy_to)}/shared/config/secrets.yml"]
command %[echo "-----> Be sure to edit 'shared/config/secrets.yml'."]

command %[touch "#{fetch(:deploy_to)}/shared/config/config.yml"]
command %[echo "-----> Be sure to edit 'shared/config/config.yml'."]

command %[touch "#{fetch(:deploy_to)}/.env"]
command %[echo "-----> Be sure to edit '.env"]

# sidekiq needs a place to store its pid file and log file
command %[mkdir -p "#{fetch(:deploy_to)}/shared/pids/"]
command %[chmod g+rx,u+rwx "#{fetch(:deploy_to)}/shared/pids"]
end

desc "Deploys the current version to the server."
task :deploy => :remote_environment do
deploy do

on :prepare do
  command %[kill -9 `cat #{fetch(:pid_file)}`]
end

comment "Deploying #{fetch(:application_name)} to #{fetch(:domain)}:#{fetch(:deploy_to)}"
invoke :'git:clone'
invoke :'deploy:link_shared_paths'
invoke :'bundle:install'
invoke :'rails:db_migrate'
# invoke :'rails:db_seed'
invoke :'rails:assets_precompile'
invoke :'deploy:cleanup'

on :launch do
  invoke :'unicorn:restart'
  command "cd #{fetch(:deploy_to)}/current ; mkdir -p tmp ; touch tmp/restart.txt"
end
end
end

desc "Restart unicorn using 'upgrade'"
task :restart => :remote_environment do
invoke 'unicorn:stop'
invoke 'unicorn:start'
end

config / unicorn.rb

# encoding: utf-8
# Set your full path to application.
app_dir = File.expand_path('../../', __FILE__)
shared_dir = File.expand_path('../../../shared/', __FILE__)

# set unicorn options
worker_processes 2
preload_app true
timeout 30

# fill path to your app
working_directory app_dir

# Set up socket location
listen "#{shared_dir}/sockets/unicorn.sock", backlog: 64

# Loging
stderr_path "#{shared_dir}/log/unicorn.stderr.log"
stdout_path "#{shared_dir}/log/unicorn.stdout.log"

# Set master PID location
pid "#{shared_dir}/pids/unicorn.pid"

before_fork do |server, worker|
 defined?(ActiveRecord::Base) && 
 ActiveRecord::Base.connection.disconnect!
old_pid = "#{server.config[:pid]}.oldbin"
if File.exists?(old_pid) && server.pid != old_pid
 begin
  sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
  Process.kill(sig, File.read(old_pid).to_i)
 rescue Errno::ENOENT, Errno::ESRCH
  # someone else did our job for us
 end
end
end

after_fork do |server, worker|
 defined?(ActiveRecord::Base) && ActiveRecord::Base.establish_connection
end

before_exec do |server|
ENV['BUNDLE_GEMFILE'] = "#{app_dir}/Gemfile"
end

/ etc / nginx / nginx.conf

user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;
}

http {


    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    gzip on;
    gzip_disable "msie6";

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

    upstream app {
    server unix:/path/shared/sockets/unicorn.sock fail_timeout=0;
    }
}

/ etc / nginx / sites-available / blog_app

server {
listen 80;
server_name ip-address;

root /path/current;

try_files $uri/index.html $uri @app;

location @app {
   proxy_pass http://app;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
   proxy_redirect off;
}

error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
keepalive_timeout 10;
}

также у меня есть символическая ссылка с включенными сайтами.

 cd /etc/nginx/sites-enabled
 sudo ln -s ../sites-available/blog_app

при тестированиисостояние nginx

 sudo /etc/init.d/nginx status

● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2018-06-10 05:55:45 UTC; 56min ago
  Process: 16869 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0/SUCCESS)
  Process: 15991 ExecReload=/usr/sbin/nginx -g daemon on; master_process on; -s reload (code=exited, status=0/SUCCESS)
  Process: 16886 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 16874 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
 Main PID: 16894 (nginx)
    Tasks: 2
   Memory: 2.4M
      CPU: 25ms
   CGroup: /system.slice/nginx.service
           ├─16894 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           └─16897 nginx: worker process

Jun 10 05:55:45 staging systemd[1]: Stopped A high performance web server and a reverse proxy server.
Jun 10 05:55:45 staging systemd[1]: Starting A high performance web server and a reverse proxy server...
Jun 10 05:55:45 staging systemd[1]: nginx.service: Failed to read PID from file /run/nginx.pid: Invalid argument
Jun 10 05:55:45 staging systemd[1]: Started A high performance web server and a reverse proxy server.
Jun 10 05:57:01 staging systemd[1]: Started A high performance web server and a reverse proxy server.

также при выполнении команды

sudo nginx -t -c /etc/nginx/nginx.conf

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

также после запуска mina deploy даст следующий результат.

-----> DB migrations unchanged; skipping DB migration
-----> Precompiling asset files
       Yarn executable was not detected in the system.
       Download Yarn at https://yarnpkg.com/en/docs/install
-----> Cleaning up old releases (keeping 5)
       /home/anoob.bava/blog_app/tmp/build-152861030811147
       RVM used your Gemfile for selecting Ruby, it is all fine - Heroku does that too,
       you can ignore these warnings with 'rvm rvmrc warning ignore /home/anoob.bava/blog_app/tmp/build-152861030811147/Gemfile'.
       To ignore the warning for all files run 'rvm rvmrc warning ignore allGemfiles'.

-----> Deploy finished
-----> Building
-----> Moving build to /home/anoob.bava/blog_app/releases/10
-----> Build finished
-----> Launching
-----> Updating the /home/anoob.bava/blog_app/current symlink
-----> Using RVM environment "ruby-2.4.1@default"
       RVM used your Gemfile for selecting Ruby, it is all fine - Heroku does that too,
       you can ignore these warnings with 'rvm rvmrc warning ignore /home/anoob.bava/blog_app/current/Gemfile'.
       To ignore the warning for all files run 'rvm rvmrc warning ignore allGemfiles'.

       Using /home/anoob.bava/.rvm/gems/ruby-2.4.1
-----> Duplicating Unicorn...
       RVM used your Gemfile for selecting Ruby, it is all fine - Heroku does that too,
       you can ignore these warnings with 'rvm rvmrc warning ignore /home/anoob.bava/blog_app/current/Gemfile'.
       To ignore the warning for all files run 'rvm rvmrc warning ignore allGemfiles'.

-----> Done. Deployed version 10
       Connection to IP closed.

       Elapsed time: 22.66 seconds

во всех руководствах нет проблем с моей конфигурацией.

1 Ответ

0 голосов
/ 19 июня 2018

После 2 дней отладки я нашел решение, по умолчанию облако Google не позволяет порту подключаться.Чтобы протестировать эту команду в терминале

telnet ipaddress port-number

, создайте новое правило брандмауэра, как описано в приведенной ниже ссылке, предоставленной GCP.

ссылка на документ GCP

...