PMPV
레일스로 헤로쿠 서버 올리기 본문
https://blog.naver.com/xhdtn8070/221236625907
http://wantknow.tistory.com/61
두 명의 빛빛빛 블로그를 참고했습니다. 앗 아아.. 눈부셔라
0.
워크스페이스를 열고 서버에 배포할 간단한 CRUD 페이지를 준비합니다.
controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class PostsController < ApplicationController def index @posts = Post.all @post = Post.new end def create post = Post.new post.title = params[:post][:title] post.save redirect_to root_path end end | cs |
view
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <h1>ㅎㅇㅎㅇㅎㅇㅎㅇ헤로쿠</h1> <%= form_for @post do |f| %> <%= f.label :title, '제목' %> <%= f.text_field :title %> <%= f.submit '저장' %> <% end %> <br> <br> <% @posts.each do |t| %> <%= t.title %> <br> <hr> <% end %> | cs |
route.rb
1 2 3 4 5 6 | Rails.application.routes.draw do root 'posts#index' resources :posts, only: [:index, :create] end | cs |
서버에 배포할 우리의 서비스가 준비됐습니다.
이제 약간 붕 뜬 상태로, 헤로쿠로 빠져봅씨다 레쓰기릿ㅆㅆㅆ
1.
헤로쿠 로그인을 하기 전, config 폴더 안을 살펴보겠습니다.
environments 폴더 안을 주목해주세요.
세 가지 환경이 있습니다.
- development
- production
- test
우리가 C9에서, 혹은 로컬 환경에서 작업을 하며 서버를 돌릴 때가 개발 환경입니다.
헤로쿠를 이용해 우리의 프로젝트를 서버에 올릴 때는 production 세팅에 맞춰 돌아가게 됩니다.
때문에 헤로쿠에서 요구하는 배포 세팅을 맞춰야 합니다.
이 점을 유의하며 지금부터 헤로쿠 공식 문서를 살펴보겠습니다.
A. pg 설치 및 세팅
첫 번째 요구 사항입니다. 레일스 데이터베이스는 splite3를 사용합니다.
헤로쿠는 postgresql을 요구합니다. 공식 문서에는 splite3 대신 pg를 사용하도록 권장하고 있지만, 우리는 development 환경에서는 splite3, production 환경에서는 pg를 사용하도록 젬파일과 DB 세팅을 수정하겠습니다.
<수정 전>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.2.5' # Use sqlite3 as the database for Active Record gem 'sqlite3' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.1.0' # See https://github.com/rails/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks gem 'turbolinks' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.0' # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', '~> 0.4.0', group: :doc # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' # Use Unicorn as the app server # gem 'unicorn' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug' end group :development do # Access an IRB console on exception pages or by using <%= console %> in views gem 'web-console', '~> 2.0' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' end |
기존의 젬파일입니다. 상단에 splite3 젬이 보입니다. 이 젬을 개발 환경에서만 사용하도록 위치를 바꿔주고, production 그룹을 만들어주겠습니다.
<수정 후>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.2.5' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.1.0' # See https://github.com/rails/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks gem 'turbolinks' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.0' # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', '~> 0.4.0', group: :doc # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' # Use Unicorn as the app server # gem 'unicorn' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug' # Use sqlite3 as the database for Active Record gem 'sqlite3' end group :development do # Access an IRB console on exception pages or by using <%= console %> in views gem 'web-console', '~> 2.0' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' end group :production do gem 'pg', '0.20' end | cs |
splite3 젬을 development, test 환경에서만 이용하도록 위치를 바꿔주고 하단에 production 환경을 만들어줬습니다.
pg 젬은 0.20 버전으로 명시했습니다.
B. database.yml 설정
이번에는 config/database.yml 파일을 수정해주겠습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | # SQLite version 3.x # gem install sqlite3 # # Ensure the SQLite 3 gem is defined in your Gemfile # gem 'sqlite3' # default: &default adapter: sqlite3 pool: 5 timeout: 5000 development: <<: *default database: db/development.sqlite3 # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: <<: *default database: db/test.sqlite3 production: <<: *default database: db/production.sqlite3 | cs |
기존의 모습입니다. 역시 production 부분만 수정해주겠습니다.
<수정 후>
1 2 3 4 | production: <<: *default adapter: postgresql encoding: unicode | cs |
이렇게 바꿔줍시다.
이것으로 우리의 프로젝트는 C9에서 작업할 때는 splite3를, 헤로쿠에 올라갈 때는 postgres를 사용하게 되었습니다.
공식 문서를 계속 읽어보겠습니다.
C. rails_12factor 설치
rails_12factor 젬을 요구합니다. 젬파일에 넣어줍시다.
1 2 3 4 | group :production do gem 'pg', '0.20' gem 'rails_12factor' end | cs |
아까 pg 젬 하단에 넣어줬습니다.
계속 읽어봅시다.
D. 루비 버전 명시
루비 버전을 2.3.4로 맞춰주길 요구합니다. 젬파일에 써주면 된다고 합니다.
젬파일 최상단에 적어주고 넘어가겠습니다. 젬파일을 수정했을 때 bundle install을 잊지 말아주세요.
계속 읽어봅시다.
E. commit & push + migrate
다음부터는 깃에 관한 얘기가 나옵니다. 깃 커밋을 먼저 하고 heroku create를 진행해줍니다.
$ git init
$ git add .
$ git commit -m "init"
$ heroku create
아직 로그인을 한적이 없다면 heroku create를 하면서 로그인을 해주시면 됩니다.
create 뒤에 저장소 이름을 명시할 수 있습니다. 명시하지 않으면 랜덤으로 저장소 이름을 생성해줍니다.
여기까지 다 됐다면 푸시를 해봅시다.
멀쩡하게 잘 올라갔네요! 서버를 돌리기 전에 마이그레이트 작업도 해줄게요.
$ heroku run rake db:migrate
여기까지 문제 없이 따라오셨다면 디플로이 무난하게 성공하셨을겁니다.
여러분의 첫 프로젝트가 웹사이트에 올라갔습니다. 축하합니다!
2.
remote rejected master -> master (pre-receive hook declined)
a. pg 설정 문제
위에서 설명한 postgres 설정을 잘못했을 가능성이 있습니다. Gemfile에서 pg 젬이 프로덕션 환경이 맞는지, database.yml 프로덕션 환경 설정이 잘 되어있는지 확인해주세요.
b. Precompiling assets failed.
낯선 개념입니다. 여러분이 C9에서만 작업을 진행하셨다면 지금까지 마주친적이 없는 오류일겁니다. css나 js 작업 내용이 있다면 발생할 수 있습니다.
위에서 설명드린 세 가지 환경 개념 - 개발, 배포, 테스트 환경과 관련된 에러입니다.
개발 환경에서는 어셋의 프리컴파일을 신경쓸 필요가 없습니다. 하지만 배포 환경에서 여러분의 서비스를 돌리고 싶다면 어셋을 프리컴파일 해줄 필요가 생깁니다.
프리컴파일에 대한 설명은 생략하겠습니다. 구글링 고고곡
방법은 두 가지가 있습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | Rails.application.configure do config.cache_classes = true config.eager_load = true config.consider_all_requests_local = false config.action_controller.perform_caching = true config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? config.assets.js_compressor = :uglifier # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false config.assets.digest = true config.log_level = :debug config.i18n.fallbacks = true config.active_support.deprecation = :notify config.log_formatter = ::Logger::Formatter.new config.active_record.dump_schema_after_migration = false end | cs |
environments/production.rb을 확인해주세요. 중간에 config.assets.compile = false 부분을 제외한 나머지 주석은 다 지웠습니다.
이 부분을 true로 변경해줄 수 있습니다.
변경 사항이 있을 때마다 라이브 컴파일을 요청하는 방식입니다. 하지만 페이지 속도와 압축의 문제로 권장되지 않는 방법입니다. 패쓰하세요.
이 요청이 권장되지 않는 이유는 다음 링크에 상세하게 나와있습니다.
https://stackoverflow.com/questions/8821864/config-assets-compile-true-in-rails-production-why-not
공식 문서를 다시 보겠습니다.
아까 보던 문서의 하단에 Asset Pipeline에 대한 항목이 있습니다. 저 링크로 접속해주세요.
To compile your assets locally, run the assets:precompile
task locally on your app. Make sure to use the production
environment so that the production version of your assets are generated.
RAILS_ENV=production bundle exec rake assets:precompile
A public/assets
directory will be created. Inside this directory you’ll find a manifest.yml
which includes the md5sums of the compiled assets in Rails 3. In Rails 4 the file will be manifest-<md5 hash>.json
. Adding public/assets
to your git repository will make it available to Heroku.
권장되는 사전 컴파일 요청입니다. 이 부분을 배쉬에 입력해주세요.
요청을 하고 난 뒤에는 깃 커밋을 다시 진행해주세요.
c. Ruby 버전 문제
Application error - An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.
푸시는 잘 됩니다. 그런데 도메인으로 접속해도 이런 오류만 뜹니다. 로그를 확인하라고 하니 확인해줍시다.
warning: constant ::Fixnum is deprecated
warning: constant ::Bignum is deprecated
대시보드에서 잘 찾아보시면 이런 에러 메세지가 있습니다.
루비 버전의 문제입니다. 루비는 2.4 버전 이후로 Fixnum과 Bignum을 사용하지 않습니다. 헤로쿠는 최신의 루비 버전을 사용한다고 설명하고 있고 현재 2.4.4 버전으로 확인됩니다. 헤로쿠의 루비 버전은 로그에서 확인이 가능합니다.
-----> Ruby app detected
-----> Compiling Ruby/Rails
-----> Using Ruby version: ruby-2.4.4
-----> Installing dependencies using bundler 1.15.2
C9은 2.3.4를 이용합니다. 이 부분에서 충돌이 발생할 수 있습니다.
해결 방법은 간단합니다. 3-D에 설명했던 루비 버전 명시를 사용해 루비 버전을 2.4 이하로 내려주세요. 저는 C9 버전에 맞춰 2.3.4로 진행했습니다.
d. migrate 미실행
We're sorry, but something went wrong. - If you are the application owner check the logs for more information.
RAILS_ENV=production bundle exec rake assets:precompile
이거 까먹으셨을수도 있습니다.
끝.