Instala Discourse en CloudPanel

:warning: This installation method is not officially endorsed. Use at your own risk.

The Discourse team only recommend installation using the official install guide

:information_source: This is an unsupported install, appropriate for those who have experience with CloudPanel, are experienced system administrators, and comfortable with docker, reverse proxies, and have successfully completed a standard installation.

Why CloudPanel

Why might you want to install a Discourse Forum on a VPS or Dedicated Server running CloudPanel?

Here are my reasons:

I prefer to use a graphical interface for server and site administration. I’ve used most of the web hosting control panels at one time or another.

In comparison to the rest, CloudPanel is very slim and minimal and uncluttered. It has every feature I need, presented very simply and intuitively. And that’s it. It has nothing I don’t need.

I develop and host and manage many Ghost blogs, Wordpress sites, Drupal sites, and other types of sites in addition to Discourse forums. I really only need one server where I can host my Discourse forums right along side my Ghost Blogs and my Wordpress and Drupal sites. (I don’t want to pay for and maintain a separate server for each instance of Discourse.)

CloudPanel includes (right out-of-the-box) built-in Nginx and a simple interface for setting up and managing Reverse Proxies which are necessary in order to run one or more instances of Discourse on the same server or with other types of websites.

The Discourse team (and the Meta forum staff here) do not provide support for alternative server environments like Cpanel or Plesk or (as in this case) CloudPanel, or others that rise up out of the command line.

So I thought I’d share my setup and my process in case there are others who might find it useful.

[If anyone tries this method, please do let me know if/how it works out for you, or if I can improve this tutorial! :heart_eyes: ]

Install Docker

In Putty (or other terminal), from the root directory, run

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu focal stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt update
sudo apt-get install docker-ce docker-ce-cli docker-compose containerd.io

Create a Reverse Proxy Site in CloudPanel

→ We click the + Add Site button…

For my Discourse instance I am using my domain name noobish.me, so from now on wherever you see that in the rest of these instructions, replace noobish.me with your actual domain name (for example, yoursite.com)

→ We create a new “Reverse Proxy Site” in the CloudPanel for the domain where we want to host our Discourse forum (of course the DNS A record of the domain needs to be pointing to the same IP address as our CloudPanel.)

Prepare the Domain and Set up SSL

cloudflare-logo

For my site I’m using Cloudflare’s nameservers to point the domain. In Cloudflare I set the SSL to Full or Full (strict).

I also create a Cloudflare Page Rule. Visit this post to learn why.

I’m also using a free Cloudflare SSL Origin Certificate for my domain, which I “Import” into CloudPanel within the “SSL/TLS” site settings for that site (by simply pasting in both the Certificate and the Private Key I had downloaded for that domain name from my Cloudflare account.)

Install Discourse

Back in Putty (or other terminal), from the root directory (c d Enter to get back to the root) → Install the Discourse Standard Install using these commands…

git clone https://github.com/discourse/discourse_docker.git /var/discourse

Enter

cd /var/discourse

Enter

chmod 700 containers

Copy the Standalone Configuration

Now we copy the file /var/discourse/standalone.yml to /var/discourse/containers/ as app.yml before editing it according to our site settings.

cp /var/discourse/samples/standalone.yml /var/discourse/containers/app.yml

Edit the app.yml File

In addition to modifying the app.yml file according to our specific site settings, we need to change 3 more things in that file before we save it…

Under the section templates: we need to add

  - "templates/web.socketed.template.yml"

Because I’m using Cloudflare, under the section templates: I also add

  - "templates/cloudflare.template.yml"

Under the section expose: we need to comment out

  #- "80:80"   # http
  #- "443:443" # https

Under the section env: we need to add

   DISCOURSE_FORCE_HTTPS: true
For reference, you can Click Here to see the contents of my working app.yml on noobish.me where I'm using both Cloudflare and Mailgun...
## this is the all-in-one, standalone Discourse Docker container template
##
## After making changes to this file, you MUST rebuild
## /var/discourse/launcher rebuild app
##
## BE *VERY* CAREFUL WHEN EDITING!
## YAML FILES ARE SUPER SUPER SENSITIVE TO MISTAKES IN WHITESPACE OR ALIGNMENT!
## visit http://www.yamllint.com/ to validate this file as needed

templates:
  - "templates/postgres.template.yml"
  - "templates/redis.template.yml"
  - "templates/web.template.yml"
  - "templates/web.ratelimited.template.yml"
  - "templates/web.socketed.template.yml"
  - "templates/cloudflare.template.yml"

params:
  db_default_text_search_config: "pg_catalog.english"

  ## Set db_shared_buffers to a max of 25% of the total memory.
  ## will be set automatically by bootstrap based on detected RAM, or you can override
  db_shared_buffers: "4096MB"

  ## can improve sorting performance, but adds memory usage per-connection
  #db_work_mem: "40MB"

  ## Which Git revision should this container use? (default: tests-passed)
  #version: tests-passed

env:
  LC_ALL: en_US.UTF-8
  LANG: en_US.UTF-8
  LANGUAGE: en_US.UTF-8
  # DISCOURSE_DEFAULT_LOCALE: en

  DISCOURSE_FORCE_HTTPS: true

  ## How many concurrent web requests are supported? Depends on memory and CPU cores.
  ## will be set automatically by bootstrap based on detected CPUs, or you can override
  UNICORN_WORKERS: 8

  ## TODO: The domain name this Discourse instance will respond to
  ## Required. Discourse will not work with a bare IP number.
  DISCOURSE_HOSTNAME: 'noobish.me'

  ## Uncomment if you want the container to be started with the same
  ## hostname (-h option) as specified above (default "$hostname-$config")
  #DOCKER_USE_HOSTNAME: true

  ## TODO: List of comma delimited emails that will be made admin and developer
  ## on initial signup example 'user1@example.com,user2@example.com'
  DISCOURSE_DEVELOPER_EMAILS: 'admin@noobish.me'

  ## TODO: The SMTP mail server used to validate new accounts and send notifications
  # SMTP ADDRESS, username, and password are required
  # WARNING the char '#' in SMTP password can cause problems!
  DISCOURSE_SMTP_ADDRESS: smtp.mailgun.org
  DISCOURSE_SMTP_PORT: 587
  DISCOURSE_SMTP_USER_NAME: postmaster@noobish.me
  DISCOURSE_SMTP_PASSWORD:  pYdRLyQW
  #DISCOURSE_SMTP_ENABLE_START_TLS: true           # (optional, default true)
  #DISCOURSE_SMTP_DOMAIN: noobish.me    # (required by some providers)
  DISCOURSE_NOTIFICATION_EMAIL: noreply@noobish.me    # (address to send notifications from)

  ## The http or https CDN address for this Discourse instance (configured to pull)
  ## see https://meta.discourse.org/t/14857 for details
  #DISCOURSE_CDN_URL: https://discourse-cdn.example.com

  ## The maxmind geolocation IP address key for IP address lookup
  ## see https://meta.discourse.org/t/-/137387/23 for details
  #DISCOURSE_MAXMIND_LICENSE_KEY: 1234567890123456

## The Docker container is stateless; all data is stored in /shared
volumes:
  - volume:
      host: /var/discourse/shared/standalone
      guest: /shared
  - volume:
      host: /var/discourse/shared/standalone/log/var-log
      guest: /var/log

## Plugins go here
## see https://meta.discourse.org/t/19157 for details
hooks:
  after_code:
    - exec:
        cd: $home/plugins
        cmd:
          - git clone https://github.com/discourse/docker_manager.git

## Any custom commands to run after building
run:
  - exec: echo "Beginning of custom commands"
  ## If you want to set the 'From' email address for your first registration, uncomment and change:
  ## After getting the first signup email, re-comment the line. It only needs to run once.
  #- exec: rails r "SiteSetting.notification_email='info@unconfigured.discourse.org'"
  - exec: echo "End of custom commands"

Then we save and exit the app.yml file…

CTRL-X

y

Enter

Next we set the permissions for the app.yml file…

chmod o-rwx containers/app.yml

then…

Bootstrap the App

cd /var/discourse
./launcher bootstrap app

This will take a considerable amount of time. In the end of the bootstrap process, you’ll be asked to:

./launcher start app

Edit the Vhost File

Now we go back into our CloudPanel and paste the below code into the “Vhost Editor” for our Discourse site (overwriting what is already there). Of course replace yoursite.com with your actual domain name.

server {
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  {{ssl_certificate_key}}
  {{ssl_certificate}}
  server_name yoursite.com;
  {{root}}

  {{nginx_access_log}}
  {{nginx_error_log}}

  if ($scheme != "https") {
    rewrite ^ https://$host$uri permanent;
  }

  location ~ /.well-known {
    auth_basic off;
    allow all;
  }

  {{settings}}

  add_header Cache-Control no-transform;

  location / {
                proxy_pass http://unix:/var/discourse/shared/standalone/nginx.http.sock:;
                proxy_set_header Host $http_host;
                proxy_http_version 1.1;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header X-Real-IP $remote_addr;

  }
}

Restart Nginx

Next we need to restart Nginx, which we can do by clicking a button in the Admin Area of the CloudPanel…

Congratulations!

Now, in our browser, we can go to our site’s URL and run the Discourse Setup Wizard…

Cohabitate Peacefully

Now I can self-host and manage my Discourse site right along side my Ghost, Wordpress, Drupal and other types of sites using a clean and lean management panel, with minimal need going forward to use the terminal/command line.


To Install Additional Discourse Instances…

3 Me gusta

Deberías eliminar estos pasos y crear app.yml sin generar este error. Es confuso.

(Si vas a reemplazar todo el archivo, ¿por qué copiar el ejemplo?) Lo mejor sería decir qué se necesita cambiar del ejemplo existente. Parece que es la plantilla del socket y forzar https.

Esto te da dos copias de postgres, lo que usa más RAM que un solo postgres. Funciona, pero no es una buena práctica.

Hay una serie de cosas que hacen que este no sea un buen ejemplo a seguir y será muy difícil de mantener. Me alegra que hayas encontrado una solución para ti, pero no creo que este sea un buen camino para enviar a la gente.

3 Me gusta

Gracias @pfaffman

Tienes razón. Hace el trabajo, pero el procedimiento es demasiado engorroso. Está en el orden equivocado. Agradezco tus sugerencias y las arreglaré.

¿Podrías aclarar por qué piensas eso?

Porque es complicado y solo es una buena idea para las personas que pueden resolverlo por sí mismas. Es bastante ineficiente y, si el objetivo es solo ejecutar dos discursos, dos máquinas virtuales separadas son una solución más barata y fácil en la mayoría de los casos.

2 Me gusta

Gracias de nuevo @pfaffman. Ahora he simplificado el procedimiento y he eliminado la sección sobre cómo añadir un segundo sitio de Discourse en el mismo servidor.

1 me gusta

Recibí este mensaje

sudo apt update
sudo apt-get install docker-ce docker-ce-cli docker-compose containerd.io
uso: gpg [opciones] --dearmor [archivo]
curl: (23) Error al escribir el cuerpo

¿Por qué?

Hola Antonio. Bienvenido.

Esto parece un problema de Docker y no tiene que ver con Discourse. Probablemente te irá mejor buscando con tu sistema operativo y actualizando docker-ce que preguntando aquí.

¿Estás intentando usar Discourse? ¿O CloudPanel?

1 me gusta

Acabo de seguir la guía aquí. Ejecuté el primer comando, para la instalación de docker, y el servidor respondió esto
el comando es:

1 me gusta

No debería haber barras invertidas al final de cada una de esas líneas. La barra invertida escapa el salto de línea, lo que significa que el shell trata la siguiente línea como una continuación de la misma línea.

En este caso, eso resultará en intentar ejecutar esto como un solo comando, que es de donde proviene el error:
sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg echo \"deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu focal stable\"

Simplemente quitar esas barras invertidas al final de las líneas solucionará eso:

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo \"deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu focal stable\" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt update
sudo apt-get install docker-ce docker-ce-cli docker-compose containerd.io
2 Me gusta

Gracias, ahora funciona bien

2 Me gusta

Gracias @Simon_Manning – He eliminado las barras invertidas en el fragmento de código en el tutorial de la publicación principal.

2 Me gusta

Lo siento, ahora tengo este error: FAILED

Pups::ExecError: /usr/local/bin/ruby -e 'if ENV["DISCOURSE_SMTP_ADDRESS"] == "smtp.example.com"; puts "Aborting! Mail is not configured!"; exit 1; end' failed with return #<Process::Status: pid 112 exit 1>
Location of failure: /usr/local/lib/ruby/gems/3.2.0/gems/pups-1.1.1/lib/pups/exec_command.rb:117:in `spawn'
exec failed with the params "/usr/local/bin/ruby -e 'if ENV[\"DISCOURSE_SMTP_ADDRESS\"] == \"smtp.example.com\"; puts \"Aborting! Mail is not configured!\"; exit 1; end'"
bootstrap failed with exit code 1
** FAILED TO BOOTSTRAP ** please scroll up and look for earlier error messages, there may be more than one.
./discourse-doctor may help diagnose the problem.
214c73c4474ed59e7b6fb7f42143ce126d2b453022b08770da3af31ca2fdaaba

No conozco CloudPanel, pero los mensajes de error parecen ser autoexplicativos:

'if ENV["DISCOURSE_SMTP_ADDRESS"] == "smtp.example.com"; puts "Aborting! Mail is not configured!"; exit 1; end'
'if ENV[\"DISCOURSE_SMTP_ADDRESS\"] == \"smtp.example.com\"; puts \"Aborting! Mail is not configured!\"; exit 1; end'\"

Parece que tu correo electrónico no se configuró durante ./discourse-setup o dentro de app.yml (puedes editarlo manualmente en cualquier momento). :thinking:

2 Me gusta

Disculpen todos, soy profesor en la escuela secundaria Fermi y estoy intentando instalar Discourse Community para nuestra escuela. Dado que usamos paneles en la nube, seguí esta guía pero aparentemente falta algo. ¿Es posible obtener ayuda y una guía más detallada para seguir? Mil gracias.

1 me gusta

Creo que usar una instalación avanzada podría no ser lo que buscas si no tienes muchos conocimientos de administración de sistemas. Otro punto importante a considerar es que dicha instalación caería bajo unsupported-install, lo que hace menos probable que obtengas ayuda aquí si encuentras problemas.

Si tienes el presupuesto y dependiendo del tamaño de tu comunidad, podría ser mejor alojar Discourse en otro servidor y seguir la instalación estándar.

1 me gusta

Disculpe, ¿y para qué serviría un servicio como este? En mi opinión, quizás la guía no es muy detallada, está hecha para administradores de sistemas, bastaría con indicar simplemente los diversos pasos. De donde yo vengo se dice: nadie nace ya educado. Gracias por tu ayuda y tu tiempo.

1 me gusta

Exactamente. Por eso se recomendó la instalación estándar.

Y esto, @denvergeeks, es por lo que no pensé que crear una guía como esta fuera una buena idea en primer lugar. Es difícil de escribir, difícil de mantener, y tú eres la única persona que puede revisarla.

4 Me gusta

Lamento no estar de acuerdo. Ya utilizo Cloud Panel con varios dominios, además, la comunidad de Discourse iría en un subdominio y la premisa del autor es demasiado clara (la guía es para quienes usan Cloud Panel con diferentes servicios instalados en VPS). Solo se necesita un poco de esfuerzo para detallar mejor todo. Después de todo, compartir conocimiento es la base de las comunidades, de lo contrario, habría comprado un software que ya estuviera instalado y listo para usar. De todos modos, no quiero molestar a nadie, si es posible obtener ayuda, gracias, de lo contrario, no los molestaré más.

1 me gusta

@denvergeeks Configurar el correo electrónico es fundamental para el funcionamiento normal y, aunque hay un enlace a la instalación estándar, la forma en que está escrita la guía actualmente elude la configuración del correo electrónico, así como otra información diversa que podría ser importante para ciertas configuraciones.

Me pregunto si valdría la pena reemplazar las secciones Instalar Discourse hasta Arrancar la aplicación con algo más parecido a:

Instalar y configurar Discourse

Sigue la instalación estándar a través de los pasos 1-6

<Realiza las cosas que actualmente están en Editar el archivo app.yml>

Reconstruir Discourse:

./launcher rebuild app

Luego, en la sección ¡Felicitaciones!, agrega una línea después de la captura de pantalla que diga algo como “Continúa con el resto de la documentación de instalación estándar”. Esencialmente, rehacer la guía para proporcionar pasos adicionales que complementen la instalación estándar en lugar de proporcionar instrucciones de instalación alternativas.

Creo que la información que has proporcionado sobre CloudPanel es muy útil y las instrucciones son claras, el lado de Discourse podría beneficiarse de tener menos divergencia de la instalación estándar para hacerlo más seguro, así como la etiqueta unsupported-install para dejar claro (más claro) que aquí hay dragones.

2 Me gusta

[quote=“Antonio Cirillo, post:18, topic:266422, username:Antonio_Cirillo”]
Después de todo, compartir conocimientos es la base de las comunidades, de lo contrario habría comprado un software que ya estuviera instalado y listo para usar. De todos modos, no quiero molestar a nadie, si es posible obtener ayuda, gracias, de lo contrario no los molestaré más.
[/quote]La discusión se desvía un poco del tema original, pero ten la seguridad de que estamos encantados de ayudarte. :slight_smile:

En resumen:

Si tienes conocimientos básicos de informática, puedes seguir la instalación estándar. También necesitarás un nombre de dominio y configurar un servicio de envío de correo electrónico como Mailgun (tutorial aquí: Configure Mailgun for email when using Digital Ocean for DNS).

Ten en cuenta que normalmente no ayudamos en asuntos que están fuera del alcance de este foro. Por ejemplo, la pregunta “¿Cómo registro un nombre de dominio?” no encajaría aquí.

Si no tienes conocimientos básicos de informática y dependiendo de tu presupuesto, puedes solicitar soporte de pago en Marketplace.

Finalmente, también puedes echar un vistazo a los planes de pago gestionados por Discourse, donde prácticamente todo será manejado por nosotros y tendrás acceso a nuestro equipo de soporte.

Además, ten en cuenta que ofrecemos descuentos para fines educativos, ya que mencionas que es para tu escuela:

¿Hay descuentos para instituciones educativas o sin fines de lucro?

¡Sí! Si eres reconocido legalmente como una institución educativa, ofrecemos un descuento del 85%. Si eres reconocido legalmente como una organización sin fines de lucro exenta de impuestos federales, ofrecemos un descuento del 50%. Estos descuentos solo se aplican a nuestros planes básico, pro y business, no se pueden combinar con otros descuentos y deben pagarse con tarjeta de débito/crédito mensualmente o anualmente. Contáctanos después de comenzar tu prueba y agregaremos el descuento a tu cuenta.

4 Me gusta