Deploying to Heroku
Making magic happen
Few things are as exciting as seeing your website live on a server other than your local host. After sifting through many errors, I finally was able to get my Dev Bootcamp team’s Sinatra-based app live on Heroku ( dbc-flashh.herokuapp.com ).
Heroku is a cloud platform for web apps. It allows you to deploy your site to a server and have a fairly short URL for it for free. Heroku supports projects in Ruby, Java, Node.js, Scala, Clojure, Python, PHP, and several other languages. I figured I’d share the steps needed to make this work in case it might help someone. This post will focus on projects built in Sinatra.
First, create an account on Heroku.com.
Then, open the root directory of your project in terminal. Add and commit any changes to git. Also run $ bundle install .
Run $ heroku login . Then run $ heroku create NAME –addons heroku-postgresql . The line before addons should be two dashes but it is printing as one - on this blog. Put anything you’d like where NAME is. It will only work if no one else has chosen that as the name for their Heroku project. If you just write heroku create, Heroku will generate a random name for you. Your URL will then be “NAME.herokuapp.com”. The –addons heroku-postgresql sets up the database for your project.
You now will have a remote pointing to heroku. If you run $ git remote -v , you should see Heroku listed there. But before you can push your project there, you need to make some tweaks to your code if you are using Sinatra.
Check your Gemfile. Make sure that pg and rspec are both included in your main gem list, NOT inside a “group production” or other special production method.
Also, you will likely get an Internal Server Error on Heroku unless you include the following code in one of your controllers:
after do
ActiveRecord::Base.connection.close
end
Now you can run $ git push heroku master . You would then run $ heroku run rake db:migrate and $ heroku run rake db:seed to populate your database. Note that you can NOT run $ heroku run rake db:create because this command does not work for Heroku. You have to activate postgresql like in the create command above. If you have any questions about how to interact with your database on Heroku, check the Heroku documentation for Postgres since not all the Sinatra rakefile commands work with Heroku. For example, you can’t run $ heroku run rake db:drop to delete your database. You have to run $ heroku pg:reset.
Your project should now be live on Heroku. Run $ heroku open to open the project from terminal, or just run NAME.herokuapp.com in your browser. If you want to change your project name (and URL) or check certain properties of your database, you can do so on the Heroku settings page.
If anyone needs help, reach out to me!