Cómo instalar Gitea en Ubuntu 22.04

Gitea es un servicio Git gratuito, de código abierto y autoalojado. Está escrito en lenguaje GO y proporciona una forma más fácil de alojar tu propio sistema de control de versiones en Internet. Es sencillo, ligero y se puede instalar en sistemas poco potentes. Es muy similar a GitHub y GitLab y ofrece un rico conjunto de características como un editor de archivos de repositorio, seguimiento de problemas del proyecto, gestión de usuarios, notificaciones, un wiki incorporado y mucho más. Es multiplataforma y puede instalarse en los principales sistemas operativos, incluyendo Linux, macOS, Windows, ARM y arquitecturas PowerPC.

En este tutorial, te mostraremos cómo instalar el servicio Gitea Git con Nginx y Let’s Encrypt SSL en Ubuntu 22.04.

Requisitos previos

  • Un servidor con Ubuntu 22.04.
  • Un nombre de dominio válido apuntado con la IP de tu servidor.
  • Una contraseña de root configurada en tu servidor.

Cómo empezar

En primer lugar, actualiza todos los paquetes del sistema a la última versión ejecutando el siguiente comando:

apt update -y
apt upgrade -y

A continuación, instala el paquete Git ejecutando el siguiente comando:

apt-get install git -y

Una vez instalado el paquete Git, puedes pasar al siguiente paso.

Instalar y configurar MariaDB

Gitea utiliza MariaDB como base de datos. Así que tendrás que instalarlo en tu servidor. Puedes instalarlo ejecutando el siguiente comando:

apt install mariadb-server -y

Después de la instalación. Entonces, necesitarás asegurar MariaDB y establecer una contraseña de root. Puedes asegurarlo ejecutando el script mysql_secure_installation:

mysql_secure_installation

Este script establecerá la contraseña de root, eliminará los usuarios anónimos, no permitirá el inicio de sesión de root de forma remota y eliminará la base de datos de prueba, como se muestra a continuación:

Enter current password for root (enter for none):
Set root password? [Y/n]: Y
Remove anonymous users? [Y/n]: Y
Disallow root login remotely? [Y/n]: Y
Remove test database and access to it? [Y/n]:  Y
Reload privilege tables now? [Y/n]:  Y

Una vez que MariaDB esté asegurada, entra en el shell de MariaDB con el siguiente comando:

mysql -u root -p

Introduce tu contraseña de root cuando se te pida. A continuación, cambia la opción GLOBAL innodeb_file_per_table a On:

MariaDB [(none)]>SET GLOBAL innodb_file_per_table = ON;

A continuación, crea una base de datos y un usuario para Gitea con el siguiente comando:

MariaDB [(none)]>CREATE DATABASE gitea;
MariaDB [(none)]>CREATE USER 'gitea'@'localhost' IDENTIFIED BY 'password';

A continuación, concede todos los privilegios a la base de datos giteadb:

MariaDB [(none)]>GRANT ALL ON gitea.* TO 'gitea'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;

A continuación, actualiza el conjunto de caracteres de la base de datos con el siguiente comando:

MariaDB [(none)]>ALTER DATABASE gitea CHARACTER SET = utf8mb4 COLLATE utf8mb4_unicode_ci;

Por último, vacía los privilegios y sal del shell de MariaDB con el siguiente comando:

MariaDB [(none)]>FLUSH PRIVILEGES;
MariaDB [(none)]>EXIT;

A continuación, tendrás que editar el archivo de configuración por defecto de MariaDB y añadir los parámetros de InnoDB:

nano /etc/mysql/mariadb.conf.d/50-server.cnf

Añade las siguientes líneas dentro de la sección [mysqld]:

innodb_file_format = Barracuda
innodb_large_prefix = 1
innodb_default_row_format = dynamic

Guarda y cierra el archivo. A continuación, reinicia el servicio MariaDB para aplicar los cambios:

systemctl restart mariadb

En este punto, tu base de datos MariaDB está configurada. Ahora puedes pasar al siguiente paso.

Instalar y configurar Gitea

En primer lugar, visita la página de descargas de Gitea, elige la última versión y descarga el último binario de Gitea con el siguiente comando:

wget https://dl.gitea.io/gitea/1.17.1/gitea-1.17.1-linux-amd64

Una vez completada la descarga, copia el archivo descargado al directorio /usr/bin/ y dale permisos de ejecución:

cp gitea-1.17.1-linux-amd64 /usr/bin/gitea
chmod 755 /usr/bin/gitea

A continuación, crea un usuario del sistema para Gitea con el siguiente comando:

adduser --system --shell /bin/bash --group --disabled-password --home /home/git git

A continuación, crea una estructura de directorios para Gitea con el siguiente comando:

mkdir -p /etc/gitea /var/lib/gitea/{custom,data,indexers,public,log}
chown git:git /etc/gitea /var/lib/gitea/{custom,data,indexers,public,log}
chmod 750 /var/lib/gitea/{data,indexers,log}
chmod 770 /etc/gitea

Una vez que hayas terminado, puedes pasar al siguiente paso.

Crear el archivo de servicio Systemd de Gitea

A continuación, tendrás que crear un archivo de servicio systemd para gestionar el servicio Gitea con systemd. Puedes crearlo con el siguiente comando:

nano /etc/systemd/system/gitea.service

Añade las siguientes líneas:

[Unit]
Description=Gitea
After=syslog.target
After=network.target
After=mysql.service

[Service]
RestartSec=2s
Type=simple
User=git
Group=git
WorkingDirectory=/var/lib/gitea/
ExecStart=/usr/bin/gitea web -c /etc/gitea/app.ini
Restart=always
Environment=USER=git HOME=/home/git GITEA_WORK_DIR=/var/lib/gitea

[Install]
WantedBy=multi-user.target

Guarda y cierra el archivo. A continuación, recarga el demonio systemd e inicia el servicio Gitea con el siguiente comando:

systemctl daemon-reload
systemctl start gitea

Puedes comprobar el estado del servicio Gitea con el siguiente comando:

systemctl status gitea

Deberías ver la siguiente salida:

? gitea.service - Gitea
     Loaded: loaded (/etc/systemd/system/gitea.service; disabled; vendor preset: enabled)
     Active: active (running) since Sun 2022-08-21 12:19:23 UTC; 8s ago
   Main PID: 24766 (gitea)
      Tasks: 6 (limit: 2242)
     Memory: 121.2M
        CPU: 800ms
     CGroup: /system.slice/gitea.service
             ??24766 /usr/bin/gitea web -c /etc/gitea/app.ini

Aug 21 12:19:23 ubuntu2204 gitea[24766]: 2022/08/21 12:19:23 ...s/install/setting.go:21:PreloadSettings() [I] AppPath: /usr/bin/gitea
Aug 21 12:19:23 ubuntu2204 gitea[24766]: 2022/08/21 12:19:23 ...s/install/setting.go:22:PreloadSettings() [I] AppWorkPath: /var/lib/gitea
Aug 21 12:19:23 ubuntu2204 gitea[24766]: 2022/08/21 12:19:23 ...s/install/setting.go:23:PreloadSettings() [I] Custom path: /var/lib/gitea/cus>
Aug 21 12:19:23 ubuntu2204 gitea[24766]: 2022/08/21 12:19:23 ...s/install/setting.go:24:PreloadSettings() [I] Log path: /var/lib/gitea/log
Aug 21 12:19:23 ubuntu2204 gitea[24766]: 2022/08/21 12:19:23 ...s/install/setting.go:25:PreloadSettings() [I] Configuration file: /etc/gitea/>
Aug 21 12:19:23 ubuntu2204 gitea[24766]: 2022/08/21 12:19:23 ...s/install/setting.go:26:PreloadSettings() [I] Prepare to run install page
Aug 21 12:19:23 ubuntu2204 gitea[24766]: 2022/08/21 12:19:23 ...s/install/setting.go:29:PreloadSettings() [I] SQLite3 is supported
Aug 21 12:19:23 ubuntu2204 gitea[24766]: 2022/08/21 12:19:23 cmd/web.go:217:listen() [I] [630222cb-6] Listen: http://0.0.0.0:3000
Aug 21 12:19:23 ubuntu2204 gitea[24766]: 2022/08/21 12:19:23 cmd/web.go:221:listen() [I] [630222cb-6] AppURL(ROOT_URL): http://localhost:3000/
Aug 21 12:19:23 ubuntu2204 gitea[24766]: 2022/08/21 12:19:23 ...s/graceful/server.go:61:NewServer() [I] [630222cb-6] Starting new Web server:>

A continuación, activa el servicio Gitea para que se inicie al reiniciar el sistema con el siguiente comando:

systemctl enable gitea

En este punto, Gitea está iniciado y escuchando en el puerto 3000. Ahora puedes pasar al siguiente paso.

Configurar Nginx como proxy inverso para Gitea

Por defecto, Gitea escucha en el puerto 3000. Por tanto, tendrás que configurar Nginx como proxy inverso para acceder a Gitea sin especificar el puerto.

Primero, instala el servidor web Nginx ejecutando el siguiente comando:

apt-get install nginx -y

Una vez instalado, crea un nuevo archivo de configuración de host virtual Nginx para Gitea:

nano /etc/nginx/sites-available/gitea

Añade las siguientes líneas:

upstream gitea {
    server 127.0.0.1:3000;
}

server {
    listen 80;
    server_name git.example.com;
    root /var/lib/gitea/public;
    access_log off;
    error_log off;

    location / {
      try_files maintain.html $uri $uri/index.html @node;
    }

    location @node {
      client_max_body_size 0;
      proxy_pass http://localhost:3000;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header Host $http_host;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_max_temp_file_size 0;
      proxy_redirect off;
      proxy_read_timeout 120;
    }
}

Guarda y cierra el archivo. A continuación, habilita el archivo de configuración del host virtual Nginx con el siguiente comando:

ln -s /etc/nginx/sites-available/gitea /etc/nginx/sites-enabled/

Por último, reinicia el servicio Nginx y comprueba el estado del servicio Nginx con el siguiente comando:

systemctl restart nginx
systemctl status nginx

Deberías obtener la siguiente salida:

? nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2022-08-21 12:21:23 UTC; 5s ago
       Docs: man:nginx(8)
    Process: 24799 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 24800 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 24801 (nginx)
      Tasks: 2 (limit: 2242)
     Memory: 4.5M
        CPU: 44ms
     CGroup: /system.slice/nginx.service
             ??24801 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;"
             ??24802 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""

Aug 21 12:21:23 ubuntu2204 systemd[1]: Starting A high performance web server and a reverse proxy server...
Aug 21 12:21:23 ubuntu2204 systemd[1]: Started A high performance web server and a reverse proxy server.

En este punto, Nginx está configurado para servir a Gitea. Ahora puedes pasar al siguiente paso.

Asegurar Gitea con Let’s Encrypt SSL

En primer lugar, necesitarás instalar el cliente Certbot para instalar y gestionar el SSL de Let’s Encrypt en tu sistema. Puedes instalarlo ejecutando el siguiente comando:

apt-get install certbot python3-certbot-nginx -y

Una vez instalado el Certbot, ejecuta el siguiente comando para descargar e instalar el Let’s Encrypt SSL para el sitio web de Gitea.

certbot --nginx -d gitea.linuxbuz.com

Proporciona tu dirección de correo electrónico y acepta las condiciones del servicio como se muestra a continuación:

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): [email protected]

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for gitea.linuxbuz.com
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/gitea

A continuación, elige si quieres redirigir el tráfico HTTP a HTTPS como se muestra a continuación:

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2

Escribe 2 y pulsa Intro para instalar el certificado como se muestra a continuación:

Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/gitea

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://gitea.linuxbuz.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=gitea.linuxbuz.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/gitea.linuxbuz.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/gitea.linuxbuz.com/privkey.pem
   Your cert will expire on 2022-11-21. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot renew"
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

Ahora, tu sitio web de Gitea está protegido con Let’s Encrypt SSL. Ahora puedes pasar al siguiente paso.

Acceder a la interfaz web de Gitea

Ahora, abre tu navegador web y escribe la URL https://git.example.com/. Serás redirigido a la siguiente página:

Configuración de Gitea

Ajustes generales

Ajustes opcionales

Proporciona el nombre de tu base de datos Gitea, el nombre de usuario, la contraseña, la ruta del repositorio, el nombre de usuario de ejecución, el puerto de escucha, la URL de la base Gitea, la ruta del registro, el nombre de usuario y la contraseña del administrador de Gitea y haz clic en el botón Instalar Gitea. Una vez finalizada la instalación, deberías ver el panel de control de Gitea en la siguiente pantalla:

Panel de control de Gitea

Conclusión

Enhorabuena! has instalado con éxito Gitea con Nginx y Let’s Encrypt SSL en el servidor Ubuntu 22.04. Ahora puedes desplegar Gitea en tu organización y empezar a crear tu primer repositorio con Gitea. Para más información, visita la documentación de Gitea.

También te podría gustar...