部署 docker 中,怎么把 assets:precompile 的结果,扔进 cdn 或云存储

lukefan · September 26, 2015 · Last by lukefan replied at October 06, 2015 · 3512 hits

我在 digitalocean 上部署了一个应用。 发现每次 js 和 css 都装载很慢。 于是想问问,如何才能实现,自动的将这些文件扔到七牛之类的国内云存储空间上去进行调用?

应用是部署在 digitalocean 主机的一个 docker 容器中的,每次 docker 容器刷新,会自动做 rake assets:precompile。 如何才能在下一步将这些文件自动的扔到七牛上,然后再在 layout 文件上调用这些资源?

七牛可以用它镜像功能,每次从源服务器抓取一次。Rails 里面 asset host 指向七牛的 CDN。

我是写了个 rake 脚本,每次 precompile 后再调用该脚本把 public 里面变动的文件传到七牛上去,config 里把 config.action_controller.asset_host 写成七牛的 url ,render 的时候生成的就是七牛的静态文件链接了

#2 楼 @embbnux 这个方法看起来要靠谱一点儿。 asset_host,具体些什么?完整地址吗?

七牛镜像

#3 楼 @lukefan 这个你可以参考 ruby china 的配置,在 config/env 下 config.action_controller.asset_host = Setting.cdn_url, 不过直接这么写 image_tag 这类出来的 url 都会变成在云储存服务器上的,如果要只限定 assets 目录解析到静态服务器上,可以这么写:

config.action_controller.asset_host = Proc.new { |source|
    if source =~ /assets/
      Settings.cdn_url
    else
      nil
    end
  }

不用上传,改一下 asset_host 就可以了,七牛自己会抓。

#4 楼 @chareice #1 楼 @rei #6 楼 @saiga

我现在使用七牛镜像了。不断是 assets 里面的文件,设置了这个值之后,所有图片都会自动转到七牛的域名,我现在准备加上一句:

link_to(resource.title, Rails.application.config.action_controller.asset_host.to_s + resource.torrent_url, {:download => resource.torrent_filename, :onclick => 'ahoy.track("Download Torrent", {title: "' + resource.torrent_filename + '"});'})

把所有东西都镜像上去,非常方便。

You need to Sign in before reply, if you don't have an account, please Sign up first.