Instalar docker en Ubuntu 20.x

image.png

Primero, actualice su lista de paquetes existente:

sudo apt update

A continuación, instale algunos paquetes de requisitos previos que permitan a apt usar paquetes a través de HTTPS:

sudo apt install apt-transport-https ca-certificates curl software-properties-common

Luego, añada la clave de GPG para el repositorio oficial de Docker en su sistema:

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add –

Agregue el repositorio de Docker a las fuentes de APT:

sudo add-apt-repository “deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable”

A continuación, actualice el paquete de base de datos con los paquetes de Docker del repositorio recién agregado:

sudo apt update
Asegúrese de estar a punto de realizar la instalación desde el repositorio de Docker en lugar del repositorio predeterminado de Ubuntu:
apt-cache policy docker-ce

Si bien el número de versión de Docker puede ser distinto, verá un resultado como el siguiente:

Output of apt-cache policy docker-ce
docker-ce:
Installed: (none)
Candidate: 5:19.03.9~3-0~ubuntu-focal
Version table:
5:19.03.9~3-0~ubuntu-focal 500
500 https://download.docker.com/linux/ubuntu focal/stable amd64 Packages

Observe que docker-ce no está instalado, pero la opción más viable para la instalación es del repositorio de Docker para Ubuntu 20.04 (focal).

Por último, instale Docker:

sudo apt install docker-ce

Con esto, Docker quedará instalado, el demonio se iniciará y el proceso se habilitará para ejecutarse en el inicio. Compruebe que funcione:

sudo systemctl status docker

El resultado debe ser similar al siguiente, y mostrar que el servicio está activo y en ejecución:

Output
● docker.service – Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2020-05-19 17:00:41 UTC; 17s ago
TriggeredBy: ● docker.socket
Docs: https://docs.docker.com
Main PID: 24321 (dockerd)
Tasks: 8
Memory: 46.4M
CGroup: /system.slice/docker.service
└─24321 /usr/bin/dockerd -H fd:// –containerd=/run/containerd/containerd.sock

#docker #linux #Ubuntu

Impactos: 0

Copias de seguridad de MariaDB automatizadas

 

image.png

Primero instalar el cliente de mariadb

 

apt-get install -y mariadb-client

Crear el siguiente script y hacerlo ejecutable

#!/bin/bash
pcds=/var/opt/mariadb
cds=$pcds/copia_de_seguridad_$(date +%Y%m%dT%H.%M.%S).sql
mysqldump –all-databases –lock-tables > $cds
if [ $? -eq 0 ]
then
gzip $cds
limite=$(date +%Y%m%dT%H.%M.%S -d “-7 days”)
for i in $pcds/*.sql.gz
do
if [[ ${i:36:17} < $limite ]] && [[ -e $i ]]
then
rm $i
fi
done
else
if [[ -e $cds ]]
then
rm $cds
fi
source /root/.telegram_keysURL=https://api.telegram.org/bot$TOKEN/sendMessage
message=”No se ha podido hacer la copia de seguridad”
curl -s -X POST $URL -d chat_id=$CHANNEL -d text=”$message” >/dev/null 2>&1
fi

y en el crontab crear las siguientes líneas:

30 23 * * * /mnt/mydatabasebackupscript.sh
0 4 * * * find /var/log/ -name *.gz -mtime +7 -exec rm {} \;
0 4 * * * find /mnt/copia/ -name *.gz -mtime +7 -exec rm {} \;

 

Impactos: 0

Monitoring access to Server SQUID

Monitoring On-line for command lineTo monitor any update, on-line, we can count on the parameter “-f” of the command “tail”, applying filters in accordance with its interest.

# tail -f /var/log/squid/access.log | awk ‘{print$3 ” ” $8 ” ” $7}’

192.168.0.1 wrochal http://www.linuxit.com.br/
192.168.0.1 wrochal http://www.linuxit.com.br/log.gif
192.168.0.1 wrochal http://www.linuxit.com.br/banners/linuxmall.gif
192.168.0.1 wrochal http://www.linuxit.com.br/parcerios/01.gif
192.168.0.1 wrochal http://www.linuxit.com.br/parcerios/02.gif
192.168.0.1 wrochal http://www.linuxit.com.br/parcerios/03.gif
192.168.0.1 wrochal http://www.linuxit.com.br/parcerios/04.gif
192.168.0.1 wrochal http://www.linuxit.com.br/google.html

Referencia: https://www.howtoforge.com/monitoring_squid

Impactos: 0

Enviar correos desde la línea de comandos con sSMTP y Gmail

Ubuntu

Enviar correos desde la línea de comandos con sSMTP y Gmail

Impactos: 0

Instalar DRBD

Linux

Instalar DRBD

Install DRBD:

[root@node1 ~]# yum -y install drbd84-utils kmod-drbd84
[root@node2 ~]# yum -y install drbd84-utils kmod-drbd84

Insert drbd module manually on both machines or reboot:
/sbin/modprobe drbd

Format or partition DRBD on both machines if needed
[root@node1 ~]# fdisk  /dev/sdb
[root@node2 ~]# fdisk  /dev/sdb
Example:
[root@node1 yum.repos.d]# fdisk  /dev/sdb
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel
Building a new DOS disklabel with disk identifier 0x2a0f1472.
Changes will remain in memory only, until you decide to write them.
After that, of course, the previous content won't be recoverable.
Warning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite)
Command (m for help):
you should input p to print out info

Command (m for help): p Disk /dev/sdb: 2147 MB, 2147483648 bytes 255 heads, 63 sectors/track, 261 cylinders, total 4194304 sectors Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x2a0f1472 Device Boot Start End Blocks Id System Command (m for help):
you should input n to create new partition
Command (m for help): n
Command action
e extended
p primary partition (1-4)
choose p (primary)
p primary partition (1-4)
p
Partition number (1-4):
choose 1
Partition number (1-4): 1
First sector (2048-4194303, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-4194303, default 4194303):
Using default value 4194303
Command (m for help):
input w to write change to disk
Command (m for help): w
The partition table has been altered!

Create the Distributed Replicated Block Device resource file (/etc/drbd.d/clusterdb.res):
[root@node1 ~]# vi /etc/drbd.d/clusterdb.res
File content as following
resource clusterdb {
     startup {
           wfc-timeout 30;
           outdated-wfc-timeout 20;
           degr-wfc-timeout 30;
     }
     net {
           cram-hmac-alg sha1;
           shared-secret sync_disk;
     }
     syncer {
           rate 10M;
           al-extents 257;
           on-no-data-accessible io-error;
     }
     on node1 {
           device /dev/drbd0;
           disk /dev/sdb1;
           address 192.168.1.1:7788;
           meta-disk internal;
     }
     on node2 {
           device /dev/drbd0;
           disk /dev/sdb1;
           address 192.168.1.2:7788;
           meta-disk internal;
      }
 }
Make sure that DNS resolution is working:
/etc/hosts
192.168.1.1 node1 node1.example.com
192.168.1.2 node2 node2.example.com

Set NTP server and add it to crontab on both machines:
vi/etc/crontab
 5 * * * * root ntpdate your.ntp.server

Copy DRBD configured and hosts file to node2:
 [root@node1 ~]# scp /etc/drbd.d/clusterdb.res node2:/etc/drbd.d/clusterdb.res
 [root@node1 ~]# scp /etc/hosts node2:/etc/

Initialize the DRBD meta data storage on both machines:
[root@node1 ~]# drbdadm create-md clusterdb
[root@node2 ~]# drbdadm create-md clusterdb

*****************
If the device we are trying to initialize already contains a filesystem, we’ll obtain the following error:

[root@node1 ~]# drbdadm create-md clusterdb
v08 Magic number not found
md_offset 2583687168
al_offset 2583654400
bm_offset 2583572480

Found ext3 filesystem which uses 2523136 kB
current configuration leaves usable 2523020 kB

Device size would be truncated, which
would corrupt data and result in
'access beyond end of device' errors.
You need to either
   * use external meta data (recommended)
   * shrink that filesystem first
   * zero out the device (destroy the filesystem)
Operation refused.

Command 'drbdmeta /dev/drbd1 v08 /dev/mapper/VolGroup01-LogVol00 internal create-md' terminated with exit code 40
drbdadm aborting
At this time, we have 3 options as the DRBD error correctly says.
- Put metadata on another disk/partition.
- Make the filesystem smaller so the metadata fits on the volume/partition.
- Initialize the filesystem (destroy metadata)
I have decided to use option 3, destroy metadata, so I’ll execute:
[root@node1 ~]# dd if=/dev/zero bs=1M count=1 of=/dev/mapper/VolGroup01-LogVol00; sync
1+0 records in
1+0 records out
1048576 bytes (1.0 MB) copied, 0.0104967 seconds, 99.9 MB/s
Once, we have fix this problem, we can rerun the create-md command again and get the successful message as follow
 There appears to be a v08 flexible-size internal meta data block
 already in place on /dev/sdb1 at byte offset 2146430976
 Do you really want to overwrite the existing v08 meta-data?
 [need to type 'yes' to confirm] yes
 Writing meta data...
 initializing activity log
 NOT initialized bitmap
 New drbd meta data block successfully created.
********************************Start the DRBD service on both nodes (remembering that we will be shutting it down again as it will be cluster managed):

#service  drbd  start 
   o  
   # systemctl start drbd.service

On the MASTER NODE only, promote the volume to the primary role:

Note that in DRBD versions <8.4 (e.g. 8.3) you will need to use a different command:
You can cat /proc/drbd to watch the synchronisation operation in progress:
Or, run service drbd status:
On both nodes, create the mountpoint for the DRBD-replicated volume, which in our case will be /data. It is needless to say (but I’ll say it anyway) that this volume will be only ever mounted from a single node at a time.
From the MASTER NODE, create an ext4 filesystem and mount/umount the new filesystem to test. Ensure that you use/dev/drbd0 – i.e. the DRBD device – not the backing store device:
Now, on both nodes, stop DRBD:
 You have finished the installation of DRBD. Now, you can run the following command to see two machines are synchronizing with eachother.

[root@node1 yum.repos.d]# cat /proc/drbd
 version: 8.3.16 (api:88/proto:86-97)
 GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build32R6, 2013-09-27 15:59:12
 0: cs:SyncSource ro:Primary/Secondary ds:UpToDate/Inconsistent C r-----
 ns:78848 nr:0 dw:0 dr:79520 al:0 bm:4 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:2017180
 [>....................] sync'ed: 4.0% (2017180/2096028)K
 finish: 0:02:58 speed: 11,264 (11,264) K/sec
ns:1081628 nr:0 dw:33260 dr:1048752 al:14 bm:64 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:0]
The following steps i will show you how to mount the data. In the single-primary mode you can mount data only on primary node. So you should make a node to be primary by the command
[root@node1 ~]# drbdadm primary clusterdb
you could also make a node to be secondary mode by following command:
[root@node1 ~]# drbdadm secondary clusterdb
in the primary node, at the first time of using you should format it by using ext4 system file format.
[root@node1 yum.repos.d]# mkfs.ext4 /dev/drbd0
 mke2fs 1.41.12 (17-May-2010)
 Filesystem label=
 OS type: Linux
 Block size=4096 (log=2)
 Fragment size=4096 (log=2)
 Stride=0 blocks, Stripe width=0 blocks
 131072 inodes, 524007 blocks
 26200 blocks (5.00%) reserved for the super user
 First data block=0
 Maximum filesystem blocks=536870912
 16 block groups
 32768 blocks per group, 32768 fragments per group
 8192 inodes per group
 Superblock backups stored on blocks:
 32768, 98304, 163840, 229376, 294912
You can now mount DRBD device on your primary node:
[root@node1 ~]# mkdir /data
[root@node1 ~]# mount /dev/drbd0  /data
Check:
[root@node1 ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/vg_unixmencentos65-lv_root 19G 3.6G 15G 20% /
tmpfs 1.2G 44M 1.2G 4% /dev/shm
/dev/sda1 485M 80M 380M 18% /boot
/dev/drbd0 2.0G 36M 1.9G 2% /data

http://blog.zorangagic.com/2016/02/drbd.html

Impactos: 0

Downgrade php 7.2 a 7.1 en Ubuntu 18.04 LTS

Ubuntu

Downgrade php 7.2 a 7.1 en Ubuntu 18.04 LTS


sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt-get install php7.1
sudo apt-get install php7.1-cli php7.1-common
sudo apt-get install php7.1-json php7.1-opcache 
sudo apt-get install php7.1-mysql php7.1-mbstring 
sudo apt-get install php7.1-mcrypt php7.1-zip 
sudo apt-get install php7.1-fpm php7.1-intl php7.1-simplexml
sudo a2dismod php7.2
sudo a2enmod php7.1
sudo service apache2 restart
sudo update-alternatives --set php /usr/bin/php7.1
sudo update-alternatives --set phar /usr/bin/phar7.1
sudo update-alternatives --set phar.phar /usr/bin/phar.phar7.1 
sudo update-alternatives --set phpize /usr/bin/phpize7.1
sudo update-alternatives --set php-config /usr/bin/php-config7.1

Impactos: 0

Desinstalar completamente php en ubuntu 18.04

prestashop

Desinstalar completamente php en Ubuntu 18.04

Eliminar completamente php from ubuntu 18.04 usando en una terminal el siguiente código

sudo apt-get remove –purge php*
sudo apt-get purge php*
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get remove dbconfig-php
sudo apt-get dist-upgrade

A continuación una instalación limpia.

sudo apt-get instasll php

How to Completely uninstall PHP and MySQL at ubuntu and install fresh PHP&MySQL in UBUNTU

Impactos: 0

Optimización del fichero htaccess

limpiar-html-wordpress

Optimización del fichero htaccess

      • Forzar Trailing slash

Esta mejora consiste en evitar que al final de la URL aparezca una barra. A nivel de optimización en buscadores, esto significa que los buscadores lo interpretan como una redirección 302. Para evitar esto, es recomendable implementar esta mejora en el fichero htaccess.

Aliños para la seguridad y SEO WordPress (apuntes básicos)

<IfModule mod_rewrite.c>
 RewriteCond %{REQUEST_URI} /+[^\.]+$
 RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
</IfModule>
      • Prevenir Hotlinking

Hotlinking significa que alguien está usando un hipervínculo a una imagen que está archivada en otra web, en lugar de guardar una copia física de la imagen en el servidor de la web en el que se mostrará la imagen. Esto supone un consumo de ancho de banda innecesario, que perjudica al SEO.

#Replace ?mysite\.com/ with your blog url
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mysite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
#Replace /images/nohotlink.jpg with your "don't hotlink" image url
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]
    • Mejorar el almacenamiento en cache de los ficheros

Este es probablemente el fragmento más útil de toda esta lista. Mediante el uso de algunas simples mejoras de cacheo en el fichero .htaccess, puede aumentar drásticamente la velocidad de carga de una página web.

# 1 año
 <FilesMatch "\.(ico|pdf|flv)$">
 Header set Cache-Control "max-age=29030400, public"
 </FilesMatch>
 # 1 semana
 <FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
 Header set Cache-Control "max-age=604800, public"
 </FilesMatch>
 # 2 días
 <FilesMatch "\.(xml|txt|css|js)$">
 Header set Cache-Control "max-age=172800, proxy-revalidate"
 </FilesMatch>
 # 1 minuto
 <FilesMatch "\.(html|htm|php)$">
 Header set Cache-Control "max-age=60, private, proxy-revalidate"
 </FilesMatch>						
      • Expirar caché de fichero estáticos con htaccess

Mediante esta mejora en el fichero htaccess, se inlcuye en el Header el tiempo de expiración de un determinado archivo, de este modo este no es cargado nuevamente si es que aun no ha expirado. Se consigue con ellos que no cambien comúnmente como las imágenes, vídeos, ficheros JS y CSS a los cuales podríamos agregarle headers de expiración con lo cual solo se cargarán la primera vez que accedemos a la pagina.

<IfModule mod_rewrite.c>ExpiresActive On
 ExpiresByType image/jpg "access 1 year"
 ExpiresByType image/jpeg "access 1 year"
 ExpiresByType image/gif "access 1 year"
 ExpiresByType image/png "access 1 year"
 ExpiresByType text/css "access 1 month"
 ExpiresByType application/pdf "access 1 month"
 ExpiresByType text/x-javascript "access 1 month"
 ExpiresByType application/x-shockwave-flash "access 1 month"
 ExpiresByType image/x-icon "access 1 year"
 ExpiresDefault "access 2 days"
 </IfModule>

    • Eliminar cabeceras ETags

Al eliminar la cabecera ETag, se deshabilitan las cachés de los navegadores lo que otorga la posibilidad de validar los archivos, de esta forma el navegador utiliza su Cache-Control y Expires Header para servir los ficheros. Las etiquetas de entidad (eTags) son un mecanismo para comprobar si hay una nueva versión de un archivo almacenado en caché.

<ifModule mod_headers.c>
unset ETag
</ifModule>
FileETag none

Impactos: 0

Optimizar el código HTML en WordPress

limpiar-html-wordpress
    • Optimizar el código HTML en WordPress

Implementa este código en el fichero functions.php del tema que estés utilizando para WordPress y eliminar HTML y etiquetas sin valor para el posicionamiento en buscadores

// optimizacion wordpress - delete html trush
remove_action( 'wp_head', 'wp_generator' ) ;
remove_action( 'wp_head', 'noindex', 1 ) ;
remove_action( 'wp_head', 'wlwmanifest_link' ) ;
remove_action( 'wp_head', 'rsd_link' ) ;
remove_action( 'wp_head', 'feed_links', 2 );
remove_action( 'wp_head', 'feed_links_extra', 3 );
remove_action( 'wp_head', 'parent_post_rel_link', 10, 0 );
remove_action( 'wp_head', 'start_post_rel_link', 10, 0 );
add_filter( 'pre_comment_content', 'wp_specialchars' ); 
//Disallow html in comments
remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );


/*Eliminar scripts y css de WordPress*/
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_scripts','print_emoji_detection_script');
remove_action( 'wp_print_styles', 'print_emoji_styles' );
remove_action( 'admin_print_styles', 'print_emoji_styles' );

Impactos: 0