Images not showing after deployment with Passenger/Capistrano to Nginx server - ruby-on-rails

Hi I'm deploying my first Rails app to Ubuntu 16 server using Capistrano everything went smooth except the images are not showing in the production environment.
On the production server the images are located in this path : /myapp/current/public/assets
But if I look at this in the browser my broken images links gives me this(see picture), this is a broken link for the header image.
the strange thing is that there is a .svgfile in the /myapp/current/public/assets which is showing up perfectly in the browser, In the picture below is the path shown
this is my Capfile
# Load DSL and set up stages
require "capistrano/setup"
# Include default deployment tasks
require "capistrano/deploy"
set :rbenv_type, :user # or :system, depends on your rbenv setup
set :rbenv_ruby, '2.3.1'
require 'capistrano/rbenv'
require 'capistrano/bundler'
require 'capistrano/rails'
# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }
This is the config/deploy.rb
# config valid only for current version of Capistrano
lock '3.6.1'
set :application, 'myapp'
set :repo_url, 'git#github.com:DadiHall/myapp.git'
# Default deploy_to directory is /var/www/my_app_name
set :deploy_to, '/home/deploy/myapp'
set :linked_files, %w{config/database.yml config/secrets.yml}
set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}
namespace :deploy do
desc 'Restart application'
task :restart do
on roles(:app), in: :sequence, wait: 5 do
execute :touch, release_path.join('tmp/restart.txt')
end
end
after :publishing, 'deploy:restart'
after :finishing, 'deploy:cleanup'
end
Here is the environments/production.rb
Rails.application.configure do
config.cache_classes = 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.assets.initialize_on_precompile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
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
Braintree::Configuration.environment = :sandbox
Braintree::Configuration.merchant_id = ENV['merchant_id']
Braintree::Configuration.public_key = ENV['public_key']
Braintree::Configuration.private_key = ENV['private_key']
end
In the /etc/nginx/sites-enabled/default I have following lines
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
server_name mydomain.com;
passenger_enabled on;
rails_env production;
root /home/deploy/myapp/current/public;
# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
this is the nginx Error log
[ 2016-09-28 06:25:02.4500 1594/7f900ee89700 age/Sha/ApiServerUtils.h:794 ]: Log file reopened.
[ 2016-09-28 09:45:43.7508 1597/7f2326502700 age/Cor/CoreMain.cpp:819 ]: Checking whether to disconnect long-running connections for process 1978, application /home/deploy/hlinreykdal/current/public (production)
App 21337 stdout:
App 21405 stdout:
[ 2016-09-28 10:30:31.0631 1597/7f2326502700 age/Cor/CoreMain.cpp:819 ]: Checking whether to disconnect long-running connections for process 21405, application /home/deploy/hlinreykdal/current/public (production)
App 23240 stdout:
App 23308 stdout:
[ 2016-09-28 10:41:40.1769 1597/7f2326502700 age/Cor/CoreMain.cpp:819 ]: Checking whether to disconnect long-running connections for process 23308, application /home/deploy/hlinreykdal/current/public (production)
App 24329 stdout:
App 24397 stdout:
I have tried bundle exec rake assets precompile with out any luck.
I have deployed and restarted nginx again and again, with out any luck
I have tried almost every answer to similar questions here on stack overflow, but nothing seems to work.
Am I missing something here?
I'm sure this problem has something to do with the assets pipeline, but I'm not sure how to fix it.
Can anyone please take a look at this and advise me.
thanks in advance

Ok if anyone is experiencing a similar problem you might want to check out the config.assets.compile In my case I only had to change the config/environments/production.rb config.assets.compile from false, I changed it to true and now everything worked.... It only took me two days to figure it out :D

Note that public/assets is where the asset pipeline puts its stuff. If this is for static assets, I would put them in app/assets/images in order to use the asset pipeline, or choose another directory name.

I was using html's img tag to serve image assets as following
<img src="/assets/AdminLTELogo.png" alt="AdminLTE Logo" class="brand-image im">
Just had to change it to following and it worked.
<%= image_tag 'AdminLTELogo.png' , alt: "AdminLTE Logo", class: "brand-image im %>
Cheers.

Related

Rails Production log dont update

I'm using Rails 6.0.3
In production I try to run a tail -f on the production log and I don't receive updates when I do any action on the application. Any idea?
I tried to apply 0644 permissions to the production.log file, but that's not the problem, because there is data in the file.
I am using nginx and puma too.
Production Log:
Production log file permissions
-rw-rw-r-- 1 ubuntu ubuntu 733 Apr 25 11:44 production.log
production.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
config.cache_store = :redis_cache_store, { url: "redis://localhost:6379/0" }
# Mount Action Cable outside main process or domain.
.....
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
............
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
Thanks in advance.
I solved my problem by adding these lines to my production file:
config.logger = Logger.new (Rails.root.join ("log / production.log"))
And restarting the cougar on the production server.

websocket-rails / puma: "async response must have empty headers and body"

I'm using websocket_rails to provide an API for a JS client. Locally it works great, but the exact same setup in production will (seemingly randomly) decide to stop working.
My production.log yields RuntimeError (eventmachine not initialized: evma_install_oneshot_timer)
At first I thought this was the root issue, but my Puma error log yields this when restart the server and try again: RuntimeError: async response must have empty headers and body
I added some logging in the puma gem, and indeed, it's receiving rails session headers when doing GET /websocket
Sometimes there is no issue at all, and everything works fine for a few days, and then, not. And no matter what I do it just refuses to work again.
Thanks in advance. I've wasted days on this problem!
Puma config:
# Change to match your CPU core count
workers 1
# Min and Max threads per worker
threads 1, 6
app_dir = File.expand_path("../..", __FILE__)
shared_dir = "#{app_dir}/shared"
# Default to production
rails_env = ENV['RAILS_ENV'] || "production"
environment rails_env
# Set up socket location
bind "unix://#{shared_dir}/sockets/puma.sock"
# Logging
stdout_redirect "#{shared_dir}/log/puma.stdout.log", "#{shared_dir}/log/puma.stderr.log", true
# Set master PID and state locations
pidfile "#{shared_dir}/pids/puma.pid"
state_path "#{shared_dir}/pids/puma.state"
activate_control_app
on_worker_boot do
require "active_record"
ActiveRecord::Base.connection.disconnect! rescue ActiveRecord::ConnectionNotEstablished
ActiveRecord::Base.establish_connection(YAML.load_file("#{app_dir}/config/database.yml")[rails_env])
end

Assets not compiling

This is driving me crazy - changes to css on my rails site only update when I run rake assets:precompile.
Does anyone know how to fix this, so assets will get compiled as they are changed?
I have a hunch the issue is in this config/environments/development.rb file:
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
config.assets.compile = true
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { :host => "http://localhost:3000/" }
# SMTP settings for gmail
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'gmail.com',
user_name: ENV['gmail_username'],
password: ENV['gmail_password'],
authentication: 'plain',
enable_starttls_auto: true
}
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
Here is the top of my assets/stylesheets/application.css file:
/*
* This is a manifest file that'll be compiled into application.css, which will include all the files
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
* or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
*
* You're free to add application wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any styles
* defined in the other CSS/SCSS files in this directory. It is generally better to create a new
* file per style scope.
*
*= require_tree .
*= require_self
*/
As well as the top of application.js:
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
Edit: I should add that this only became a problem once I removed bootstrap...
To solve the issue:
rake assets:clobber
OR
delete the public/assets folder
From the comments above: Assets not compiling

Rails, Nginx, Passenger, SSL - File Uploads Not Working

I am not able to get uploads to work with Passenger-Nginx and SSL. Uploads work fine if I disable SSL.
Here is my Nginx site config:
server {
listen 80;
server_name www.mysite.in;
root /home/deploy/mysite/current/public;
passenger_enabled on;
passenger_ruby /home/deploy/.rvm/gems/ruby-2.1.4/wrappers/ruby;
passenger_user deploy;
}
server {
listen 443 ssl;
server_name www.mysite.in;
root /home/deploy/mysite/current/public;
passenger_enabled on;
passenger_ruby /home/deploy/.rvm/gems/ruby-2.1.4/wrappers/ruby;
passenger_user deploy;
ssl on;
ssl_certificate /etc/nginx/ssl/www_mysite_in.crt;
ssl_certificate_key /etc/nginx/ssl/myserver.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
#Disables all weak ciphers
ssl_ciphers 'AES256+EECDH:AES256+EDH';
# Specifies that server ciphers should be preferred over client (e.g. browser) ciphers when using SSL/TLS.
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.4.4 8.8.8.8 valid=300s;
resolver_timeout 10s;
passenger_set_cgi_param HTTP_X_FORWARDED_PROTO https;
}
Any config/environments/production.rb
Mysite::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# config.action_mailer.delivery_method = :sendmail
end
I have tried disabling the config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' and it makes no difference under SSL or non-SSL.
I was never able to get this to work. So I just deleted the VPS image, and created a new one... and it works.
PS - I was using a setup script to install all the packages, so I am at a total loss as to why it didn't work with the original VPS image.

capistrano deploy from one local directory to another

I want to deploy application on my local machine. For example I have my Rails APP in:
/home/thesis/dev/myapp but I want to cap deploy:setup to /home/thesis/deploy/. I have tried that but capistrano tries to connect to localhost, but it is not needed at all. How can I solve it?
Here goes my deploy.rb
role :app, "localhost"
role :web, "localhost"
role :db, "localhost", :primary => true
set(:deploy_to) { "/home/thesis/dev/myapp" }
set :bundle_without, [:development, :test]
set :use_sudo, false
set :repository, "."
set :scm, :none
set :deploy_via, :copy
set :copy_dir, "/home/thesis/deploy/tmp"
set :copy_remote_dir, "/home/thesis/deploy/tmp"
It drops with:
connection failed for: localhost (Errno::ECONNREFUSED: Connection refused - connect(2))
The localhost issue is because you're setting this in the role definitions. Since you're doing all this locally, and since Capistrano requires a role, you can set the following:
role :app, ""
I also think you're setting the copy_dir and copy_remote_dir values incorrectly. I'd recommend removing these and letting Capistrano use it's defaults.
Here's a full config which should work for you:
role :app, ""
set :use_sudo, false
set :application, 'thesis' # you'll need to specify an app name
set :repository, "."
set :scm, :none
set :deploy_to, "/home/thesis/deploy/" # the destination dir
set :deploy_via, :copy
# override deploy:restart since this isn't a Rails app
namespace :deploy do
task :restart do
# no-op
end
end
Maybe you're missing a SSH server to connect on your on machine because you only have the client installed.
Test ssh 127.0.0.1, if you still get a connection refuse error, use:
sudo apt-get install openssh-server
To install the ssh server.
I also get this problem, for I had set SSH port to 13000, not the default port 22.
And the /etc/hosts.deny added
sshd:ALL
/etc/hosts.allow added
sshd:#some allowed IPs
I processing are:
1) add to deploy.rb
ssh_options[:port] = 13600
2) add localhost to hosts.allow
sshed:127.0.0.1 localhost # others allowed IPs
You need to have an ssh server installed for local deployment to work, such as openssh (sudo apt-get install openssh-server to install)
config/deploy/staging.rb
set :stage, :staging
role :app, %w{127.0.0.1}
role :web, %w{127.0.0.1}
role :db, %w{127.0.0.1}
server '127.0.0.1', user: 'your-username', roles: %w{web app}
set :branch, "staging"
config/deploy.rb
set :deploy_to ,'/home/your/app/path/deploy'
# Path of tests to be run, use array with empty string to run all tests
set :tests, ['']
namespace :deploy do
desc "Runs test before deploying, can't deploy unless they pass"
task :run_tests do
test_log = "log/capistrano.test.log"
tests = fetch(:tests)
tests.each do |test|
puts "--> Running tests: '#{test}', please wait ..."
unless system "bundle exec rspec #{test} > #{test_log} 2>&1"
puts "--> Aborting deployment! One or more tests in '#{test}' failed. Results in: #{test_log}"
exit;
end
puts "--> '#{test}' passed"
end
puts "--> All tests passed, continuing deployment"
system "rm #{test_log}"
end
# Only allow a deploy with passing tests to be deployed
before :deploy, "deploy:run_tests"
end
Run it with with
cap staging deploy

Resources