Utilidades
Escribiendo un servicio para un script python con ambiente virtual
1. Escribiendo el archivo .service
vim /etc/systemd/system/hipy.service
2. Gestión del Servicio
systemctl stop hipy.service
systemctl start hipy.service
systemctl daemon-reload
# systemctl status hipy.service
● hipy.service - Ejemplo de Script python en ambiente virtual como servicio
Loaded: loaded (/etc/systemd/system/hipy.service; disabled; preset: enabled)
Active: active (running) since Tue 2024-05-07 10:58:19 -05; 12min ago
Main PID: 2385 (python)
Tasks: 6 (limit: 1113)
Memory: 34.9M (peak: 35.1M)
CPU: 2.929s
CGroup: /system.slice/hipy.service
└─2385 /home/myuser/python/myEnv/bin/python /home/myuser/python/main.py
May 07 10:58:19 py systemd[1]: Started hipy.service - Ejemplo de Script python como servicio.
May 07 10:58:20 py python[2385]: INFO: Started server process [2385]
May 07 10:58:20 py python[2385]: INFO: Waiting for application startup.
May 07 10:58:20 py python[2385]: INFO: Application startup complete.
May 07 10:58:20 py python[2385]: INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)
# systemctl enable hipy.service
Created symlink /etc/systemd/system/multi-user.target.wants/hipy.service → /etc/systemd/system/hipy.service.
root@py:/etc/systemd/system# systemctl status hipy.service
● hipy.service - Ejemplo de Script python en ambiente virtual como servicio
Loaded: loaded (/etc/systemd/system/hipy.service; enabled; preset: enabled)
Active: active (running) since Tue 2024-05-07 10:58:19 -05; 14min ago
Main PID: 2385 (python)
Tasks: 6 (limit: 1113)
Memory: 34.9M (peak: 35.1M)
CPU: 3.186s
CGroup: /system.slice/hipy.service
└─2385 /home/myuser/python/myEnv/bin/python /home/myuser/python/main.py
May 07 10:58:19 py systemd[1]: Started hipy.service - Ejemplo de Script python como servicio.
May 07 10:58:20 py python[2385]: INFO: Started server process [2385]
May 07 10:58:20 py python[2385]: INFO: Waiting for application startup.
May 07 10:58:20 py python[2385]: INFO: Application startup complete.
May 07 10:58:20 py python[2385]: INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)
Servidor web nginx con host virtuales y acceso https (Ubuntu server)
1. Instalar nginx
apt install nginx
systemctl status nginx
● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: enabled)
Active: active (running) since Tue 2024-05-07 09:28:23 -05; 20min ago
Docs: man:nginx(8)
Process: 1526 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
Process: 1530 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
Main PID: 1531 (nginx)
Tasks: 2 (limit: 1113)
Memory: 1.8M (peak: 2.4M)
CPU: 40ms
CGroup: /system.slice/nginx.service
├─1531 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;"
└─1532 "nginx: worker process"
May 07 09:28:23 py systemd[1]: Starting nginx.service - A high performance web server and a reverse proxy server...
May 07 09:28:23 py systemd[1]: Started nginx.service - A high performance web server and a reverse proxy server.
2. Configurar un host virtual
2.1. Crear archivo de configuración en sites-available
vim /etc/nginx/sites-available/hi.nethuber.com
server {
listen 80; # Specify the listening port
listen [::]:80; # The same thing for IPv6
root /var/www/hi.nethuber.com/html; # The path to the website files
index index.html index.htm; # Files to display if only the domain name is specified in the address
server_name hi.nethuber.com; # Domain name of this site
location / {
try_files $uri $uri/ =404;
}
}
2.2. Crear link en sites-enabled
ln -s /etc/nginx/sites-available/hi.nethuber.com /etc/nginx/sites-enabled/
2.3. Crear el HOME del sitio web (agregar cualquier archivo index.html)
mkdir -p /var/www/hi.nethuber.com/html
chmod -R 755 /var/www
echo "<h1>Hola Mundo</h1>" > /var/www/hi.nethuber.com/html/index.html
2.4. Reiniciar nginx
systemctl restart nginx
systemctl status nginx
3. nginx como proxy server
Suponga que tenemos corriendo una aplicación python en el puerto 8080, pero ese puerto no está expuesto al público
3.1. Crear archivo de configuración en sites-available
vim /etc/nginx/sites-available/hipy.nethuber.com
server{
server_name hipy.nethuber.com;
location / {
include proxy_params;
proxy_pass http://127.0.0.1:8080;
}
}
3.2. Reiniciar nginx
systemctl restart nginx
systemctl status nginx
3.3. Aplicación python basada en FastAPI y corriendo en el puerto 8080
Cómo Configurar TIMEZONE en ubuntu
# dpkg-reconfigure tzdata
Current default time zone: 'America/Bogota'
Local time is now: Mon May 2 09:58:12 -05 2024.
Universal Time is now: Mon May 2 14:58:12 UTC 2024.
# date
Mon May 2 09:59:02 -05 2024
Cómo crear un ambiente de desarrollo y producción para python con FastApi
1. Instalando dependencias
apt install python-is-python3
apt install python3.12-venv
2. Crear ambiente virtual
python -m venv myEnv
Para activar el ambiente virtual:
en windows:
myEnv\\Scripts\activate
en Linux/macOSX:
$ source myEnv/bin/activate
(myEnv) $
Para desactivar el ambiente virtual:
$ deactivate
3. Instalar PIP (gestor de paquetes en python)
En linux:
apt install python3-pip
En Windows:
python -m pip install –upgrade pip
4. Instalamos FastAPI
pip install fastapi
Nota 1: al instalar fastapi se instala tambien uvicorn (Servidor web ASGI)
Nota 2: instalar uvicorn full: $ pip install 'uvicorn[standard]'
5. Creamos aplicación de prueba
Este es el código:
6. Desplegando la aplicación.
$ uvicorn main:app --reload --host 0.0.0.0 # en un servidor
INFO: Will watch for changes in these directories: ['/RUTA_A_LA_APP']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [5713] using WatchFiles
INFO: Started server process [5715]
INFO: Waiting for application startup.
INFO: Application startup complete.
7. Examinar estas direcciones en un navegador y observar los resultados.
http://localhost:8000/prueba
{"Hello":"World!!!"}
http://localhost:8000/
"Hello World!!!"
http://localhost:8000/otro
{"detail":"Not Found"}
8. Para un ambiente de producción:
uvicorn main:app --host [midominio.com](http://midominio.com) --ssl-certfile /etc/ssl/ssl.crt/cert.crt --ssl-keyfile /etc/ssl/ssl.key/keyDelCert.key
9. Una nota final sobre los requerimientos:
a. Crear el archivo de requerimientos:
pip freeze > requirements.txt
b. Instalar los requerimientos
pip install -r requirements.txt
10. Documentación
En un navegador abrir esta dirección (autodocumentado!):
-.-
Cómo Configurar un usuario en linux para hacer SUDO
1. Crear el usuario
# adduser myuser
info: Adding user `myuser' ...
info: Selecting UID/GID from range 1000 to 59999 ...
info: Adding new group `myuser' (1001) ...
info: Adding new user `myuser' (1001) with group `myuser (1001)' ...
info: Creating home directory `/home/myuser' ...
info: Copying files from `/etc/skel' ...
New password:
Retype new password:
passwd: password updated successfully
Changing the user information for myuser
Enter the new value, or press ENTER for the default
Full Name []:
Room Number []:
Work Phone []:
Home Phone []:
Other []:
Is the information correct? [Y/n] Y
info: Adding new user `myuser' to supplemental / extra groups `users' ...
info: Adding user `myuser' to group `users' ...
2. Agregarlo al grupo de SUDOERS
# usermod -aG sudo myuser
3. Verificar
# id myuser
uid=1001(myuser) gid=1001(myuser) groups=1001(myuser),27(sudo),100(users)