Despliegue Python
Integración con Traefik y base de datos opcional.
docker-compose.yml
Section titled “docker-compose.yml”Añadir al archivo /root/docker-compose.yml:
python-app: build: context: ./proyecto-python container_name: python-app restart: unless-stopped env_file: - ./proyecto-python/.env labels: - traefik.enable=true - traefik.http.routers.python-app.rule=Host(`python.tudominio.com`) - traefik.http.routers.python-app.tls=true - traefik.http.routers.python-app.entrypoints=web,websecure - traefik.http.routers.python-app.tls.certresolver=mytlschallenge - traefik.http.services.python-app.loadbalancer.server.port=8000Con PostgreSQL (Opcional)
Section titled “Con PostgreSQL (Opcional)”Añadir también:
postgres: image: postgres:16-alpine container_name: postgres restart: unless-stopped environment: POSTGRES_DB: myapp POSTGRES_USER: myuser POSTGRES_PASSWORD: cambiar_password_seguro volumes: - postgres_data:/var/lib/postgresql/data
volumes: postgres_data:Actualizar python-app:
python-app: build: context: ./proyecto-python container_name: python-app restart: unless-stopped depends_on: - postgres environment: - DATABASE_URL=postgresql://myuser:cambiar_password_seguro@postgres:5432/myapp labels: # ... (mismos labels)Variables de Entorno (.env)
Section titled “Variables de Entorno (.env)”Crear .env en el proyecto:
# FlaskFLASK_ENV=productionSECRET_KEY=tu_clave_secreta_aqui
# DjangoDEBUG=FalseSECRET_KEY=tu_clave_secreta_aquiALLOWED_HOSTS=python.tudominio.com,tudominio.comDATABASE_URL=postgresql://user:pass@postgres:5432/dbname
# FastAPIENVIRONMENT=productionConstruir y Desplegar
Section titled “Construir y Desplegar”cd /rootdocker compose build python-appdocker compose up -d python-app
# Con PostgreSQLdocker compose up -d postgres python-appEjecutar Migraciones (Django)
Section titled “Ejecutar Migraciones (Django)”docker exec -it python-app python manage.py migratedocker exec -it python-app python manage.py collectstatic --noinputdocker exec -it python-app python manage.py createsuperuserVerificar
Section titled “Verificar”docker compose logs -f python-appAcceder a https://python.tudominio.com.
Con IP en lugar de Dominio
Section titled “Con IP en lugar de Dominio”labels: - traefik.enable=true - traefik.http.routers.python-app.rule=PathPrefix(`/api`) - traefik.http.routers.python-app.tls=false - traefik.http.routers.python-app.entrypoints=web - traefik.http.services.python-app.loadbalancer.server.port=8000Acceder: http://TU_IP/api