Merge pull request #5696 from consuldemocracy/servers-docs

Update documentation for Production and Staging servers
This commit is contained in:
Sebastia
2024-09-30 19:19:06 +02:00
committed by GitHub
27 changed files with 306 additions and 383 deletions

View File

@@ -16,14 +16,14 @@
* [Windows](installation/windows.md) * [Windows](installation/windows.md)
* [Vagrant](installation/vagrant.md) * [Vagrant](installation/vagrant.md)
* [Docker](installation/docker.md) * [Docker](installation/docker.md)
* [Production and Staging servers](installation/servers.md) * [Production and staging servers](installation/servers.md)
* [Installer](installation/installer.md) * [Installer](installation/installer.md)
* [Create a deploy user](installation/create_deploy_user.md) * [Create a deploy user](installation/create_deploy_user.md)
* [Generating SSH Key](installation/generating_ssh_key.md) * [Generating SSH Key](installation/generating_ssh_key.md)
* [Manual installation (not recommended)](installation/manual_installation_production.md) * [Manual installation (not recommended)](installation/manual_installation_production.md)
* [Digital Ocean](installation/digital_ocean.md) * [Digital Ocean](installation/digital_ocean.md)
* [Heroku](installation/deploying-on-heroku.md) * [Heroku](installation/deploying-on-heroku.md)
* [Mail Server Configuration](installation/mail_server_configuration.md) * [Mail server configuration](installation/mail_server_configuration.md)
* [Basic configuration](installation/basic_configuration.md) * [Basic configuration](installation/basic_configuration.md)
* [User documentation and guides](installation/documentation_and_guides.md) * [User documentation and guides](installation/documentation_and_guides.md)

View File

@@ -2,13 +2,13 @@
[The installer](https://github.com/consuldemocracy/installer) by default connects as the `root` user only to create a `deploy` user. This `deploy` user is the one who installs all libraries. If you do not have `root` access, please ask your system administrator to follow these instructions to create a user manually. [The installer](https://github.com/consuldemocracy/installer) by default connects as the `root` user only to create a `deploy` user. This `deploy` user is the one who installs all libraries. If you do not have `root` access, please ask your system administrator to follow these instructions to create a user manually.
You could create a user called `deploy` or any other name. As as example, we are going to create a user named `jupiter`. You could create a user called `deploy` or any other name. **In this example, we are going to create a user named `jupiter`**.
```bash ```bash
adduser jupiter adduser jupiter
``` ```
I'm using jupiter as the user name, you should change that for whatever makes sense to you. Input a password when prompted, and just leave empty the rest of the options. **Remember to replace `jupiter` with whatever username makes sense for you**. Input a password when prompted, and leave the rest of the options empty.
Let's create a `wheel` group and add the user `jupiter` to this group. Let's create a `wheel` group and add the user `jupiter` to this group.
@@ -17,7 +17,9 @@ sudo groupadd wheel
sudo usermod -a -G wheel jupiter sudo usermod -a -G wheel jupiter
``` ```
Now let's give sudo privileges to the `wheel` group and allow it to not use a password, this is important so that the installer doesn't get stalled waiting for a password. **Remember to replace "jupiter" with the username you chose earlier.**
Now let's give sudo privileges to the `wheel` group and allow it to not use a password. This is important to ensure the installer doesn't stall waiting for a password.
First we open the sudoers file: First we open the sudoers file:
@@ -31,7 +33,7 @@ And we add this line at the end:
%wheel ALL=(ALL) NOPASSWD: ALL %wheel ALL=(ALL) NOPASSWD: ALL
``` ```
Now we need to give the keys of the server to the new user. Dont close the server terminal window, because you can lock yourself out of your server if there is a mistake. Now we need to give the keys of the server to the new user. Don't close the server terminal window, because you can lock yourself out of your server if there is a mistake.
Let's create the necessary directory in the server to upload the public key: Let's create the necessary directory in the server to upload the public key:
@@ -51,7 +53,7 @@ Open another local terminal window (not in the server) and type:
cat ~/.ssh/id_rsa.pub cat ~/.ssh/id_rsa.pub
``` ```
Copy the content of your public key to the file authorized_keys that should still be open in the server. Copy the content of your public key to the file `authorized_keys` that should still be open in the server.
Test that your user can log in by typing: Test that your user can log in by typing:
@@ -73,7 +75,7 @@ Type the following command to edit the SSH config file of the server:
sudo nano /etc/ssh/sshd_config sudo nano /etc/ssh/sshd_config
``` ```
Look for the "PasswordAuthentication yes" line and change it to "PasswordAuthentication no". Type Control-K to close the nano editor and type: Look for the "PasswordAuthentication yes" line and change it to "PasswordAuthentication no". Type `Control+X` to close the nano editor and type:
```bash ```bash
sudo service ssh restart sudo service ssh restart

View File

@@ -5,13 +5,13 @@
This tutorial assumes that you have already managed to clone Consul Democracy on your machine and gotten it to work. This tutorial assumes that you have already managed to clone Consul Democracy on your machine and gotten it to work.
1. First, create a [Heroku](https://www.heroku.com) account if it isn't already done. 1. First, create a [Heroku](https://www.heroku.com) account if it isn't already done.
2. Install the [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli) and sign in using 2. Install the [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli) and sign in using:
```bash ```bash
heroku login heroku login
``` ```
3. Go to your Consul Democracy repository and instantiate the process 3. Go to your Consul Democracy repository and instantiate the process:
```bash ```bash
cd consuldemocracy cd consuldemocracy
@@ -22,7 +22,7 @@ This tutorial assumes that you have already managed to clone Consul Democracy on
If _your-app-name_ is not already taken, Heroku should now create your app. If _your-app-name_ is not already taken, Heroku should now create your app.
4. Create a database using 4. Create a database using:
```bash ```bash
heroku addons:create heroku-postgresql heroku addons:create heroku-postgresql
@@ -30,19 +30,7 @@ This tutorial assumes that you have already managed to clone Consul Democracy on
You should now have access to an empty Postgres database whose address was automatically saved as an environment variable named _DATABASE\_URL_. Consul Democracy will automatically connect to it when deployed. You should now have access to an empty Postgres database whose address was automatically saved as an environment variable named _DATABASE\_URL_. Consul Democracy will automatically connect to it when deployed.
5. **(Not needed)** Add a file name _heroku.yml_ at the root of your project and paste the following in it 5. Now, generate a secret key and save it to an ENV variable named SECRET\_KEY\_BASE using:
```yml
build:
languages:
- ruby
packages:
- imagemagick
run:
web: bundle exec rails server -e ${RAILS_ENV:-production}
```
6. Now, generate a secret key and save it to an ENV variable named SECRET\_KEY\_BASE using
```bash ```bash
heroku config:set SECRET_KEY_BASE=$(rails secret) heroku config:set SECRET_KEY_BASE=$(rails secret)
@@ -70,48 +58,72 @@ This tutorial assumes that you have already managed to clone Consul Democracy on
**Remember not to commit the file if you have any sensitive information in it!** **Remember not to commit the file if you have any sensitive information in it!**
7. You can now push your app using 6. To ensure Heroku correctly detects and uses the node.js and ruby versions defined in the project, we need to make the following changes:
In package.json, add the node.js version:
```json
"engines": {
"node": "18.20.3"
}
```
and apply:
```bash
heroku buildpacks:add heroku/nodejs
```
In _Gemfile_, add the ruby version and run bundle:
```Gemfile
ruby file: ".ruby-version"
```
and apply:
```bash
heroku buildpacks:set heroku/ruby
```
7. You can now push your app using:
```bash ```bash
git push heroku your-branch:master git push heroku your-branch:master
``` ```
8. It won't work straight away because the database doesn't contain the tables needed. To create them, run 8. It won't work straight away because the database doesn't contain the tables needed. To create them, run:
```bash ```bash
heroku run rake db:migrate heroku run rake db:migrate
heroku run rake db:seed heroku run rake db:seed
``` ```
If you want to add the test data in the database, move `gem 'faker', '~> 1.8.7'` outside of `group :development` and run 9. Your app should now be ready to use. You can open it with:
```bash
heroku config:set DATABASE_CLEANER_ALLOW_REMOTE_DATABASE_URL=true
heroku config:set DATABASE_CLEANER_ALLOW_PRODUCTION=true
heroku run rake db:dev_seed
```
9. Your app should now be ready to use. You can open it with
```bash ```bash
heroku open heroku open
``` ```
You also can run the console on heroku using You also can run the console on Heroku using:
```bash ```bash
heroku console --app your-app-name heroku console --app your-app-name
``` ```
10. Heroku doesn't allow to save images or documents in its servers, so it's necessary to setup a permanent storage space. 10. Heroku doesn't allow saving images or documents in its servers, so it's necessary to setup a permanent storage space.
See [our S3 guide](./using-aws-s3-as-storage.md) for more details about configuring Paperclip with S3. See [our S3 guide](using-aws-s3-as-storage.md) for more details about configuring ActiveStorage with S3.
### Configure Sendgrid ### Configure Twilio Sendgrid
Add the SendGrid add-on in Heroku. It will create a SendGrid account for you with `ENV["SENDGRID_USERNAME"]` and `ENV["SENDGRID_PASSWORD"]`. Add the Twilio SendGrid add-on in Heroku. This will create a Twilio SendGrid account for the application with a username and allow you to create a password. This username and password can be stored in the applications environment variables on Heroku:
Add this to `config/secrets.yml`, under the `production:` section: ```bash
heroku config:set SENDGRID_USERNAME=example-username SENDGRID_PASSWORD=xxxxxxxxx
```
Now add this to `config/secrets.yml`, under the `production:` section:
```yaml ```yaml
mailer_delivery_method: :smtp mailer_delivery_method: :smtp
@@ -125,62 +137,4 @@ Add this to `config/secrets.yml`, under the `production:` section:
:enable_starttls_auto: true :enable_starttls_auto: true
``` ```
Important: Turn on one worker dyno so that emails get sent. **Important:** Turn on one worker dyno so that emails get sent.
## Optional but recommended
### Install rails\_12factor and specify the Ruby version
**The rails\_12factor is only useful if you use a version of Consul Democracy older than 1.0.0. The latter uses Rails 5 which includes the changes.**
As recommended by Heroku, you can add the gem rails\_12factor and specify the version of Ruby you want to use. You can do so by adding
```ruby
gem 'rails_12factor'
ruby 'x.y.z'
```
in the file _Gemfile\_custom_, where `x.y.z` is the version defined in the `.ruby-version` file in the Consul Democracy repository. Don't forget to run
```bash
bundle install
```
to generate _Gemfile.lock_ before committing and pushing to the server.
### Use Puma as a web server
Heroku recommends to use Puma to improve the responsiveness of your app on [a number of levels](http://blog.scoutapp.com/articles/2017/02/10/which-ruby-app-server-is-right-for-you).
If you want to allow more concurrency, uncomment the line:
```ruby
workers ENV.fetch("WEB_CONCURRENCY") { 2 }
```
You can find an explanation for each of these settings in the [Heroku tutorial](https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server).
The last part is to change the _web_ task to use Puma by changing it to this in your _heroku.yml_ file:
```yml
web: bundle exec puma -C config/puma.rb
```
### Add configuration variables to tune your app from the dashboard
The free and hobby versions of Heroku are barely enough to run an app like Consul Democracy. To optimise the response time and make sure the app doesn't run out of memory, you can [change the number of workers and threads](https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#workers) that Puma uses.
My recommended settings are one worker and three threads. You can set it by running these two commands:
```bash
heroku config:set WEB_CONCURRENCY=1
heroku config:set RAILS_MAX_THREADS=3
```
I also recommend to set the following:
```bash
heroku config:set RAILS_SERVE_STATIC_FILES=enabled
heroku config:set RAILS_ENV=production
```

View File

@@ -4,25 +4,23 @@ These instructions will help you register and buy a server in Digital Ocean to i
First you need to [sign up](https://cloud.digitalocean.com/registrations/new) and provide your personal information. First you need to [sign up](https://cloud.digitalocean.com/registrations/new) and provide your personal information.
Once you are logged in, you need to create a Droplet (thats the name that Digital Ocean uses for a Virtual Server). Click on the “Create” green button at the top of the page and select "Droplets": Once you have logged in, you'll need to create a Droplet (this is the name Digital Ocean uses for a cloud server) following this [guide](https://docs.digitalocean.com/products/droplets/how-to/create/) and configure it with the following recommendations:
![Digital Ocean Droplets](../../img/digital_ocean/droplets.png) ## Region
In the next page, you need to select Ubuntu (it should be pre-selected) and change the version **from 18.04 x64 to 16.04 x64**. In the "Choose Region" section, to avoid latency in the service, select the region that is geographically closest to your users.
![Digital Ocean Choose an image](../../img/digital_ocean/image.png) ## Image
In the "Choose a size" section select the **$80/mo 16GB/6CPUs** option if this is going to be a production server. If you are just setting up a test system with a few users the cheapest $5/mo option can be enough. In this "Choose an Image" section, we recommend selecting Ubuntu with the latest version supported by the installer, which in this case would be **24.04**.
![Digital Ocean Choose a size](../../img/digital_ocean/size.png) ## Size
Leave the rest of the options with their defaults until “Choose a datacenter”. Select the one that will be geographically closer to your users. If you are in the EU, select either Frankfurt or Amsterdam data centers. In the "Choose Size" section, if the goal is to create a production server, we recommend choosing an option with at least **16GB of RAM**. If you are setting up a testing system or a staging environment with just a few users, the cheapest option may be sufficient.
![Digital Ocean Choose a region](../../img/digital_ocean/region.png) ## Authentication
In the "Add you SSH keys" section click "New SSH Key" button. In the "Choose Authentication Method" section, select "SSH Key" and click the "New SSH Key" button to add your key.
![Digital Ocean Add your SSH Keys](../../img/digital_ocean/ssh_keys.png)
In the pop up window that appears you need to copy and paste the public key that we [generated in the previous step](generating_ssh_key.md). To see the content of this key in the terminal window type: In the pop up window that appears you need to copy and paste the public key that we [generated in the previous step](generating_ssh_key.md). To see the content of this key in the terminal window type:
@@ -36,24 +34,16 @@ You should see a text like this:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDy/BXU0OsK8KLLXpd7tVnqDU+d4ZS2RHQmH+hv0BFFdP6PmUbKdBDigRqG6W3QBexB2DpVcb/bmHlfhzDlIHJn/oki+SmUYLSWWTWuSeF/1N7kWf9Ebisk6hiBkh5+i0oIJYvAUsNm9wCayQ+i3U3NjuB25HbgtyjR3jDPIhmg1xv0KZ8yeVcU+WJth0pIvwq+t4vlZbwhm/t2ah8O7hWnbaGV/MZUcj0/wFuiad98yk2MLGciV6XIIq+MMIEWjrrt933wAgzEB8vgn9acrDloJNvqx25uNMpDbmoNXJ8+/P3UDkp465jmejVd/6bRaObXplu2zTv9wDO48ZpsaACP your_username@your_computer_name ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDy/BXU0OsK8KLLXpd7tVnqDU+d4ZS2RHQmH+hv0BFFdP6PmUbKdBDigRqG6W3QBexB2DpVcb/bmHlfhzDlIHJn/oki+SmUYLSWWTWuSeF/1N7kWf9Ebisk6hiBkh5+i0oIJYvAUsNm9wCayQ+i3U3NjuB25HbgtyjR3jDPIhmg1xv0KZ8yeVcU+WJth0pIvwq+t4vlZbwhm/t2ah8O7hWnbaGV/MZUcj0/wFuiad98yk2MLGciV6XIIq+MMIEWjrrt933wAgzEB8vgn9acrDloJNvqx25uNMpDbmoNXJ8+/P3UDkp465jmejVd/6bRaObXplu2zTv9wDO48ZpsaACP your_username@your_computer_name
``` ```
Select and copy all the text and paste it in the pop-up window like this: Select all the text, paste it into the pop-up window in the "SSH Key content" field, add a meaningful name such as **Consul_Democracy_key**, and click the Add SSH Key button.
![Digital Ocean New SSH Key](../../img/digital_ocean/new_ssh.png)
Please note that there will be two little green checks. If they are not there, retry copying the text because you probably left something out. Give your key a meaningful name, like **Consul_Democracy_key** and click "Add SSH Key" button.
By using an SSH key instead of a user/password combination to access your server, it will be much more secure, as only someone with the private SSH key can access the server. By using an SSH key instead of a user/password combination to access your server, it will be much more secure, as only someone with the private SSH key can access the server.
Now in the "Choose a hostname" section change the default for something more meaningful, like **consuldemocracyserver** for example. ## Hostname
![Digital Ocean hostname](../../img/digital_ocean/hostname.png) Now, in the "Finalize Details" section, change the default value of the Hostname field to something more meaningful, like **consuldemocracyserver**.
At the bottom of the page youll see a summary of your options. Check that everything is OK and click the big green "Create" button. At the bottom of the page youll see a summary of your options. Check that everything is OK and click the big green "Create" button.
![Digital Ocean create](../../img/digital_ocean/create.png)
It will take a few minutes, and at the end you will have a shiny new server. It will look like this in the Digital Ocean page: It will take a few minutes, and at the end you will have a shiny new server. It will look like this in the Digital Ocean page:
![Digital Ocean server](../../img/digital_ocean/server.png) Next to setup Consul Democracy in the server check the [installer's README](https://github.com/consuldemocracy/installer).
Next to setup Consul Democracy in the server check the [installer's README](https://github.com/consuldemocracy/installer)

View File

@@ -1,5 +1,5 @@
# Installer # Installer
## Installation notes for Production and Staging servers ## Installation notes for production and staging servers
Check out the [installer's README](https://github.com/consuldemocracy/installer). Check out the [installer's README](https://github.com/consuldemocracy/installer) for detailed installation instructions.

View File

@@ -1,26 +1,19 @@
# Mail Server Configuration # Mail server configuration
This is an example of how to integrate a mailing service with Consul Democracy. This is an example of how to integrate a mailing service with Consul Democracy.
In this example we use [Mailgun](https://www.mailgun.com/). ## Get an account from any email provider
## Create an account in Mailgun To configure email in Consul Democracy, you will need:
![Creating an account in Mailgun](../../img/mailserver/mailgun-create-account.png) * The _smtp_address_, which is the address of your email provider's SMTP server (e.g., smtp.yourdomain.com).
* The _domain_, which is the domain name of your application.
* The _user_name_ and _password_, which are the credentials provided by your email provider to authenticate with the SMTP server.
* Skip the credit card form ## Email configuration in Consul Democracy
* And activate your account with the link sent by email
## Domain configuration 1. Go to the `config/secrets.yml` file.
2. On this file, change these lines under the section `staging`, `preproduction` or `production`, depending on your setup:
* Go to the Domains section: ![Mailgun domain section](../../img/mailserver/mailgun-domains.png)
* Since you don't have a domain yet, you should click in the sandbox that is already created
* Remember the following credentials: ![Mailgun sandbox](../../img/mailserver/mailgun-sandbox.png)
## Consul Democracy mailing configuration
* Go to the `config/secrets.yml` file
* Change the lines on the file to configure the mail server under the section `staging`, `preproduction` or `production`, depending on your setup:
```yml ```yml
mailer_delivery_method: :smtp mailer_delivery_method: :smtp
@@ -34,5 +27,5 @@ In this example we use [Mailgun](https://www.mailgun.com/).
:enable_starttls_auto: true :enable_starttls_auto: true
``` ```
* Fill `<smtp address>`, `<domain>`, `<user_name>` and `<password>` with your information 3. Fill `<smtp address>`, `<domain>`, `<user_name>` and `<password>` with your information.
* Save the file and restart your Consul Democracy application 4. Save the file and restart your Consul Democracy application.

View File

@@ -1,8 +1,8 @@
# Manual installation for production # Manual installation for production
**WARNING:** This method is *not recommended* and not officially supported, since you should use the [installer](https://github.com/consuldemocracy/installer) instead. Use this method if the installer isn't an option and you can already deal with PostgreSQL, puma or passenger, NGNIX and SSL (with letsencrypt, for instance). **WARNING:** This method is *not recommended* and not officially supported, since you should use the [installer](https://github.com/consuldemocracy/installer) instead. Use this method only if the installer isn't an option and you have experience configuring PostgreSQL, Puma or Passenger, NGINX, and SSL (with letsencrypt, for instance).
This guide assumes you've already [installed all the necessary packages](prerequisites.md) on your system. This guide assumes you've already [installed all the necessary packages](prerequisites.md) on your system. Make sure to install RVM to be able to install the Ruby version required by the project, which is defined in the .ruby-version file. Also, ensure you have installed FNM to install the Node.js version defined in the .node-version file.
The created directory structure herein is to be used with [capistrano](https://capistranorb.com/documentation/getting-started/structure/). The created directory structure herein is to be used with [capistrano](https://capistranorb.com/documentation/getting-started/structure/).
@@ -21,22 +21,24 @@ mkdir -p shared/public/assets shared/public/system shared/public/ckeditor_assets
## Initial release ## Initial release
Extract from the repo the first release to the respective directory, and create the symbolic link of the current release (replace `<latest_consuldemocracy_stable_version>` with the latest version number, like 1.3.1 or 1.4.1): Extract from the repo the first release to the respective directory, and create the symbolic link of the current release. Be sure to replace `<latest_consuldemocracy_stable_version>` with the number of the latest stable version of Consul Democracy, such as 2.1.1 or 2.2.0. To find the most recent version, visit the releases section in the [Consul Democracy repository](https://github.com/consuldemocracy/consuldemocracy/releases)
```bash ```bash
mkdir releases/first
cd repo cd repo
git archive <latest_consuldemocracy_stable_version> | tar -x -f - -C ../releases/first git archive <latest_consuldemocracy_stable_version> | tar -x -f - -C ../releases/first
cd .. cd ..
ln -s releases/first current ln -s releases/first current
``` ```
## Gems installation ## Installing dependencies
Install the gems Consul Democracy depends on: Install the dependencies for Consul Democracy:
```bash ```bash
cd releases/first cd releases/first
bundle install --path ../../shared/bundle --without development test bundle install --path ../../shared/bundle --without development test
fnm exec npm install
cd ../.. cd ../..
``` ```
@@ -53,7 +55,7 @@ ln -s ../../../shared/config/secrets.yml
cd ../../.. cd ../../..
``` ```
Edit the `shared/config/database.yml` file, filling in `username` and `password` with the data generated during the [PostgreSQL setup](debian.md#postgresql-94). Edit the `shared/config/database.yml` file, filling in `username` and `password` with the data generated during the [PostgreSQL setup](debian.md#postgresql).
We now need to generate a secret key: We now need to generate a secret key:
@@ -78,6 +80,7 @@ Create a database, load the seeds and compile the assets:
```bash ```bash
cd current cd current
bin/rake db:create RAILS_ENV=production
bin/rake db:migrate RAILS_ENV=production bin/rake db:migrate RAILS_ENV=production
bin/rake db:seed RAILS_ENV=production bin/rake db:seed RAILS_ENV=production
bin/rake assets:precompile RAILS_ENV=production bin/rake assets:precompile RAILS_ENV=production

View File

@@ -1,21 +1,21 @@
# Production and Staging servers # Production and staging servers
## Recommended Minimum System Requirements ## Recommended minimum system requirements
### 1. Production Server ### 1. Production server
- Distribution: Ubuntu 16.04.X - Supported distributions: Ubuntu 22.04, Ubuntu 24.04, Debian Bullseye or Debian Bookworm
- RAM: 32GB - RAM: 32GB
- Processor: Quad core - Processor: Quad core
- Hard Drive: 20 GB - Hard Drive: 20 GB
- Database: Postgres - Database: Postgres
### 2. Staging Server ### 2. Staging server
- Distribution: Ubuntu 16.04.X - Supported distributions: Ubuntu 22.04, Ubuntu 24.04, Debian Bullseye or Debian Bookworm
- RAM: 16GB - RAM: 16GB
- Processor: Dual core - Processor: Dual core
- Hard Drive: 20 GB - Hard Drive: 20 GB
- Database: Postgres - Database: Postgres
If your city has a population of over 1.000.000, consider balancing your load using 2-3 production servers and a separate server for the database. If your city has a population of over 1,000,000, consider balancing your load using 2-3 production servers and a separate server for the database.

View File

@@ -1,87 +1,64 @@
# Using AWS S3 as file storage # Using AWS S3 as file storage
While Consul Democracy keeps most of its data in a PostgreSQL database, all the files such as documents or images have to be stored elsewhere. Although Consul Democracy stores most of its data in a PostgreSQL database, in Heroku all files, such as documents or images, must be stored elsewhere, such as AWS S3.
To take care of them, Consul Democracy uses the [Paperclip gem](https://github.com/thoughtbot/paperclip) (Warning: this gem is now deprecated and Consul Democracy will probably migrate to ActiveStorage in the future. Check that this is not already the case before using this guide).
By default, the attachments are stored on the filesystem. However, with services such as Heroku, there is no persistent storage which means that these files are periodically erased.
This tutorial explains how to configure Paperclip to use [AWS S3](https://aws.amazon.com/fr/s3/). It doesn't recommend S3 or the use of Amazon services and will hopefully be expanded to include configuration for [fog storage](http://fog.io/storage/).
## Adding the gem *aws-sdk-s3* ## Adding the gem *aws-sdk-s3*
First, add the following line in your *Gemfile_custom* Add the following line to your *Gemfile_custom*:
```ruby ```ruby
gem 'aws-sdk-s3', '~> 1' gem "aws-sdk-s3", "~> 1"
``` ```
Make sure to have a recent version of paperclip (Consul Democracy is currently using 5.2.1, which doesn't recognize *aws-sdk-s3*). In your Gemfile, the line should be: And run `bundle install` to apply your changes.
```ruby
gem 'paperclip', '~> 6.1.0'
```
Run `bundle install` to apply your changes.
## Adding your credentials in *secrets.yml* ## Adding your credentials in *secrets.yml*
This guide will assume that you have an Amazon account configured to use S3 and that you created a bucket for your instance of Consul Democracy. It is highly recommended to use a different bucket for each instance (production, preproduction, staging). This guide assumes you have an Amazon account configured to use S3 and that you have created a bucket for your instance of Consul Democracy. It is strongly recommended to use a different bucket for each instance (production, preproduction, staging).
You will need the following information: You will need the following information:
- the **name** of the S3 bucket - The **name** of the S3 bucket.
- the **region** of the S3 bucket (`eu-central-1` for UE-Francfort for example) - The **region** of the S3 bucket (`eu-central-1` for UE-Francfort for example).
- the **hostname** of the S3 bucket (`s3.eu-central-1.amazonaws.com` for Francfort, for example) - An **access_key** and a **secret_key** with read/write permission to that bucket.
- an **access key id** and a **secret access key** with read/write permission to that bucket
**WARNING:** It is recommended to create IAM users that will only have read/write permission to the bucket you want to use for that specific instance of Consul Democracy. **WARNING:** It is recommended to create IAM users (Identity and Access Management) who only have read/write permissions for the bucket you intend to use for that specific instance of Consul Democracy.
Once you have these pieces of information, you can save them as environment variables of the instance running Consul Democracy. In this tutorial, we save them respectively as *AWS_S3_BUCKET*, *AWS_S3_REGION*, *AWS_S3_HOSTNAME*, *AWS_ACCESS_KEY_ID* and *AWS_SECRET_ACCESS_KEY*. Once you have these pieces of information, you can save them as environment variables of the instance running Consul Democracy. In this tutorial, we save them respectively as *S3_BUCKET*, *S3_REGION*, *S3_ACCESS_KEY_ID* and *S3_SECRET_ACCESS_KEY*.
Add the following block in your *secrets.yml* file: ```bash
heroku config:set S3_BUCKET=example-bucket-name S3_REGION=eu-west-example S3_ACCESS_KEY_ID=xxxxxxxxx S3_SECRET_ACCESS_KEY=yyyyyyyyyy
```yaml
aws: &aws
aws_s3_region: <%= ENV["AWS_S3_REGION"] %>
aws_access_key_id: <%= ENV["AWS_ACCESS_KEY_ID"] %>
aws_secret_access_key: <%= ENV["AWS_SECRET_ACCESS_KEY"] %>
aws_s3_bucket: <%= ENV["AWS_S3_BUCKET"] %>
aws_s3_host_name: <%= ENV["AWS_S3_HOST_NAME"] %>
``` ```
and `<<: *aws` under the environments which you want to use S3 with, for example: Now add the following block to your *secrets.yml* file:
```yaml ```yaml
production: production:
[...] s3:
<<: *aws access_key_id: <%= ENV["S3_ACCESS_KEY_ID"] %>
secret_access_key: <%= ENV["S3_SECRET_ACCESS_KEY"] %>
region: <%= ENV["S3_REGION"] %>
bucket: <%= ENV["S3_BUCKET"] %>
``` ```
## Configuring Paperclip ## Enabling the use of S3 in the application
First, activate Paperclip's URI adapter by creating the file *config/initializers/paperclip.rb* with the following content: First, add the following line inside the `class Application < Rails::Application` class in the `config/application_custom.rb` file:
```ruby ```ruby
Paperclip::UriAdapter.register # Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :s3
``` ```
Finally, add the following lines in the environment file of the instance which you want to use S3 with. In production, you should for example edit *config/environments/production.rb*. Then, uncomment the s3 block that you will find in the *storage.yml* file:
```ruby ```yaml
# Paperclip settings to store images and documents on S3 s3:
config.paperclip_defaults = { service: S3
storage: :s3, access_key_id: <%= Rails.application.secrets.dig(:s3, :access_key_id) %>
preserve_files: true, secret_access_key: <%= Rails.application.secrets.dig(:s3, :secret_access_key) %>
s3_host_name: Rails.application.secrets.aws_s3_host_name, region: <%= Rails.application.secrets.dig(:s3, :region) %>
s3_protocol: :https, bucket: <%= Rails.application.secrets.dig(:s3, :bucket) %>
s3_credentials: {
bucket: Rails.application.secrets.aws_s3_bucket,
access_key_id: Rails.application.secrets.aws_access_key_id,
secret_access_key: Rails.application.secrets.aws_secret_access_key,
s3_region: Rails.application.secrets.aws_s3_region,
}
}
``` ```
You will need to restart to apply the changes. You will need to restart the application to apply the changes.

View File

@@ -1,27 +1,27 @@
# Crear un usuario para hacer la instalación # Crear un usuario para hacer la instalación
[El instalador](https://github.com/consuldemocracy/installer) de forma predeterminada se conecta como el usuario `root` sólo para crear un usuario `deploy`. Este usuario `deploy` es el que instala todas las librerías. Si no tiene acceso `root`, por favor pídale a su administrador de sistemas que siga estas instrucciones para crear un usuario manualmente. [El instalador](https://github.com/consuldemocracy/installer) de forma predeterminada se conecta como el usuario `root` sólo para crear un usuario `deploy`. Este usuario `deploy` es el que instala todas las librerías. Si no tienes acceso `root`, por favor pide a tu administrador de sistemas que siga estas instrucciones para crear un usuario manualmente.
Puede crear un usuario llamado `deploy` o utilizar cualquier otro nombre. Como ejemplo, vamos a crear un usuario llamado `jupiter`. Puedes crear un usuario llamado `deploy` o utilizar cualquier otro nombre. **En este ejemplo, vamos a crear un usuario llamado `jupiter`**.
```bash ```bash
adduser jupiter adduser jupiter
``` ```
Estoy usando jupiter como nombre de usuario, debería cambiar eso por lo que sea que tenga sentido para usted. Introduzca una contraseña cuando se le pida y deje vacías el resto de las opciones. **Recuerda cambiar "jupiter" por el nombre de usuario que elijas.** Introduce una contraseña cuando se te pida y deja vacías el resto de las opciones.
Creemos un grupo `wheel` y añadamos al usuario `jupiter` al grupo. Ahora, crearemos un grupo `wheel` y añadiremos al usuario `jupiter` al grupo.
```bash ```bash
sudo groupadd wheel sudo groupadd wheel
sudo usermod -a -G wheel jupiter sudo usermod -a -G wheel jupiter
``` ```
**Recuerde cambiar jupiter** por cualquier nombre de usuario que haya elegido en el paso anterior. **Recuerda cambiar "jupiter" por cualquier nombre de usuario que hayas elegido en el paso anterior.**
Ahora démosle al grupo `wheel` derechos de superadministración sin necesidad de usar contraseña, esto es importante para que el instalador no se quede parado esperando una contraseña. A continuación, configuraremos el grupo `wheel` para que tenga derechos de superadministración sin necesidad de usar contraseña. **Esto es importante para que el instalador no se quede esperando una contraseña.**
Primero debemos abrir el archivo `sudoers`: Primero, debemos abrir el archivo `sudoers`:
```bash ```bash
sudo visudo -f /etc/sudoers sudo visudo -f /etc/sudoers
@@ -33,9 +33,9 @@ Y añadimos esta línea al final del archivo:
%wheel ALL=(ALL) NOPASSWD: ALL %wheel ALL=(ALL) NOPASSWD: ALL
``` ```
Ahora tenemos que dar las claves del servidor al nuevo usuario. No cierre la ventana de la terminal del servidor, porque puede bloquearse si hay un error. Ahora tenemos que dar las claves del servidor al nuevo usuario. No cierres la ventana de la terminal del servidor, porque puedes bloquearte si hay un error.
Y escriba los siguientes comandos para crear el archivo necesario donde subir la clave pública: Escribe los siguientes comandos para crear el archivo necesario donde subir la clave pública:
```bash ```bash
su jupiter su jupiter
@@ -45,37 +45,37 @@ cd .ssh
nano authorized_keys nano authorized_keys
``` ```
Asegúrese que ha [generado una clave pública](generating_ssh_key.md) en su terminal local. Asegúrate de que has [generado una clave pública](generating_ssh_key.md) en tu terminal local.
Abra otra ventana de terminal local (no en el servidor) y escriba: Abre otra ventana de terminal local (no en el servidor) y escribe:
```bash ```bash
cat ~/.ssh/id_rsa.pub cat ~/.ssh/id_rsa.pub
``` ```
Copie el contenido de ese comando al archivo `authorized_keys` que debería seguir abierto en el servidor. Copia el contenido de ese comando al archivo `authorized_keys` que debería seguir abierto en el servidor.
Compruebe que su usuario puede iniciar sesión escribiendo: Comprueba que el usuario puede iniciar sesión escribiendo:
```bash ```bash
ssh jupiter@your-copied-ip-address ssh jupiter@your-copied-ip-address
``` ```
Debería ver la página de bienvenida del servidor y un mensaje como este: Deberías ver la página de bienvenida del servidor y un mensaje como este:
```bash ```bash
jupiter@consuldemocracyserver:~$ jupiter@consuldemocracyserver:~$
``` ```
Note que el nombre de usuario en el prompt no es "root", sino su nombre de usuario. Así que todo está bien y ahora podemos bloquear la cuenta root del acceso externo y también dejar de permitir el acceso con contraseña para que sólo las personas con claves SSH puedan iniciar sesión. Nota que el nombre de usuario en el prompt no es `root`, sino el nombre de usuario que elegiste, lo que indica que todo está bien. Ahora podemos bloquear la cuenta `root` del acceso externo y también dejar de permitir el acceso con contraseña para que sólo las personas con claves SSH puedan iniciar sesión.
Escriba el siguiente comando para editar el archivo de configuración SSH del servidor: Escribe el siguiente comando para editar el archivo de configuración SSH del servidor:
```bash ```bash
sudo nano /etc/ssh/sshd_config sudo nano /etc/ssh/sshd_config
``` ```
Busque la línea "PasswordAuthentication yes" y cámbiela por "PasswordAuthentication no". Escriba Control-K para cerrar el editor nano y escriba: Busca la línea "PasswordAuthentication yes" y cámbiala por "PasswordAuthentication no". Escribe `Control+X` para cerrar el editor nano y escribe:
```bash ```bash
sudo service ssh restart sudo service ssh restart

View File

@@ -11,7 +11,7 @@ Este tutorial asume que ya has conseguido clonar Consul Democracy en tu máquina
heroku login heroku login
``` ```
3. Accede a tu repositorio de Consul Democracy y crea una instancia 3. Accede a tu repositorio de Consul Democracy y crea una instancia:
```bash ```bash
cd consuldemocracy cd consuldemocracy
@@ -22,7 +22,7 @@ Este tutorial asume que ya has conseguido clonar Consul Democracy en tu máquina
Si _your-app-name_ no existe aún, Heroku creará tu aplicación. Si _your-app-name_ no existe aún, Heroku creará tu aplicación.
4. Crea la base de datos con 4. Crea la base de datos con:
```bash ```bash
heroku addons:create heroku-postgresql heroku addons:create heroku-postgresql
@@ -30,19 +30,7 @@ Este tutorial asume que ya has conseguido clonar Consul Democracy en tu máquina
Ahora deberías tener acceso a una base de datos Postgres vacía cuya dirección se guardó automáticamente como una variable de entorno llamada _DATABASE\_URL_. Consul Democracy se conectará automáticamente a ella durante la instalación. Ahora deberías tener acceso a una base de datos Postgres vacía cuya dirección se guardó automáticamente como una variable de entorno llamada _DATABASE\_URL_. Consul Democracy se conectará automáticamente a ella durante la instalación.
5. **(No es necesario)** Crea un archivo con el nombre _heroku.yml_ en la raíz del proyecto y añade el siguiente código 5. Ahora, genera una clave secreta y guárdala en la variable de entorno SECRET\_KEY\_BASE de la siguiente manera:
```yml
build:
languages:
- ruby
packages:
- imagemagick
run:
web: bundle exec rails server -e ${RAILS_ENV:-production}
```
6. Ahora, genera una clave secreta y guárdala en la variable de entorno SECRET\_KEY\_BASE de la siguinte manera
```bash ```bash
heroku config:set SECRET_KEY_BASE=$(rails secret) heroku config:set SECRET_KEY_BASE=$(rails secret)
@@ -70,28 +58,48 @@ Este tutorial asume que ya has conseguido clonar Consul Democracy en tu máquina
**¡Recuerda no añadir el archivo si tienes información sensible en él!** **¡Recuerda no añadir el archivo si tienes información sensible en él!**
6. Para que Heroku detecte y utilice correctamente las versiones de node.js y ruby definidas en el proyecto deberemos añadir los siguientes cambios:
En el _package.json_ añadir la versión de node.js:
```json
"engines": {
"node": "18.20.3"
}
```
y aplicar:
```bash
heroku buildpacks:add heroku/nodejs
```
En el _Gemfile_ añadir la versión de ruby y ejecutar bundle:
```Gemfile
ruby file: ".ruby-version"
```
y aplicar:
```bash
heroku buildpacks:set heroku/ruby
```
7. Ahora ya puedes subir tu aplicación utilizando: 7. Ahora ya puedes subir tu aplicación utilizando:
```bash ```bash
git push heroku your-branch:master git push heroku your-branch:master
``` ```
8. No funcionará de inmediato porque la base de datos no contiene las tablas necesarias. Para crearlas, ejecuta 8. No funcionará de inmediato porque la base de datos no contiene las tablas necesarias. Para crearlas, ejecuta:
```bash ```bash
heroku run rake db:migrate heroku run rake db:migrate
heroku run rake db:seed heroku run rake db:seed
``` ```
Si quieres añadir los datos de prueba en la base de datos, mueve `gem 'faker', '~> 1.8.7'` fuera del `group :development` y ejecuta: 9. Ahora tu aplicación debería estar ya operativa. Puedes abrirla con:
```bash
heroku config:set DATABASE_CLEANER_ALLOW_REMOTE_DATABASE_URL=true
heroku config:set DATABASE_CLEANER_ALLOW_PRODUCTION=true
heroku run rake db:dev_seed
```
9. Ahora tu aplicación debería estar ya opertaiva. Puedes abrirla con
```bash ```bash
heroku open heroku open
@@ -105,13 +113,17 @@ Este tutorial asume que ya has conseguido clonar Consul Democracy en tu máquina
10. Heroku no permite guardar imágenes o documentos en sus servidores, por lo que es necesario configurar un nuevo espacio de almacenamiento. 10. Heroku no permite guardar imágenes o documentos en sus servidores, por lo que es necesario configurar un nuevo espacio de almacenamiento.
Consulta [nuestra guía de S3](./using-aws-s3-as-storage.md) para más detalles sobre la configuración de Paperclip con S3. Consulta [nuestra guía de S3](using-aws-s3-as-storage.md) para más detalles sobre la configuración de ActiveStorage con S3.
### Configurar Sendgrid ### Configurar Twilio SendGrid
Añade el complemento (add-on) de SendGrid en Heroku. Esto creará una cuenta de SendGrid para la aplicación con `ENV["SENDGRID_USERNAME"]` y `ENV["SENDGRID_PASSWORD"]`. Añade el complemento (_add-on_) de Twilio SendGrid en Heroku. Esto creará una cuenta en Twilio SendGrid para la aplicación con un nombre de usuario y permitirá crear una contraseña. Este usuario y contraseña lo podemos guardar en las variables de entorno de la aplicación en Heroku:
Añade el siguiente código a `config/secrets.yml`, en la sección `production:`: ```bash
heroku config:set SENDGRID_USERNAME=example-username SENDGRID_PASSWORD=xxxxxxxxx
```
Ahora añade el siguiente código a `config/secrets.yml`, en la sección `production:`:
```yaml ```yaml
mailer_delivery_method: :smtp mailer_delivery_method: :smtp
@@ -125,62 +137,4 @@ Añade el siguiente código a `config/secrets.yml`, en la sección `production:`
:enable_starttls_auto: true :enable_starttls_auto: true
``` ```
Importante: Activa un "worker dyno" para que se envíen los correos electrónicos. **Importante:** Activa un "_worker dyno_" para que se envíen los correos electrónicos.
### Opcional (pero recomendado)
### Instalar rails\_12factor y especificar la versión de Ruby
**Instalar rails\_12factor sólo es útil si utilizas una versión de Consul Democracy anterior a la 1.0.0. La última versión utiliza Rails 5 que ya incluye los cambios.**
Como nos recomienda Heroku, puedes añadir la gema rails\_12factor y especificar la versión de Ruby a utilizar. Puedes hacerlo añadiendo:
```ruby
gem 'rails_12factor'
ruby 'x.y.z'
```
en el archivo _Gemfile\_custom_, donde `x.y.z` es la versión definida en el fichero `.ruby-version` del repositorio de Consul Democracy. No olvides ejecutar
```bash
bundle install
```
para generar el _Gemfile.lock_ antes de añadir los cambios y subirlos al servidor.
### Utilizar Puma como servidor web
Heroku recomienda utilizar Puma para mejorar el [rendimiento](http://blog.scoutapp.com/articles/2017/02/10/which-ruby-app-server-is-right-for-you) de la aplicación.
Si quieres permitir más concurrencia, descomenta la siguiente linea:
```ruby
workers ENV.fetch("WEB_CONCURRENCY") { 2 }
```
Puedes encontrar una explicación para diferentes configuraciones en el siguiente [tutorial de Heroku](https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server).
Por último hay que cambiar la tarea _web_ para usar Puma cambiándola en el archivo _heroku.yml_ con el siguiente código:
```yml
web: bundle exec puma -C config/puma.rb
```
### Añadir variables de configuración desde el panel de control
Las versiones gratuita y hobby de Heroku no son suficientes para ejecutar una aplicación como Consul Democracy. Para optimizar el tiempo de respuesta y asegurarte de que la aplicación no se quede sin memoria, puedes [cambiar el número de "workers" e hilos](https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#workers) que utiliza Puma.
La configuración recomendada es un "worker" y tres hilos. Puedes configurarlo ejecutando estos dos comandos:
```bash
heroku config:set WEB_CONCURRENCY=1
heroku config:set RAILS_MAX_THREADS=3
```
También es recomendable configurar las siguientes variables:
```bash
heroku config:set RAILS_SERVE_STATIC_FILES=enabled
heroku config:set RAILS_ENV=production
```

View File

@@ -1,59 +1,49 @@
# Instalando Consul Democracy en un VPS de Digital Ocean # Instalando Consul Democracy en un VPS de Digital Ocean
Estas instrucciones le ayudaran a registrarse y comprar un servidor en Digital Ocean para instalar Consul Democracy. Estas instrucciones te ayudarán a registrarte y comprar un servidor en Digital Ocean para instalar Consul Democracy.
Primero necesita [registrarse](https://cloud.digitalocean.com/registrations/new) y proporcionar su información personal. Primero necesitas [registrarte](https://cloud.digitalocean.com/registrations/new) y proporcionar tu información personal.
Una vez que haya iniciado sesión, deberá crear un Droplet (ese es el nombre que Digital Ocean utiliza para un Servidor Virtual). Haga clic en el botón verde "Crear" en la parte superior de la página y seleccione "Droplets": Una vez que hayas iniciado sesión, deberás crear un _Droplet_ (este es el nombre que Digital Ocean utiliza para un servidor en la nube) siguiendo esta [guía](https://docs.digitalocean.com/products/droplets/how-to/create/) y configurarlo teniendo en cuenta los siguientes consejos:
![Digital Ocean Droplets](../../img/digital_ocean/droplets.png) ## Región
En la página siguiente, debe seleccionar Ubuntu (debería estar preseleccionado) y cambiar la versión **de 18.04 x64 a 16.04 x64**. Para evitar latencia en el servicio, selecciona la región que esté geográficamente más cerca de vuestros usuarios.
![Digital Ocean Choose an image](../../img/digital_ocean/image.png) ## Imagen
En la sección "Elegir un tamaño" seleccione la opción **$80/mo 16GB/6CPUs** si va a ser un servidor de producción. Si está configurando un sistema de prueba con unos pocos usuarios, la opción más barata de $5/mes puede ser suficiente. En esta sección recomendamos seleccionar ubuntu con la última versión soportada por el instalador, que en este caso sería la **24.04**.
![Digital Ocean Choose a size](../../img/digital_ocean/size.png) ## Tamaño
Deje el resto de las opciones con sus valores por defecto hasta "Elegir un centro de datos". Seleccione el que esté geográficamente más cerca de sus usuarios. Si se encuentra en la UE, seleccione los centros de datos de Frankfurt o Amsterdam. En la sección "Elegir un tamaño" si el objetivo es crear un servidor para producción recomendamos elegir una opción que al menos tenga **16GB de RAM**. Si por el contrario estás configurando un sistema de pruebas o un entorno de staging con unos pocos usuarios, la opción más barata puede ser suficiente.
![Digital Ocean Choose a region](../../img/digital_ocean/region.png) ## Autenticación
En la sección "Añadir claves SSH" pulse el botón "Nueva clave SSH". En la sección "Elegir un método de autenticación" seleccionaremos _SSH Key_ y pulsaremos el botón _New SSH Key_ para añadir nuestra clave
![Digital Ocean Add your SSH Keys](../../img/digital_ocean/ssh_keys.png) En la ventana emergente que aparece es necesario copiar y pegar la clave pública que [generamos en el paso anterior](generating_ssh_key.md). Para ver el contenido de esta clave en la ventana del terminal, escribe:
En la ventana emergente que aparece es necesario copiar y pegar la clave pública que [generamos en el paso anterior](generating_ssh_key.md). Para ver el contenido de esta clave en la ventana del terminal, escriba:
```bash ```bash
cat ~/.ssh/id_rsa.pub cat ~/.ssh/id_rsa.pub
``` ```
Debería ver un texto como este: Deberías ver un texto como este:
```text ```text
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDy/BXU0OsK8KLLXpd7tVnqDU+d4ZS2RHQmH+hv0BFFdP6PmUbKdBDigRqG6W3QBexB2DpVcb/bmHlfhzDlIHJn/oki+SmUYLSWWTWuSeF/1N7kWf9Ebisk6hiBkh5+i0oIJYvAUsNm9wCayQ+i3U3NjuB25HbgtyjR3jDPIhmg1xv0KZ8yeVcU+WJth0pIvwq+t4vlZbwhm/t2ah8O7hWnbaGV/MZUcj0/wFuiad98yk2MLGciV6XIIq+MMIEWjrrt933wAgzEB8vgn9acrDloJNvqx25uNMpDbmoNXJ8+/P3UDkp465jmejVd/6bRaObXplu2zTv9wDO48ZpsaACP your_username@your_computer_name ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDy/BXU0OsK8KLLXpd7tVnqDU+d4ZS2RHQmH+hv0BFFdP6PmUbKdBDigRqG6W3QBexB2DpVcb/bmHlfhzDlIHJn/oki+SmUYLSWWTWuSeF/1N7kWf9Ebisk6hiBkh5+i0oIJYvAUsNm9wCayQ+i3U3NjuB25HbgtyjR3jDPIhmg1xv0KZ8yeVcU+WJth0pIvwq+t4vlZbwhm/t2ah8O7hWnbaGV/MZUcj0/wFuiad98yk2MLGciV6XIIq+MMIEWjrrt933wAgzEB8vgn9acrDloJNvqx25uNMpDbmoNXJ8+/P3UDkp465jmejVd/6bRaObXplu2zTv9wDO48ZpsaACP your_username@your_computer_name
``` ```
Seleccione y copie todo el texto y péguelo en la ventana emergente de la siguiente manera: Selecciona todo el texto, pégalo en la ventana emergente en el campo _SSH Key content_, añade un nombre significativo como por ejemplo **Consul_Democracy_key** y clica sobre el botón _Add SSH Key_.
![Digital Ocean New SSH Key](../../img/digital_ocean/new_ssh.png) Al utilizar una clave SSH en lugar de una combinación de usuario/contraseña para acceder a tu servidor, será mucho más seguro, ya que sólo alguien con la clave privada SSH puede acceder al servidor.
Tenga en cuenta que habrá dos pequeños checks verdes. Si no están ahí, vuelva a intentar copiar el texto porque probablemente omitió algo. Dé a su clave un nombre significativo, como **Consul_Democracy_key** y haga clic en el botón "Add SSH Key" (Añadir clave SSH). ## Nombre del host
Al utilizar una clave SSH en lugar de una combinación de usuario/contraseña para acceder a su servidor, será mucho más seguro, ya que sólo alguien con la clave privada SSH puede acceder al servidor. Ahora en la sección "Ultimar detalles" cambia el valor por defecto del campo _Hostname_ por algo más significativo, como **consuldemocracyserver** por ejemplo.
Ahora en la sección "Choose a hostname" cambie el valor por defecto por algo más significativo, como **consuldemocracyserver** por ejemplo. En la parte inferior de la página verás un resumen de tus opciones. Comprueba que todo está bien y haz clic en el botón grande verde "Crear".
![Digital Ocean hostname](../../img/digital_ocean/hostname.png) Tardará unos minutos, y al final tendrás un brillante nuevo servidor.
En la parte inferior de la página verás un resumen de tus opciones. Compruebe que todo está bien y haga clic en el botón grande verde "Crear". Lo siguiente es configurar Consul Democracy en el servidor. Por favor [lee estas instrucciones](https://github.com/consuldemocracy/installer).
![Digital Ocean create](../../img/digital_ocean/create.png)
Tardará unos minutos, y al final tendrá un brillante nuevo servidor. Se verá así en la página de Digital Ocean:
![Digital Ocean server](../../img/digital_ocean/server.png)
Lo siguiente es configurar Consul Democracy en el servidor. Por favor [leer estas instrucciones](https://github.com/consuldemocracy/installer)

View File

@@ -1,18 +1,18 @@
# Generación de claves SSH # Generación de claves SSH
Estas instrucciones le ayudarán a generar una clave pública con la que podrá conectarse al servidor sin necesidad de utilizar una contraseña. Estas instrucciones te ayudarán a generar una clave pública con la que podrás conectarte al servidor sin necesidad de utilizar una contraseña.
En la ventana del terminal, escriba: En la ventana del terminal, escribe:
```bash ```bash
ssh-keygen ssh-keygen
``` ```
Cuando se le pida el archivo en el que guardar la clave, sólo tiene que pulsar ENTER para dejar el valor predeterminado. Cuando se le pida una frase de contraseña, pulse ENTER de nuevo para dejarla vacía. Al final debería ver un mensaje como este: Cuando se te pida el archivo en el que guardar la clave, solo tienes que pulsar ENTER para dejar el valor predeterminado. Cuando se te pida una frase de contraseña, pulsa ENTER de nuevo para dejarla vacía. Al final deberías ver un mensaje como este:
```text ```text
Your identification has been saved in /your_home/.ssh/id_rsa. Your identification has been saved in /your_home/.ssh/id_rsa.
Your public key has been saved in /your_home/.ssh/id_rsa.pub. Your public key has been saved in /your_home/.ssh/id_rsa.pub.
``` ```
Tome nota de la ubicación del archivo **id_rsa.pub**, porque necesitará el contenido de este archivo más adelante. Toma nota de la ubicación del archivo **id_rsa.pub**, porque necesitarás el contenido de este archivo más adelante.

View File

@@ -1,5 +1,5 @@
# Instalador # Instalador
## Instrucciones de instalación para entornos de Producción y Pruebas ## Instrucciones de instalación para entornos de producción y pruebas
Se encuentran en el [repositorio del instalador](https://github.com/consuldemocracy/installer) Puedes encontrar las instrucciones en el [README del repositorio del instalador](https://github.com/consuldemocracy/installer).

View File

@@ -2,25 +2,18 @@
Este es un ejemplo de cómo integrar un servicio de correo con Consul Democracy. Este es un ejemplo de cómo integrar un servicio de correo con Consul Democracy.
En este ejemplo usamos [Mailgun](https://www.mailgun.com/). ## Obtener una cuenta de tu proveedor de correos de confianza
## Crear una cuenta en Mailgun Para poder configurar el correo en Consul Democracy necesitaremos:
![Creando una cuenta en Mailgun](../../img/mailserver/mailgun-create-account.png) * El _smtp_address_, que es la dirección del servidor SMTP de tu proveedor de correos (por ejemplo, smtp.tudominio.com).
* El _domain_, que es el nombre de dominio de tu aplicación.
* Puedes omitir el formulario de tarjeta de crédito * El _user_name_ y _password_, que son las credenciales que tu proveedor de correos te proporciona para autenticarte en el servidor SMTP.
* Y activa tu cuenta con el enlace enviado por correo electrónico
## Configuración del dominio
* Ve a la sección "domain": ![Mailgun sección domain](../../img/mailserver/mailgun-domains.png)
* Como todavía no tienes un dominio, debes pinchar en el "sandbox" que ya está creado
* Recuerda las siguientes credenciales: ![Mailgun sandbox](../../img/mailserver/mailgun-sandbox.png)
## Configuración del correo en Consul Democracy ## Configuración del correo en Consul Democracy
* Ve al archivo `config/secrets.yml` 1. Ve al archivo `config/secrets.yml`.
* Modifica las líneas en el archivo para configurar el servidor de correo: 2. Modifica las siguientes líneas en la sección de `staging`, `preproduction` or `production`, dependiendo de tu configuración:
```yml ```yml
mailer_delivery_method: :smtp mailer_delivery_method: :smtp
@@ -34,5 +27,5 @@ En este ejemplo usamos [Mailgun](https://www.mailgun.com/).
:enable_starttls_auto: true :enable_starttls_auto: true
``` ```
* Rellena `<smtp address>`, `<domain>`, `<user_name>` y `<password>` con tu información. 3. Rellena `<smtp address>`, `<domain>`, `<user_name>` y `<password>` con tu información.
* Guarda el fichero y reinicia tu aplicación Consul Democracy 4. Guarda el fichero y reinicia tu aplicación Consul Democracy.

View File

@@ -1,8 +1,8 @@
# Instalación manual en producción # Instalación manual en producción
**AVISO:** Recomendamos *no usar* este sistema, para el que no damos soporte oficial, ya que siempre que sea posible debe utilizarse el [instalador](https://github.com/consuldemocracy/installer). Utiliza este método si usar el instalador no es una opción y si tienes experiencia configurando PostgreSQL, puma o passenger, NGNIX y SSL (con letsencrypt, por ejemplo). **AVISO:** Recomendamos *no usar* este sistema, para el que no damos soporte oficial, ya que siempre que sea posible debe utilizarse el [instalador](https://github.com/consuldemocracy/installer). Utiliza este método solo si usar el instalador no es una opción y si tienes experiencia configurando PostgreSQL, Puma o Passenger, NGNIX y SSL (con letsencrypt, por ejemplo).
Esta guía asume que ya has [instalado todas las dependencias necesarias](prerequisites.md) en tu sistema. Esta guía asume que ya has [instalado todas las dependencias necesarias](prerequisites.md) en tu sistema. Asegúrate de instalar RVM para poder instalar la versión de ruby necesaria para el proyecto que está definida en el fichero .ruby-version y también asegúrate de instalar FNM para poder instalar la versión de node.js definida en el fichero .node-version.
La estructura de directorios que se crea a continuación está pensada para usarse con [capistrano](https://capistranorb.com/documentation/getting-started/structure/). La estructura de directorios que se crea a continuación está pensada para usarse con [capistrano](https://capistranorb.com/documentation/getting-started/structure/).
@@ -20,22 +20,24 @@ mkdir -p shared/public/assets shared/public/system shared/public/ckeditor_assets
## Versión inicial ## Versión inicial
Crea una primera carpeta en "releases" a partir del repositorio, junto con un enlace simbólico a la versión actual (sustituye `<latest_consul_stable_version>` por el número de la última versión estable de Consul Democracy, como 1.3.1 o 1.4.1): Crea una carpeta en _releases_ a partir del repositorio y luego genera un enlace simbólico a la versión actual. Asegúrate de sustituir `<latest_consul_stable_version>` por el número de la última versión estable de Consul Democracy, como 2.1.1 o 2.2.0. Para encontrar la versión más reciente, visita la sección de _releases_ en el [repositorio de Consul Democracy](https://github.com/consuldemocracy/consuldemocracy/releases):
```bash ```bash
mkdir releases/first
cd repo cd repo
git archive <latest_consul_stable_version> | tar -x -f - -C ../releases/first git archive <latest_consul_stable_version> | tar -x -f - -C ../releases/first
cd .. cd ..
ln -s releases/first current ln -s releases/first current
``` ```
## Instalación de gemas ## Instalación de dependencias
Instala las gemas de las que depende Consul Democracy: Instala las dependencias de Consul Democracy:
```bash ```bash
cd releases/first cd releases/first
bundle install --path ../../shared/bundle --without development test bundle install --path ../../shared/bundle --without development test
fnm exec npm install
cd ../.. cd ../..
``` ```
@@ -52,7 +54,7 @@ ln -s ../../../shared/config/secrets.yml
cd ../../.. cd ../../..
``` ```
Edita el fichero `shared/config/database.yml`, rellenando `username` y `password` con los datos generador durante la [configuración de PostgreSQL](debian.md#postgresql-94). Edita el fichero `shared/config/database.yml`, rellenando `username` y `password` con los datos generador durante la [configuración de PostgreSQL](debian.md#postgresql).
Ahora generamos una clave secreta: Ahora generamos una clave secreta:
@@ -77,6 +79,7 @@ Crea una base de datos, genera los datos necesarios para que la aplicación func
```bash ```bash
cd current cd current
bin/rake db:create RAILS_ENV=production
bin/rake db:migrate RAILS_ENV=production bin/rake db:migrate RAILS_ENV=production
bin/rake db:seed RAILS_ENV=production bin/rake db:seed RAILS_ENV=production
bin/rake assets:precompile RAILS_ENV=production bin/rake assets:precompile RAILS_ENV=production

View File

@@ -2,20 +2,20 @@
## Requisitos de sistema mínimos recomendados ## Requisitos de sistema mínimos recomendados
### 1. Production Server ### 1. Servidor de producción
- Distrubution: Ubuntu 16.04.X - Distribuciones compatibles: Ubuntu 22.04, Ubuntu 24.04, Debian Bullseye o Debian Bookworm
- RAM: 32GB - RAM: 32GB
- Processor: Quad core - Procesador: Quad core
- Hard Drive: 20 GB - Disco duro: 20 GB
- Database: Postgres - Base de datos: Postgres
### 2. Staging Server ### 2. Servidor de pruebas
- Distrubution: Ubuntu 16.04.X - Distribuciones compatibles: Ubuntu 22.04, Ubuntu 24.04, Debian Bullseye o Debian Bookworm
- RAM: 16GB - RAM: 16GB
- Processor: Dual core - Procesador: Dual core
- Hard Drive: 20 GB - Disco duro: 20 GB
- Database: Postgres - Base de datos: Postgres
Si tu ciudad tiene una población superior a 1.000.000, considera añadir un balanceador de carga y usar 2-3 servidores de producción, además de un servidor de base de datos dedicado. Si tu ciudad tiene una población superior a 1.000.000, considera añadir un balanceador de carga y usar 2-3 servidores de producción, además de un servidor de base de datos dedicado.

View File

@@ -0,0 +1,64 @@
# Usar AWS S3 como almacenamiento de archivos
Aunque Consul Democracy almacena la mayor parte de sus datos en una base de datos PostgreSQL, en Heroku todos los archivos como documentos o imágenes deben almacenarse en otro lugar, como puede ser AWS S3.
## Añadir la gema *aws-sdk-s3*
Añade la siguiente línea en tu *Gemfile_custom*:
```ruby
gem "aws-sdk-s3", "~> 1"
```
Y ejecuta `bundle install` para aplicar los cambios.
## Añadir tus credenciales en *secrets.yml*
Esta guía asume que tienes una cuenta de Amazon configurada para usar S3 y que has creado un _bucket_ para tu instancia de Consul Democracy. Se recomienda encarecidamente usar un _bucket_ diferente para cada instancia (producción, preproducción, staging).
Necesitarás la siguiente información:
- El **nombre** del _bucket_.
- La **región** del _bucket_ (`eu-central-1` para UE-Frankfurt, por ejemplo).
- Una **_access_key_** y un **_secret_key_** con permisos de lectura/escritura para el _bucket_.
**AVISO:** Se recomienda crear usuarios _IAM_ (Identity and Access Management) que solo tengan permisos de lectura/escritura en el _bucket_ que deseas usar para esa instancia específica de Consul Democracy.
Una vez que tengas esta información, puedes guardarla como variables de entorno de la instancia que ejecuta Consul Democracy. En este tutorial, las guardamos respectivamente como *S3_BUCKET*, *S3_REGION*, *S3_ACCESS_KEY_ID* and *S3_SECRET_ACCESS_KEY*.
```bash
heroku config:set S3_BUCKET=example-bucket-name S3_REGION=eu-west-example S3_ACCESS_KEY_ID=xxxxxxxxx S3_SECRET_ACCESS_KEY=yyyyyyyyyy
```
Ahora añade el siguiente bloque en tu fichero *secrets.yml*:
```yaml
production:
s3:
access_key_id: <%= ENV["S3_ACCESS_KEY_ID"] %>
secret_access_key: <%= ENV["S3_SECRET_ACCESS_KEY"] %>
region: <%= ENV["S3_REGION"] %>
bucket: <%= ENV["S3_BUCKET"] %>
```
## Habilitar el uso de S3 en la aplicación
Primero, agrega la siguiente línea dentro de la clase `class Application < Rails::Application` en el fichero `config/application_custom.rb`:
```ruby
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :s3
```
Luego, descomenta el bloque de **s3** que encontrarás en el fichero *storage.yml*:
```yaml
s3:
service: S3
access_key_id: <%= Rails.application.secrets.dig(:s3, :access_key_id) %>
secret_access_key: <%= Rails.application.secrets.dig(:s3, :secret_access_key) %>
region: <%= Rails.application.secrets.dig(:s3, :region) %>
bucket: <%= Rails.application.secrets.dig(:s3, :bucket) %>
```
Necesitarás reiniciar la aplicación para aplicar los cambios.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB