Configure o BackBlaze S3 com BunnyCDN

Levou-me uma eternidade descobrir como fazer tudo isso, então quis criar este guia para facilitar a vida das pessoas. Servir suas imagens dessa forma deve fazer seu site carregar mais rápido. Minha configuração do Discourse combina um droplet da DigitalOcean, BackBlaze B2 S3, BunnyCDN e a versão gratuita do Cloudflare.

Escolhi esses serviços após pesquisar um pouco sobre confiabilidade, preços e benchmarks. Eles pareciam as melhores opções para mim. O Cloudflare ajuda na segurança, mas, pelo que entendi, também pode deixar o site um pouco mais lento, então vale a pena investigar isso. A Backblaze tem parcerias tanto com o Cloudflare quanto com o Bunny que permitem transferência de dados gratuita.

Embora o Cloudflare seja chamado de CDN, ele não funciona como os CDNs comuns e provavelmente não funcionará sozinho para configurar o S3 com o Discourse. Você pode precisar de outro provedor de CDN; o BunnyCDN funciona bem para mim. Se alguém conseguiu fazer isso apenas com o Cloudflare, me avise como :stuck_out_tongue:

Como configurar os uploads para o S3:
Primeiro, você precisa se cadastrar na Backblaze, criar buckets e inserir os detalhes nas configurações do Discourse:

Em seguida, cadastre-se no BunnyCDN e siga este guia:

bunny.net - The Global Edge Platform that truly Hops (link de indicação, ganho um crédito de 20 dólares na minha fatura)

Após criar sua zona de pull no BunnyCDN, você precisa obter a URL correta para inserir na configuração de backend do administrador do Discourse para “s3 cdn url”. Vá para o painel do BunnyCDN > pull zones > gerenciar zonas de pull > clique na sua zona > copie a URL ao lado de “host name”.

A URL deve se parecer com algo assim: example.b-cdn.net, mas você precisará garantir que coloque https:// na frente dela, assim: https://example.b-cdn.net

Salve as alterações na área de configurações de administrador do Discourse.

Pressione Ctrl+F5 duas vezes no seu navegador na página do seu site Discourse.

Faça um teste enviando uma imagem no editor de texto do Discourse. Inspeccione o elemento da imagem de teste ou visualize a fonte da imagem para garantir que funcionou. A URL deve ser diferente do seu domínio normal; deve ser algo como example.b-cdn.net / nome_do_arquivo

Agora, toda vez que alguém enviar uma imagem, ela ficará no seu bucket da Backblaze e não ocupará espaço no seu droplet da DigitalOcean :stuck_out_tongue:

Backup de Uploads para o S3
Se você quiser configurar os backups do Discourse para irem para o seu bucket da Backblaze, faça o seguinte:

No guia que postei mais acima neste tópico, preste atenção na explicação de que são necessários dois buckets separados. Um bucket é público; este é o seu bucket de uploads para que os usuários enviem imagens no seu fórum. O outro bucket é privado; este é o seu bucket de backups. É importante fazer backups automatizados do Discourse caso algo quebre, assim você poderá carregar seu backup e corrigir o problema.

No painel do BunnyCDN, crie uma segunda zona de pull. Sua primeira zona de pull era para uploads; esta nova zona de pull será para backups.

painel do bunnycdn > pull zones > adicionar zona de pull

Siga o mesmo guia que vinculei anteriormente, “Como acelerar a entrega de arquivos Backblaze B2 com o BunnyCDN” do BunnyCDN, mas desta vez vincule a nova zona de pull ao seu bucket de backups em vez do bucket de uploads.

Recomendo usar o “high volume tier 5$/TB” na página de criação da zona de pull do BunnyCDN. Acho que os backups não precisam do tier mais caro e rápido “standard tier 10$/TB” que usei para o bucket de uploads.

Configure suas opções de backup na área de configurações de administrador do Discourse. “backup location” deve ser definido como S3 e “s3 endpoint” deve apontar para o que você tem na Backblaze, algo assim:
s3.us-west-002.backblazeb2.com

Pressione Ctrl+F5 duas vezes no seu site para limpar o cache.

Inicie um backup e aguarde que ele termine. Em seguida, aguarde 5 minutos e verifique a pasta de backups da Backblaze; você deverá ver o novo backup lá.

Migrando Imagens Antigas:
Esta etapa é opcional, mas recomendada, especialmente se você estiver com pouco espaço de armazenamento no seu servidor. Então, você configurou tudo para novos uploads de imagens, mas as imagens antigas também podem ser transferidas para seus buckets. Para que esse processo funcione, siga o seguinte:

Configurando o CDN Cloudflare
Esta etapa é opcional, já que a Backblaze estabeleceu uma parceria que torna a transferência de dados para o Bunny gratuita também. No entanto, para segurança adicional e outros recursos, você pode fazer os dados passarem primeiro pelo Cloudflare e, em seguida, fazer o Bunny buscar os dados de onde o Cloudflare os deixa.

https://help.backblaze.com/hc/en-us/articles/217666928-Using-Backblaze-B2-with-the-Cloudflare-CDN

8 curtidas

Just wanted to say I have done what Bill did, and confirm it works! The only catch is that it works for new files and not the old ones. The cool thing about Bill’s method is that it didn’t even need a rebuild. However, I hope that someone figures out how to get the old files to work with S3 too.

Backups don’t work either btw. At least not for me and I did the same exact thing as Bill.

5 curtidas

You can migrate old files using the rake task.

1 curtida

If you mean this command, I already tried it and it didn’t upload the old assets:

sudo -E -u discourse bundle exec rake s3:upload_assets

I rebaked my posts too, but no dice.

The task is:

cd /var/discourse
./launcher enter app
rails c
rake uploads:migrate_to_s3
cd /var/discourse
./launcher enter app
rails c
rake uploads:migrate_from_s3

Does this work for you @AntiMetaman ?
I will add it to the guide if so.

I will try to figure out how to get backups to work correctly, and update the guide with that as well. I know for sure I need to make a second pull zone.

I have backups working fine with backblaze … What issue are you facing?

1 curtida

My backups are working fine with this method as well. You must have something set wrong. I will update the guide right now on how I set up backups. @AntiMetaman

I’m sorry, I don’t follow this? How come I have something working fine when you are suggesting that I have something set wrong?

He’s talking to me @itsbhanusharma. My backups aren’t working. My configuration is the same as Bill’s. I didn’t use a separate pull zone for the backup bucket though so maybe that’s why. I just have the name of the backup bucket in the env variables.

I’ll try Bhanu’s suggestion to migrate the s3 assets later.

I created two pull zones, one for each of the buckets (upload and backup). I started a backup from my admin panel but it failed. The only thing that Discourse knows is the name of the backup bucket.

DISCOURSE_S3_CDN_URL: https://duelistsunite.b-cdn.net
DISCOURSE_S3_BUCKET: s3omega
DISCOURSE_S3_BACKUP_BUCKET: s3omegabackup
DISCOURSE_BACKUP_LOCATION: s3

Not sure what I’m missing here. Is there a S3_CDN_BACKUP_URL ? given that the url is different for the backup.

@itsbhanusharma Also, I tried your method, but migrate_from_S3 is undefined.

Also, I wasn’t sure if you meant migrate_to_s3 so I tried that too, but that was also undefined.

I’m sorry for the confusion, I meant rake uploads:migrate_to_s3

1 curtida

It aborts the rake it seems because it adds the amazonaws.com to the url when in fact, that is incorrect. This is the problem. If you use a S3 that’s not amazon, then the rake won’t work since it’s hardcoded to change the url.

1 curtida

Can you confirm/deny if you added settings to the app.yml env section or did you add the settings to admin > settings page?

I have my backups working with S3 as well. So I have old and new uploads working with S3. I am using Cloudflare for SSL, DDoS, BunnyCDN for the upload and backup pull zones, and BackBlaze for the S3 storage. I’m all good now!

Note that it’s better to define the env variables in the app.yml as shown here: Using Object Storage for Uploads (S3 Clones)

Then rebuild so that the S3 configuration is globally defined and not just in admin panel. This way, when you migrate old files to s3, you can do it easier with 3 commands:

./launcher enter app
rake uploads:migrate_to_s3
rake posts:rebake

3 curtidas

Not sure what I’m missing here. Is there a S3_CDN_BACKUP_URL ? given that the url is different for the backup.

Did you resolve this question? I’m also not clear where to put the url for the pull zone that points to the backup bucket.

Edit: Am I correct in realizing that the CDN is only needed for the uploads bucket? The guide on this topic suggests a second CDN pull zone should be created for the backup bucket. If that’s wrong, perhaps the guide should be updated @Bill

Apparently it only needs the backup bucket name. From the name it can get the backup S3 url since it will be the same as the upload except for the name difference. This is why you don’t have to define a separate S3 backup url. This is of course assuming that both buckets are in the same S3 service.

But if the backup bucket is private, how would the CDN access it? I’m new to CDN’s and may be missing something, but I suspect that Discourse doesn’t use the CDN at all to back up.

They do. I went to my backup bucket and I see the backup uploaded there. It’s private but discourse can access it. You can setup permissions if the url is there. You can make it so only your site can access the bucket too or any https source.

Can you verify that the backup went through the CDN, vs directly from your Discourse install to BackBlaze B2?