0

Прошу прощения за вопрос, который кажется таким простым вопросом, который задают снова и снова.Рельсы статические изображения не отображаются

Я построил небольшое приложение, используя Rails 4.2.3. Все работает на местном уровне, так что я пытаюсь развернуть на AWS Elastic Beanstalk с и на следующие установки: 64-битную Amazon Linux 2016.03 v2.1.6 рубинового 2.3 (Puma)

Перед тем, как разворачивать я бегу:

rake assets:precompile RAILS_ENV=production 

I затем скопируйте эти файлы в git и используйте eb deploy, чтобы подтолкнуть файлы к экземпляру EC2.

Некоторые вещи работают:

  • Когда я SSH в этом случае, я вижу, все скомпилированных активов в/вар/приложение/текущие/государственные/активы
  • CSS все выглядит правильно
  • Coffeescripts работают нормально

Но, не статические изображения или те, которые я загружаю через Paperclip, выглядят так, как я ожидал.

В production.rb У меня есть эта строка:

config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? 

Я могу подтвердить, что ключ не в моей переменной ENV, перейдя в консоль:

irb(main):001:0> ENV['RAILS_SERVE_STATIC_FILES'] 
=> nil 

, что приводит меня к мысли, что обслуживание этих файлов должно выполняться nginx. Я могу подтвердить, что nginx работает, но, честно говоря, я не знаю, как он настроен.

[[email protected] assets]$ ps waux | grep nginx 
root  2800 0.0 0.4 109364 4192 ?  Ss Oct08 0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf 
nginx  2801 0.0 0.6 109820 6672 ?  S Oct08 0:09 nginx: worker process 
ec2-user 21321 0.0 0.2 110456 2092 pts/0 S+ 23:02 0:00 grep --color=auto nginx 

Я «думаю» я должен изменить мои .ebextensions файл, чтобы сделать несколько вещей автоматически при развертывании, но вот о том, где я застрял. Какие-либо предложения?

/etc/nginx/nginx.conf

# For more information on configuration, see: 
# * Official English Documentation: http://nginx.org/en/docs/ 
# * Official Russian Documentation: http://nginx.org/ru/docs/ 

user nginx; 
worker_processes auto; 
error_log /var/log/nginx/error.log; 
pid /var/run/nginx.pid; 

events { 
    worker_connections 1024; 
} 

http { 
    log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 
         '$status $body_bytes_sent "$http_referer" ' 
         '"$http_user_agent" "$http_x_forwarded_for"'; 

    access_log /var/log/nginx/access.log main; 

    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; 

    # Load modular configuration files from the /etc/nginx/conf.d directory. 
    # See http://nginx.org/en/docs/ngx_core_module.html#include 
    # for more information. 
    include /etc/nginx/conf.d/*.conf; 

    index index.html index.htm; 

    server { 
     listen  80 ; 
     listen  [::]:80 ; 
     server_name localhost; 
     root   /usr/share/nginx/html; 

     # Load configuration files for the default server block. 
     include /etc/nginx/default.d/*.conf; 

     location/{ 
     } 

     # redirect server error pages to the static page /40x.html 
     # 
     error_page 404 /404.html; 
      location = /40x.html { 
     } 

     # redirect server error pages to the static page /50x.html 
     # 
     error_page 500 502 503 504 /50x.html; 
      location = /50x.html { 
     } 

     # proxy the PHP scripts to Apache listening on 127.0.0.1:80 
     # 
     #location ~ \.php$ { 
     # proxy_pass http://127.0.0.1; 
     #} 

     # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 
     # 
     #location ~ \.php$ { 
     # root   html; 
     # fastcgi_pass 127.0.0.1:9000; 
     # fastcgi_index index.php; 
     # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; 
     # include  fastcgi_params; 
     #} 

     # deny access to .htaccess files, if Apache's document root 
     # concurs with nginx's one 
     # 
     #location ~ /\.ht { 
     # deny all; 
     #} 
    } 

# Settings for a TLS enabled server. 
# 
# server { 
#  listen  443 ssl; 
#  listen  [::]:443 ssl; 
#  server_name localhost; 
#  root   /usr/share/nginx/html; 
# 
#  ssl_certificate "/etc/pki/nginx/server.crt"; 
#  ssl_certificate_key "/etc/pki/nginx/private/server.key"; 
#  # It is *strongly* recommended to generate unique DH parameters 
#  # Generate them with: openssl dhparam -out /etc/pki/nginx/dhparams.pem 2048 
#  #ssl_dhparam "/etc/pki/nginx/dhparams.pem"; 
#  ssl_session_cache shared:SSL:1m; 
#  ssl_session_timeout 10m; 
#  ssl_protocols TLSv1 TLSv1.1 TLSv1.2; 
#  ssl_ciphers HIGH:SEED:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!RSAPSK:!aDH:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA:!SRP; 
#  ssl_prefer_server_ciphers on; 
# 
#  # Load configuration files for the default server block. 
#  include /etc/nginx/default.d/*.conf; 
# 
#  location/{ 
#  } 
# 
#  error_page 404 /404.html; 
#   location = /40x.html { 
#  } 
# 
#  error_page 500 502 503 504 /50x.html; 
#   location = /50x.html { 
#  } 
# } 

} 

/etc/nginx/conf.d/virtual.conf

# 
# A virtual host using mix of IP-, name-, and port-based configuration 
# 

#server { 
# listen  8000; 
# listen  somename:8080; 
# server_name somename alias another.alias; 

# location/{ 
#  root html; 
#  index index.html index.htm; 
# } 
#} 

/и т.д./Nginx/конф. d/webapp_healthd.conf

upstream my_app { 
    server unix:///var/run/puma/my_app.sock; 
} 

log_format healthd '$msec"$uri"' 
       '$status"$request_time"$upstream_response_time"' 
       '$http_x_forwarded_for'; 

server { 
    listen 80; 
    server_name _ localhost; # need to listen to localhost for worker tier 

    if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") { 
    set $year $1; 
    set $month $2; 
    set $day $3; 
    set $hour $4; 
    } 

    access_log /var/log/nginx/access.log main; 
    access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd; 

    location/{ 
    proxy_pass http://my_app; # match the name of upstream directive which is defined above 
    proxy_set_header Host $host; 
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
    } 

    location /assets { 
    alias /var/app/current/public/assets; 
    gzip_static on; 
    gzip on; 
    expires max; 
    add_header Cache-Control public; 
    } 

    location /public { 
    alias /var/app/current/public; 
    gzip_static on; 
    gzip on; 
    expires max; 
    add_header Cache-Control public; 
    } 
} 
+0

пожалуйста показать сайт, посвященный Nginx хоста конфигурации в местах с поддержкой – num8er

+0

я добавил/и т.д. /nginx/nginx.conf до конца сообщения. Если это не то, что вы искали, пожалуйста, сообщите нам об этом месте. –

+0

Это не то, что проверить файл в /etc/nginx/conf.d/, который имеет директиву сервера {}. Ваша проблема в том, что nginx не сервер вашей статической папки или, возможно, поиск неправильного пути. – num8er

ответ

2

Fix webapp_healthd.conf сделать Nginx для обслуживания файлов в public папке и если не может или они не существуют, то proxy_pass на Ваше приложение:

upstream my_app { 
    server unix:///var/run/puma/my_app.sock; 
} 

server { 
    listen 80; 
    server_name _; # need to listen to localhost for worker tier 

    if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") { 
    set $year $1; 
    set $month $2; 
    set $day $3; 
    set $hour $4; 
    } 

    access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd; 

    index index.html index.htm; 

    location @app { 
     log_not_found off; 
     access_log off; 
     proxy_pass http://my_app; # proxy passing to upstream 
     proxy_http_version 1.1; 
     proxy_set_header X-Real-IP $remote_addr; 
     proxy_set_header Host $host; 
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
     proxy_set_header Upgrade $http_upgrade; 
     proxy_set_header Connection 'upgrade'; 
     proxy_cache_bypass $http_upgrade; 
    } 

    root /var/app/current/public; 

    location/{ 
     try_files $uri $uri/ @app; # tries to serve static files if not will ask @app 
    } 
} 
+0

sudo service nginx stop/sudo vi webapp_healthd.conf/sudo service nginx start –

+0

Запуск nginx: nginx: [предупреждение] конфликтующее имя сервера «localhost» на 0.0.0.0:80, игнорируется –

+0

И теперь все пустое:) –

Смежные вопросы